@kecan0406/ttheme 1.0.1 → 1.0.2

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/bin/ttheme.js CHANGED
@@ -1,41 +1,41 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as qh}from"node:module";var Rh=Object.create;var{getPrototypeOf:yh,defineProperty:io,getOwnPropertyNames:Oh}=Object;var Lh=Object.prototype.hasOwnProperty;function Qh(n){return this[n]}var Zh,Uh,Jt=(n,r,t)=>{var e=n!=null&&typeof n==="object";if(e){var i=r?Zh??=new WeakMap:Uh??=new WeakMap,o=i.get(n);if(o)return o}t=n!=null?Rh(yh(n)):{};let s=r||!n||!n.__esModule?io(t,"default",{value:n,enumerable:!0}):t;for(let u of Oh(n))if(!Lh.call(s,u))io(s,u,{get:Qh.bind(n,u),enumerable:!0});if(e)i.set(n,s);return s};var an=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=qh(import.meta.url);var Oo=an((L0,Ut)=>{var yo=yo||function(n){return Buffer.from(n).toString("base64")};function gf(n){var r=this,t=Math.round,e=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,g,l=Array(65535),$=Array(65535),a=Array(64),w=Array(64),F=[],v=0,j=7,M=Array(64),p=Array(64),b=Array(64),K=Array(256),E=Array(2048),J,S=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],O=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Z=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],vn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kn=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function mn(m){var y=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var q=0;q<64;q++){var Q=e((y[q]*m+50)/100);if(Q<1)Q=1;else if(Q>255)Q=255;i[S[q]]=Q}var Y=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var P=0;P<64;P++){var en=e((Y[P]*m+50)/100);if(en<1)en=1;else if(en>255)en=255;o[S[P]]=en}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],In=0;for(var $n=0;$n<8;$n++)for(var I=0;I<8;I++)s[In]=1/(i[S[In]]*on[$n]*on[I]*8),u[In]=1/(o[S[In]]*on[$n]*on[I]*8),In++}function x(m,y){var q=0,Q=0,Y=[];for(var P=1;P<=16;P++){for(var en=1;en<=m[P];en++)Y[y[Q]]=[],Y[y[Q]][0]=q,Y[y[Q]][1]=P,Q++,q++;q*=2}return Y}function pn(){c=x(O,R),h=x(vn,U),f=x(A,Z),g=x(B,kn)}function sn(){var m=1,y=2;for(var q=1;q<=15;q++){for(var Q=m;Q<y;Q++)$[32767+Q]=q,l[32767+Q]=[],l[32767+Q][1]=q,l[32767+Q][0]=Q;for(var Y=-(y-1);Y<=-m;Y++)$[32767+Y]=q,l[32767+Y]=[],l[32767+Y][1]=q,l[32767+Y][0]=y-1+Y;m<<=1,y<<=1}}function nn(){for(var m=0;m<256;m++)E[m]=19595*m,E[m+256>>0]=38470*m,E[m+512>>0]=7471*m+32768,E[m+768>>0]=-11059*m,E[m+1024>>0]=-21709*m,E[m+1280>>0]=32768*m+8421375,E[m+1536>>0]=-27439*m,E[m+1792>>0]=-5329*m}function C(m){var y=m[0],q=m[1]-1;while(q>=0){if(y&1<<q)v|=1<<j;if(q--,j--,j<0){if(v==255)d(255),d(0);else d(v);j=7,v=0}}}function d(m){F.push(m)}function L(m){d(m>>8&255),d(m&255)}function hn(m,y){var q,Q,Y,P,en,on,In,$n,I=0,G,V=8,Mn=64;for(G=0;G<V;++G){q=m[I],Q=m[I+1],Y=m[I+2],P=m[I+3],en=m[I+4],on=m[I+5],In=m[I+6],$n=m[I+7];var z=q+$n,D=q-$n,gn=Q+In,W=Q-In,un=Y+on,jn=Y-on,En=P+en,qn=P-en,xn=z+En,ar=z-En,Hr=gn+un,Sr=gn-un;m[I]=xn+Hr,m[I+4]=xn-Hr;var Cr=(Sr+ar)*0.707106781;m[I+2]=ar+Cr,m[I+6]=ar-Cr,xn=qn+jn,Hr=jn+W,Sr=W+D;var Tr=(xn-Sr)*0.382683433,Ht=0.5411961*xn+Tr,_r=1.306562965*Sr+Tr,Br=Hr*0.707106781,xr=D+Br,Dr=D-Br;m[I+5]=Dr+Ht,m[I+3]=Dr-Ht,m[I+1]=xr+_r,m[I+7]=xr-_r,I+=8}I=0;for(G=0;G<V;++G){q=m[I],Q=m[I+8],Y=m[I+16],P=m[I+24],en=m[I+32],on=m[I+40],In=m[I+48],$n=m[I+56];var Pi=q+$n,me=q-$n,zi=Q+In,Ai=Q-In,Ci=Y+on,Ti=Y-on,_i=P+en,Kh=P-en,nt=Pi+_i,de=Pi-_i,St=zi+Ci,jt=zi-Ci;m[I]=nt+St,m[I+32]=nt-St;var Bi=(jt+de)*0.707106781;m[I+16]=de+Bi,m[I+48]=de-Bi,nt=Kh+Ti,St=Ti+Ai,jt=Ai+me;var xi=(nt-jt)*0.382683433,Di=0.5411961*nt+xi,no=1.306562965*jt+xi,ro=St*0.707106781,to=me+ro,eo=me-ro;m[I+40]=eo+Di,m[I+24]=eo-Di,m[I+8]=to+no,m[I+56]=to-no,I++}var Gt;for(G=0;G<Mn;++G)Gt=m[G]*y[G],a[G]=Gt>0?Gt+0.5|0:Gt-0.5|0;return a}function fn(){L(65504),L(16),d(74),d(70),d(73),d(70),d(0),d(1),d(1),d(0),L(1),L(1),d(0),d(0)}function rn(m){if(!m)return;if(L(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)L(m.length+2);else L(m.length+5+2),d(69),d(120),d(105),d(102),d(0);for(var y=0;y<m.length;y++)d(m[y])}function tn(m,y){L(65472),L(17),d(8),L(y),L(m),d(3),d(1),d(17),d(0),d(2),d(17),d(1),d(3),d(17),d(1)}function T(){L(65499),L(132),d(0);for(var m=0;m<64;m++)d(i[m]);d(1);for(var y=0;y<64;y++)d(o[y])}function H(){L(65476),L(418),d(0);for(var m=0;m<16;m++)d(O[m+1]);for(var y=0;y<=11;y++)d(R[y]);d(16);for(var q=0;q<16;q++)d(A[q+1]);for(var Q=0;Q<=161;Q++)d(Z[Q]);d(1);for(var Y=0;Y<16;Y++)d(vn[Y+1]);for(var P=0;P<=11;P++)d(U[P]);d(17);for(var en=0;en<16;en++)d(B[en+1]);for(var on=0;on<=161;on++)d(kn[on])}function N(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((y)=>{if(typeof y!=="string")return;L(65534);var q=y.length;L(q+2);var Q;for(Q=0;Q<q;Q++)d(y.charCodeAt(Q))})}function dn(){L(65498),L(12),d(3),d(1),d(0),d(2),d(17),d(3),d(17),d(0),d(63),d(0)}function X(m,y,q,Q,Y){var P=Y[0],en=Y[240],on,In=16,$n=63,I=64,G=hn(m,y);for(var V=0;V<I;++V)w[S[V]]=G[V];var Mn=w[0]-q;if(q=w[0],Mn==0)C(Q[0]);else on=32767+Mn,C(Q[$[on]]),C(l[on]);var z=63;for(;z>0&&w[z]==0;z--);if(z==0)return C(P),q;var D=1,gn;while(D<=z){var W=D;for(;w[D]==0&&D<=z;++D);var un=D-W;if(un>=In){gn=un>>4;for(var jn=1;jn<=gn;++jn)C(en);un=un&15}on=32767+w[D],C(Y[(un<<4)+$[on]]),C(l[on]),D++}if(z!=$n)C(P);return q}function _(){var m=String.fromCharCode;for(var y=0;y<256;y++)K[y]=m(y)}this.encode=function(m,y){var q=new Date().getTime();if(y)Un(y);F=[],v=0,j=7,L(65496),fn(),N(m.comments),rn(m.exifBuffer),T(),tn(m.width,m.height),H(),dn();var Q=0,Y=0,P=0;v=0,j=7,this.encode.displayName="_encode_";var{data:en,width:on,height:In}=m,$n=on*4,I=on*3,G,V=0,Mn,z,D,gn,W,un,jn,En;while(V<In){G=0;while(G<$n){gn=$n*V+G,W=gn,un=-1,jn=0;for(En=0;En<64;En++){if(jn=En>>3,un=(En&7)*4,W=gn+jn*$n+un,V+jn>=In)W-=$n*(V+1+jn-In);if(G+un>=$n)W-=G+un-$n+4;Mn=en[W++],z=en[W++],D=en[W++],M[En]=(E[Mn]+E[z+256>>0]+E[D+512>>0]>>16)-128,p[En]=(E[Mn+768>>0]+E[z+1024>>0]+E[D+1280>>0]>>16)-128,b[En]=(E[Mn+1280>>0]+E[z+1536>>0]+E[D+1792>>0]>>16)-128}Q=X(M,s,Q,c,f),Y=X(p,u,Y,h,g),P=X(b,u,P,h,g),G+=32}V+=8}if(j>=0){var qn=[];qn[1]=j+1,qn[0]=(1<<j+1)-1,C(qn)}if(L(65497),typeof Ut>"u")return new Uint8Array(F);return Buffer.from(F);var xn,ar};function Un(m){if(m<=0)m=1;if(m>100)m=100;if(J==m)return;var y=0;if(m<50)y=Math.floor(5000/m);else y=Math.floor(200-m*2);mn(y),J=m}function An(){var m=new Date().getTime();if(!n)n=50;_(),pn(),sn(),nn(),Un(n);var y=new Date().getTime()-m}An()}if(typeof Ut<"u")Ut.exports=Ro;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ro;function Ro(n,r){if(typeof r>"u")r=50;var t=new gf(r),e=t.encode(n,r);return{data:e,width:n.width,height:n.height}}});var Qo=an((Q0,Je)=>{var Ge=function(){var r=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,e=799,i=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function g(j,M){var p=0,b=[],K,E,J=16;while(J>0&&!j[J-1])J--;b.push({children:[],index:0});var S=b[0],O;for(K=0;K<J;K++){for(E=0;E<j[K];E++){S=b.pop(),S.children[S.index]=M[p];while(S.index>0){if(b.length===0)throw Error("Could not recreate Huffman Table");S=b.pop()}S.index++,b.push(S);while(b.length<=K)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O;p++}if(K+1<J)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O}return b[0].children}function l(j,M,p,b,K,E,J,S,O,R){var{precision:A,samplesPerLine:Z,scanLines:vn,mcusPerLine:U,progressive:B,maxH:kn,maxV:mn}=p,x=M,pn=0,sn=0;function nn(){if(sn>0)return sn--,pn>>sn&1;if(pn=j[M++],pn==255){var I=j[M++];if(I)throw Error("unexpected marker: "+(pn<<8|I).toString(16))}return sn=7,pn>>>7}function C(I){var G=I,V;while((V=nn())!==null){if(G=G[V],typeof G==="number")return G;if(typeof G!=="object")throw Error("invalid huffman sequence")}return null}function d(I){var G=0;while(I>0){var V=nn();if(V===null)return;G=G<<1|V,I--}return G}function L(I){var G=d(I);if(G>=1<<I-1)return G;return G+(-1<<I)+1}function hn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V);G[0]=I.pred+=Mn;var z=1;while(z<64){var D=C(I.huffmanTableAC),gn=D&15,W=D>>4;if(gn===0){if(W<15)break;z+=16;continue}z+=W;var un=r[z];G[un]=L(gn),z++}}function fn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V)<<O;G[0]=I.pred+=Mn}function rn(I,G){G[0]|=nn()<<O}var tn=0;function T(I,G){if(tn>0){tn--;return}var V=E,Mn=J;while(V<=Mn){var z=C(I.huffmanTableAC),D=z&15,gn=z>>4;if(D===0){if(gn<15){tn=d(gn)+(1<<gn)-1;break}V+=16;continue}V+=gn;var W=r[V];G[W]=L(D)*(1<<O),V++}}var H=0,N;function dn(I,G){var V=E,Mn=J,z=0;while(V<=Mn){var D=r[V],gn=G[D]<0?-1:1;switch(H){case 0:var W=C(I.huffmanTableAC),un=W&15,z=W>>4;if(un===0)if(z<15)tn=d(z)+(1<<z),H=4;else z=16,H=1;else{if(un!==1)throw Error("invalid ACn encoding");N=L(un),H=z?2:3}continue;case 1:case 2:if(G[D])G[D]+=(nn()<<O)*gn;else if(z--,z===0)H=H==2?3:0;break;case 3:if(G[D])G[D]+=(nn()<<O)*gn;else G[D]=N<<O,H=0;break;case 4:if(G[D])G[D]+=(nn()<<O)*gn;break}V++}if(H===4){if(tn--,tn===0)H=0}}function X(I,G,V,Mn,z){var D=V/U|0,gn=V%U,W=D*I.v+Mn,un=gn*I.h+z;if(I.blocks[W]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[W][un])}function _(I,G,V){var Mn=V/I.blocksPerLine|0,z=V%I.blocksPerLine;if(I.blocks[Mn]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[Mn][z])}var Un=b.length,An,m,y,q,Q,Y;if(B)if(E===0)Y=S===0?fn:rn;else Y=S===0?T:dn;else Y=hn;var P=0,en,on;if(Un==1)on=b[0].blocksPerLine*b[0].blocksPerColumn;else on=U*p.mcusPerColumn;if(!K)K=on;var In,$n;while(P<on){for(m=0;m<Un;m++)b[m].pred=0;if(tn=0,Un==1){An=b[0];for(Q=0;Q<K;Q++)_(An,Y,P),P++}else for(Q=0;Q<K;Q++){for(m=0;m<Un;m++){An=b[m],In=An.h,$n=An.v;for(y=0;y<$n;y++)for(q=0;q<In;q++)X(An,Y,P,y,q)}if(P++,P===on)break}if(P===on)do{if(j[M]===255){if(j[M+1]!==0)break}M+=1}while(M<j.length-2);if(sn=0,en=j[M]<<8|j[M+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)M+=2;else break}return M-x}function $(j,M){var p=[],b=M.blocksPerLine,K=M.blocksPerColumn,E=b<<3,J=new Int32Array(64),S=new Uint8Array(64);function O(x,pn,sn){var nn=M.quantizationTable,C,d,L,hn,fn,rn,tn,T,H,N=sn,dn;for(dn=0;dn<64;dn++)N[dn]=x[dn]*nn[dn];for(dn=0;dn<8;++dn){var X=8*dn;if(N[1+X]==0&&N[2+X]==0&&N[3+X]==0&&N[4+X]==0&&N[5+X]==0&&N[6+X]==0&&N[7+X]==0){H=c*N[0+X]+512>>10,N[0+X]=H,N[1+X]=H,N[2+X]=H,N[3+X]=H,N[4+X]=H,N[5+X]=H,N[6+X]=H,N[7+X]=H;continue}C=c*N[0+X]+128>>8,d=c*N[4+X]+128>>8,L=N[2+X],hn=N[6+X],fn=h*(N[1+X]-N[7+X])+128>>8,T=h*(N[1+X]+N[7+X])+128>>8,rn=N[3+X]<<4,tn=N[5+X]<<4,H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+128>>8,L=L*s-hn*u+128>>8,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,N[0+X]=C+T,N[7+X]=C-T,N[1+X]=d+tn,N[6+X]=d-tn,N[2+X]=L+rn,N[5+X]=L-rn,N[3+X]=hn+fn,N[4+X]=hn-fn}for(dn=0;dn<8;++dn){var _=dn;if(N[8+_]==0&&N[16+_]==0&&N[24+_]==0&&N[32+_]==0&&N[40+_]==0&&N[48+_]==0&&N[56+_]==0){H=c*sn[dn+0]+8192>>14,N[0+_]=H,N[8+_]=H,N[16+_]=H,N[24+_]=H,N[32+_]=H,N[40+_]=H,N[48+_]=H,N[56+_]=H;continue}C=c*N[0+_]+2048>>12,d=c*N[32+_]+2048>>12,L=N[16+_],hn=N[48+_],fn=h*(N[8+_]-N[56+_])+2048>>12,T=h*(N[8+_]+N[56+_])+2048>>12,rn=N[24+_],tn=N[40+_],H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+2048>>12,L=L*s-hn*u+2048>>12,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,N[0+_]=C+T,N[56+_]=C-T,N[8+_]=d+tn,N[48+_]=d-tn,N[16+_]=L+rn,N[40+_]=L-rn,N[24+_]=hn+fn,N[32+_]=hn-fn}for(dn=0;dn<64;++dn){var Un=128+(N[dn]+8>>4);pn[dn]=Un<0?0:Un>255?255:Un}}v(E*K*8);var R,A;for(var Z=0;Z<K;Z++){var vn=Z<<3;for(R=0;R<8;R++)p.push(new Uint8Array(E));for(var U=0;U<b;U++){O(M.blocks[Z][U],S,J);var B=0,kn=U<<3;for(A=0;A<8;A++){var mn=p[vn+A];for(R=0;R<8;R++)mn[kn+R]=S[B++]}}}return p}function a(j){return j<0?0:j>255?255:j}f.prototype={load:function(M){var p=new XMLHttpRequest;p.open("GET",M,!0),p.responseType="arraybuffer",p.onload=function(){var b=new Uint8Array(p.response||p.mozResponseArrayBuffer);if(this.parse(b),this.onload)this.onload()}.bind(this),p.send(null)},parse:function(M){var p=this.opts.maxResolutionInMP*1000*1000,b=0,K=M.length;function E(){var W=M[b]<<8|M[b+1];return b+=2,W}function J(){var W=E(),un=M.subarray(b,b+W-2);return b+=un.length,un}function S(W){var un=1,jn=1,En,qn;for(qn in W.components)if(W.components.hasOwnProperty(qn)){if(En=W.components[qn],un<En.h)un=En.h;if(jn<En.v)jn=En.v}var xn=Math.ceil(W.samplesPerLine/8/un),ar=Math.ceil(W.scanLines/8/jn);for(qn in W.components)if(W.components.hasOwnProperty(qn)){En=W.components[qn];var Hr=Math.ceil(Math.ceil(W.samplesPerLine/8)*En.h/un),Sr=Math.ceil(Math.ceil(W.scanLines/8)*En.v/jn),Cr=xn*En.h,Tr=ar*En.v,Ht=Tr*Cr,_r=[];v(Ht*256);for(var Br=0;Br<Tr;Br++){var xr=[];for(var Dr=0;Dr<Cr;Dr++)xr.push(new Int32Array(64));_r.push(xr)}En.blocksPerLine=Hr,En.blocksPerColumn=Sr,En.blocks=_r}W.maxH=un,W.maxV=jn,W.mcusPerLine=xn,W.mcusPerColumn=ar}var O=null,R=null,A=null,Z,vn,U=[],B=[],kn=[],mn=[],x=E(),pn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=E();while(x!=65497){var sn,nn,C;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var d=J();if(x===65534){var L=String.fromCharCode.apply(null,d);this.comments.push(L)}if(x===65504){if(d[0]===74&&d[1]===70&&d[2]===73&&d[3]===70&&d[4]===0)O={version:{major:d[5],minor:d[6]},densityUnits:d[7],xDensity:d[8]<<8|d[9],yDensity:d[10]<<8|d[11],thumbWidth:d[12],thumbHeight:d[13],thumbData:d.subarray(14,14+3*d[12]*d[13])}}if(x===65505){if(d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102&&d[4]===0)this.exifBuffer=d.subarray(5,d.length)}if(x===65518){if(d[0]===65&&d[1]===100&&d[2]===111&&d[3]===98&&d[4]===101&&d[5]===0)R={version:d[6],flags0:d[7]<<8|d[8],flags1:d[9]<<8|d[10],transformCode:d[11]}}break;case 65499:var hn=E(),fn=hn+b-2;while(b<fn){var rn=M[b++];v(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=M[b++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=E()}else throw Error("DQT: invalid table spec");U[rn&15]=tn}break;case 65472:case 65473:case 65474:E(),Z={},Z.extended=x===65473,Z.progressive=x===65474,Z.precision=M[b++],Z.scanLines=E(),Z.samplesPerLine=E(),Z.components={},Z.componentsOrder=[];var H=Z.scanLines*Z.samplesPerLine;if(H>p){var N=Math.ceil((H-p)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${N}MP`)}var dn=M[b++],X,_=0,Un=0;for(sn=0;sn<dn;sn++){X=M[b];var An=M[b+1]>>4,m=M[b+1]&15,y=M[b+2];if(An<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");Z.componentsOrder.push(X),Z.components[X]={h:An,v:m,quantizationIdx:y},b+=3}S(Z),B.push(Z);break;case 65476:var q=E();for(sn=2;sn<q;){var Q=M[b++],Y=new Uint8Array(16),P=0;for(nn=0;nn<16;nn++,b++)P+=Y[nn]=M[b];v(16+P);var en=new Uint8Array(P);for(nn=0;nn<P;nn++,b++)en[nn]=M[b];sn+=17+P,(Q>>4===0?mn:kn)[Q&15]=g(Y,en)}break;case 65501:E(),vn=E();break;case 65500:E(),E();break;case 65498:var on=E(),In=M[b++],$n=[],I;for(sn=0;sn<In;sn++){I=Z.components[M[b++]];var G=M[b++];I.huffmanTableDC=mn[G>>4],I.huffmanTableAC=kn[G&15],$n.push(I)}var V=M[b++],Mn=M[b++],z=M[b++],D=l(M,b,Z,$n,vn,V,Mn,z>>4,z&15,this.opts);b+=D;break;case 65535:if(M[b]!==255)b--;break;default:if(M[b-3]==255&&M[b-2]>=192&&M[b-2]<=254){b-=3;break}else if(x===224||x==225){if(pn!==-1)throw Error(`first unknown JPEG marker at offset ${pn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(b-1).toString(16)}`);pn=b-1;let W=E();if(M[b+W-2]===255){b+=W-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=E()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var gn=B[sn].components;for(var nn in gn)gn[nn].quantizationTable=U[gn[nn].quantizationIdx],delete gn[nn].quantizationIdx}this.width=Z.samplesPerLine,this.height=Z.scanLines,this.jfif=O,this.adobe=R,this.components=[];for(var sn=0;sn<Z.componentsOrder.length;sn++){var I=Z.components[Z.componentsOrder[sn]];this.components.push({lines:$(Z,I),scaleX:I.h/Z.maxH,scaleY:I.v/Z.maxV})}},getData:function(M,p){var b=this.width/M,K=this.height/p,E,J,S,O,R,A,Z,vn,U,B,kn=0,mn,x,pn,sn,nn,C,d,L,hn,fn,rn,tn=M*p*this.components.length;v(tn);var T=new Uint8Array(tn);switch(this.components.length){case 1:E=this.components[0];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn}break;case 2:E=this.components[0],J=this.components[1];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn,mn=A[0|U*J.scaleX*b],T[kn++]=mn}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;E=this.components[0],J=this.components[1],S=this.components[2];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K];for(U=0;U<M;U++){if(!rn)L=R[0|U*E.scaleX*b],hn=A[0|U*J.scaleX*b],fn=Z[0|U*S.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],pn=Z[0|U*S.scaleX*b],L=a(mn+1.402*(pn-128)),hn=a(mn-0.3441363*(x-128)-0.71413636*(pn-128)),fn=a(mn+1.772*(x-128));T[kn++]=L,T[kn++]=hn,T[kn++]=fn}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(rn=!1,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;E=this.components[0],J=this.components[1],S=this.components[2],O=this.components[3];for(B=0;B<p;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K],vn=O.lines[0|B*O.scaleY*K];for(U=0;U<M;U++){if(!rn)nn=R[0|U*E.scaleX*b],C=A[0|U*J.scaleX*b],d=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],pn=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b],nn=255-a(mn+1.402*(pn-128)),C=255-a(mn-0.3441363*(x-128)-0.71413636*(pn-128)),d=255-a(mn+1.772*(x-128));T[kn++]=255-nn,T[kn++]=255-C,T[kn++]=255-d,T[kn++]=255-sn}}break;default:throw Error("Unsupported color mode")}return T},copyToImageData:function(M,p){var{width:b,height:K,data:E}=M,J=this.getData(b,K),S=0,O=0,R,A,Z,vn,U,B,kn,mn,x;switch(this.components.length){case 1:for(A=0;A<K;A++)for(R=0;R<b;R++)if(Z=J[S++],E[O++]=Z,E[O++]=Z,E[O++]=Z,p)E[O++]=255;break;case 3:for(A=0;A<K;A++)for(R=0;R<b;R++)if(kn=J[S++],mn=J[S++],x=J[S++],E[O++]=kn,E[O++]=mn,E[O++]=x,p)E[O++]=255;break;case 4:for(A=0;A<K;A++)for(R=0;R<b;R++)if(U=J[S++],B=J[S++],Z=J[S++],vn=J[S++],kn=255-a(U*(1-vn/255)+vn),mn=255-a(B*(1-vn/255)+vn),x=255-a(Z*(1-vn/255)+vn),E[O++]=kn,E[O++]=mn,E[O++]=x,p)E[O++]=255;break;default:throw Error("Unsupported color mode")}}};var w=0,F=0;function v(j=0){var M=w+j;if(M>F){var p=Math.ceil((M-F)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${p}MB`)}w=M}return f.resetMaxMemoryUsage=function(j){w=0,F=j},f.getBytesAllocated=function(){return w},f.requestMemoryAllocation=v,f}();if(typeof Je<"u")Je.exports=Lo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Lo;function Lo(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},e={...t,...r},i=new Uint8Array(n),o=new Ge;o.opts=e,Ge.resetMaxMemoryUsage(e.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=e.formatAsRGBA?4:3,u=o.width*o.height*s;try{Ge.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:e.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(c,e.formatAsRGBA),c}});var Uo=an((Z0,Zo)=>{var lf=Oo(),mf=Qo();Zo.exports={encode:lf,decode:mf}});var Ke=an((U0,Wo)=>{var df=Gn("util"),qo=Gn("stream"),Cn=Wo.exports=function(){qo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};df.inherits(Cn,qo);Cn.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Cn.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(n))t=n;else t=Buffer.from(n,r||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Cn.prototype.end=function(n,r){if(n)this.write(n,r);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Cn.prototype.destroySoon=Cn.prototype.end;Cn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Cn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Cn.prototype._processReadAllowingLess=function(n){this._reads.shift();let r=this._buffers[0];if(r.length>n.length)this._buffered-=n.length,this._buffers[0]=r.slice(n.length),n.func.call(this,r.slice(0,n.length));else this._buffered-=r.length,this._buffers.shift(),n.func.call(this,r)};Cn.prototype._processRead=function(n){this._reads.shift();let r=0,t=0,e=Buffer.alloc(n.length);while(r<n.length){let i=this._buffers[t++],o=Math.min(i.length,n.length-r);if(i.copy(e,r,0,o),r+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,e)};Cn.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let n=this._reads[0];if(n.allowLess)this._processReadAllowingLess(n);else if(this._buffered>=n.length)this._processRead(n);else break}if(this._buffers&&!this.writable)this._end()}catch(n){this.emit("error",n)}}});var Re=an(($f)=>{var gr=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];$f.getImagePasses=function(n,r){let t=[],e=n%8,i=r%8,o=(n-e)/8,s=(r-i)/8;for(let u=0;u<gr.length;u++){let c=gr[u],h=o*c.x.length,f=s*c.y.length;for(let g=0;g<c.x.length;g++)if(c.x[g]<e)h++;else break;for(let g=0;g<c.y.length;g++)if(c.y[g]<i)f++;else break;if(h>0&&f>0)t.push({width:h,height:f,index:u})}return t};$f.getInterlaceIterator=function(n){return function(r,t,e){let i=r%gr[e].x.length,o=(r-i)/gr[e].x.length*8+gr[e].x[i],s=t%gr[e].y.length,u=(t-s)/gr[e].y.length*8+gr[e].y[s];return o*4+u*n*4}}});var ye=an((W0,Xo)=>{Xo.exports=function(r,t,e){let i=r+t-e,o=Math.abs(i-r),s=Math.abs(i-t),u=Math.abs(i-e);if(o<=s&&o<=u)return r;if(s<=u)return t;return e}});var Oe=an((X0,Yo)=>{var wf=Re(),Ef=ye();function Vo(n,r,t){let e=n*r;if(t!==8)e=Math.ceil(e/(8/t));return e}var Jr=Yo.exports=function(n,r){let{width:t,height:e,interlace:i,bpp:o,depth:s}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=wf.getImagePasses(t,e);for(let c=0;c<u.length;c++)this._images.push({byteWidth:Vo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:Vo(t,o,s),height:e,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Jr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Jr.prototype._unFilterType1=function(n,r,t){let e=this._xComparison,i=e-1;for(let o=0;o<t;o++){let s=n[1+o],u=o>i?r[o-e]:0;r[o]=s+u}};Jr.prototype._unFilterType2=function(n,r,t){let e=this._lastLine;for(let i=0;i<t;i++){let o=n[1+i],s=e?e[i]:0;r[i]=o+s}};Jr.prototype._unFilterType3=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Jr.prototype._unFilterType4=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=s>i&&o?o[s-e]:0,g=Ef(h,c,f);r[s]=u+g}};Jr.prototype._reverseFilterLine=function(n){let r=n[0],t,e=this._images[this._imageIndex],i=e.byteWidth;if(r===0)t=n.slice(1,i+1);else switch(t=Buffer.alloc(i),r){case 1:this._unFilterType1(n,t,i);break;case 2:this._unFilterType2(n,t,i);break;case 3:this._unFilterType3(n,t,i);break;case 4:this._unFilterType4(n,t,i);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(t),e.lineIndex++,e.lineIndex>=e.height)this._lastLine=null,this._imageIndex++,e=this._images[this._imageIndex];else this._lastLine=t;if(e)this.read(e.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ao=an((V0,zo)=>{var kf=Gn("util"),Po=Ke(),Mf=Oe(),Ff=zo.exports=function(n){Po.call(this);let r=[],t=this;this._filter=new Mf(n,{read:this.read.bind(this),write:function(e){r.push(e)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};kf.inherits(Ff,Po)});var Kr=an((Y0,Co)=>{Co.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Ze=an((P0,To)=>{var Le=[];(function(){for(let n=0;n<256;n++){let r=n;for(let t=0;t<8;t++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;Le[n]=r}})();var Qe=To.exports=function(){this._crc=-1};Qe.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=Le[(this._crc^n[r])&255]^this._crc>>>8;return!0};Qe.prototype.crc32=function(){return this._crc^-1};Qe.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=Le[(r^n[t])&255]^r>>>8;return r^-1}});var Ue=an((z0,_o)=>{var Hn=Kr(),If=Ze(),Sn=_o.exports=function(n,r){this._options=n,n.checkCRC=n.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Hn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Hn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Hn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Hn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Hn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Hn.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=r.read,this.error=r.error,this.metadata=r.metadata,this.gamma=r.gamma,this.transColor=r.transColor,this.palette=r.palette,this.parsed=r.parsed,this.inflateData=r.inflateData,this.finished=r.finished,this.simpleTransparency=r.simpleTransparency,this.headersFinished=r.headersFinished||function(){}};Sn.prototype.start=function(){this.read(Hn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Sn.prototype._parseSignature=function(n){let r=Hn.PNG_SIGNATURE;for(let t=0;t<r.length;t++)if(n[t]!==r[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e="";for(let o=4;o<8;o++)e+=String.fromCharCode(n[o]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Hn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new If,this._crc.write(Buffer.from(e)),this._chunks[t])return this._chunks[t](r);if(!i){this.error(Error("Unsupported critical chunk type "+e));return}this.read(r+4,this._skipChunk.bind(this))};Sn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Sn.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==r){this.error(Error("Crc error - "+r+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};Sn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e=n[8],i=n[9],o=n[10],s=n[11],u=n[12];if(e!==8&&e!==4&&e!==2&&e!==1&&e!==16){this.error(Error("Unsupported bit depth "+e));return}if(!(i in Hn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=Hn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:t,depth:e,interlace:Boolean(u),palette:Boolean(i&Hn.COLORTYPE_PALETTE),color:Boolean(i&Hn.COLORTYPE_COLOR),alpha:Boolean(i&Hn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Sn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};Sn.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let t=0;t<r;t++)this._palette.push([n[t*3],n[t*3+1],n[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Sn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};Sn.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Hn.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(n.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let r=0;r<n.length;r++)this._palette[r][3]=n[r];this.palette(this._palette)}if(this._colorType===Hn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Hn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};Sn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};Sn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Hn.GAMMA_DIVISION),this._handleChunkEnd()};Sn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};Sn.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Hn.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(r);let t=n-r.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};Sn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};Sn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var qe=an((jf)=>{var Bo=Re(),vf=[function(){},function(n,r,t,e){if(e===r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=255},function(n,r,t,e){if(e+1>=r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=r[e+1]},function(n,r,t,e){if(e+2>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=255},function(n,r,t,e){if(e+3>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=r[e+3]}],pf=[function(){},function(n,r,t,e){let i=r[0];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=e},function(n,r,t){let e=r[0];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=r[1]},function(n,r,t,e){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=e},function(n,r,t){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=r[3]}];function Nf(n,r){let t=[],e=0;function i(){if(e===n.length)throw Error("Ran out of data");let o=n[e];e++;let s,u,c,h,f,g,l,$;switch(r){default:throw Error("unrecognised depth");case 16:l=n[e],e++,t.push((o<<8)+l);break;case 4:l=o&15,$=o>>4,t.push($,l);break;case 2:f=o&3,g=o>>2&3,l=o>>4&3,$=o>>6&3,t.push($,l,g,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,g=o>>5&1,l=o>>6&1,$=o>>7&1,t.push($,l,g,f,h,c,u,s);break}}return{get:function(o){while(t.length<o)i();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(e!==n.length)throw Error("extra data found")}}}function Hf(n,r,t,e,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<s;f++){let g=t(f,h,c);vf[e](r,i,g,o),o+=e}return o}function Sf(n,r,t,e,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<s;f++){let g=i.get(e),l=t(f,h,c);pf[e](r,g,l,o)}i.resetAfterLine()}}jf.dataToBitMap=function(n,r){let{width:t,height:e,depth:i,bpp:o,interlace:s}=r,u;if(i!==8)u=Nf(n,i);let c;if(i<=8)c=Buffer.alloc(t*e*4);else c=new Uint16Array(t*e*4);let h=Math.pow(2,i)-1,f=0,g,l;if(s)g=Bo.getImagePasses(t,e),l=Bo.getInterlaceIterator(t,e);else{let $=0;l=function(){let a=$;return $+=4,a},g=[{width:t,height:e}]}for(let $=0;$<g.length;$++)if(i===8)f=Hf(g[$],c,l,o,n,f);else Sf(g[$],c,l,o,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var We=an((C0,xo)=>{function Jf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=i[n[o]];if(!c)throw Error("index "+n[o]+" not in palette");for(let h=0;h<4;h++)r[o+h]=c[h];o+=4}}function Kf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===n[o])c=!0}else if(i[0]===n[o]&&i[1]===n[o+1]&&i[2]===n[o+2])c=!0;if(c)for(let h=0;h<4;h++)r[o+h]=0;o+=4}}function Rf(n,r,t,e,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<e;c++)for(let h=0;h<t;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}xo.exports=function(n,r,t=!1){let{depth:e,width:i,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)Jf(n,h,i,o,c);else{if(u)Kf(n,h,i,o,u);if(e!==8&&!t){if(e===16)h=Buffer.alloc(i*o*4);Rf(n,h,i,o,e)}}return h}});var rs=an((T0,ns)=>{var yf=Gn("util"),Xe=Gn("zlib"),Do=Ke(),Of=Ao(),Lf=Ue(),Qf=qe(),Zf=We(),nr=ns.exports=function(n){Do.call(this),this._parser=new Lf(n,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=n,this.writable=!0,this._parser.start()};yf.inherits(nr,Do);nr.prototype._handleError=function(n){if(this.emit("error",n),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};nr.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Xe.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,e=Math.max(t,Xe.Z_MIN_CHUNK);this._inflate=Xe.createInflate({chunkSize:e});let i=t,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(n)};nr.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new Of(this._bitmapInfo)};nr.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};nr.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};nr.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nr.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nr.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};nr.prototype._complete=function(n){if(this.errord)return;let r;try{let t=Qf.dataToBitMap(n,this._bitmapInfo);r=Zf(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var es=an((_0,ts)=>{var Xn=Kr();ts.exports=function(n,r,t,e){let i=[Xn.COLORTYPE_COLOR_ALPHA,Xn.COLORTYPE_ALPHA].indexOf(e.colorType)!==-1;if(e.colorType===e.inputColorType){let a=function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256}();if(e.bitDepth===8||e.bitDepth===16&&a)return n}let o=e.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Xn.COLORTYPE_TO_BPP_MAP[e.inputColorType];if(u===4&&!e.inputHasAlpha)u=3;let c=Xn.COLORTYPE_TO_BPP_MAP[e.colorType];if(e.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=e.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function $(){let a,w,F,v=s;switch(e.inputColorType){case Xn.COLORTYPE_COLOR_ALPHA:v=o[f+3],a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_COLOR:a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_ALPHA:v=o[f+1],a=o[f],w=a,F=a;break;case Xn.COLORTYPE_GRAYSCALE:a=o[f],w=a,F=a;break;default:throw Error("input color type:"+e.inputColorType+" is not supported at present")}if(e.inputHasAlpha){if(!i)v/=s,a=Math.min(Math.max(Math.round((1-v)*l.red+v*a),0),s),w=Math.min(Math.max(Math.round((1-v)*l.green+v*w),0),s),F=Math.min(Math.max(Math.round((1-v)*l.blue+v*F),0),s)}return{red:a,green:w,blue:F,alpha:v}}for(let a=0;a<t;a++)for(let w=0;w<r;w++){let F=$(o,f);switch(e.colorType){case Xn.COLORTYPE_COLOR_ALPHA:case Xn.COLORTYPE_COLOR:if(e.bitDepth===8){if(h[g]=F.red,h[g+1]=F.green,h[g+2]=F.blue,i)h[g+3]=F.alpha}else if(h.writeUInt16BE(F.red,g),h.writeUInt16BE(F.green,g+2),h.writeUInt16BE(F.blue,g+4),i)h.writeUInt16BE(F.alpha,g+6);break;case Xn.COLORTYPE_ALPHA:case Xn.COLORTYPE_GRAYSCALE:{let v=(F.red+F.green+F.blue)/3;if(e.bitDepth===8){if(h[g]=v,i)h[g+1]=F.alpha}else if(h.writeUInt16BE(v,g),i)h.writeUInt16BE(F.alpha,g+2);break}default:throw Error("unrecognised color Type "+e.colorType)}f+=u,g+=c}return h}});var ss=an((B0,os)=>{var is=ye();function Uf(n,r,t,e,i){for(let o=0;o<t;o++)e[i+o]=n[r+o]}function qf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++)e+=Math.abs(n[o]);return e}function Wf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;e[i+s]=c}}function Xf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=n[r+o]-s;i+=Math.abs(u)}return i}function Vf(n,r,t,e,i){for(let o=0;o<t;o++){let s=r>0?n[r+o-t]:0,u=n[r+o]-s;e[i+o]=u}}function Yf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++){let s=r>0?n[o-t]:0,u=n[o]-s;e+=Math.abs(u)}return e}function Pf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=n[r+s]-(u+c>>1);e[i+s]=h}}function zf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=n[r+o]-(s+u>>1);i+=Math.abs(c)}return i}function Af(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=r>0&&s>=o?n[r+s-(t+o)]:0,f=n[r+s]-is(u,c,h);e[i+s]=f}}function Cf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=r>0&&o>=e?n[r+o-(t+e)]:0,h=n[r+o]-is(s,u,c);i+=Math.abs(h)}return i}var Tf={0:Uf,1:Wf,2:Vf,3:Pf,4:Af},_f={0:qf,1:Xf,2:Yf,3:zf,4:Cf};os.exports=function(n,r,t,e,i){let o;if(!("filterType"in e)||e.filterType===-1)o=[0,1,2,3,4];else if(typeof e.filterType==="number")o=[e.filterType];else throw Error("unrecognised filter types");if(e.bitDepth===16)i*=2;let s=r*i,u=0,c=0,h=Buffer.alloc((s+1)*t),f=o[0];for(let g=0;g<t;g++){if(o.length>1){let l=1/0;for(let $=0;$<o.length;$++){let a=_f[o[$]](n,c,s,i);if(a<l)f=o[$],l=a}}h[u]=f,u++,Tf[f](n,c,s,h,u,i),u+=s,c+=s}return h}});var Ve=an((x0,us)=>{var Jn=Kr(),Bf=Ze(),xf=es(),Df=ss(),ng=Gn("zlib"),lr=us.exports=function(n){if(this._options=n,n.deflateChunkSize=n.deflateChunkSize||32768,n.deflateLevel=n.deflateLevel!=null?n.deflateLevel:9,n.deflateStrategy=n.deflateStrategy!=null?n.deflateStrategy:3,n.inputHasAlpha=n.inputHasAlpha!=null?n.inputHasAlpha:!0,n.deflateFactory=n.deflateFactory||ng.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Jn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Jn.COLORTYPE_COLOR_ALPHA,[Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.inputColorType)===-1)throw Error("option input color type:"+n.inputColorType+" is not supported at present");if(n.bitDepth!==8&&n.bitDepth!==16)throw Error("option bit depth:"+n.bitDepth+" is not supported at present")};lr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};lr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};lr.prototype.filterData=function(n,r,t){let e=xf(n,r,t,this._options),i=Jn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Df(e,r,t,this._options,i)};lr.prototype._packChunk=function(n,r){let t=r?r.length:0,e=Buffer.alloc(t+12);if(e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),r)r.copy(e,8);return e.writeInt32BE(Bf.crc32(e.slice(4,e.length-4)),e.length-4),e};lr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Jn.GAMMA_DIVISION),0),this._packChunk(Jn.TYPE_gAMA,r)};lr.prototype.packIHDR=function(n,r){let t=Buffer.alloc(13);return t.writeUInt32BE(n,0),t.writeUInt32BE(r,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Jn.TYPE_IHDR,t)};lr.prototype.packIDAT=function(n){return this._packChunk(Jn.TYPE_IDAT,n)};lr.prototype.packIEND=function(){return this._packChunk(Jn.TYPE_IEND,null)}});var gs=an((D0,fs)=>{var rg=Gn("util"),cs=Gn("stream"),tg=Kr(),eg=Ve(),hs=fs.exports=function(n){cs.call(this);let r=n||{};this._packer=new eg(r),this._deflate=this._packer.createDeflate(),this.readable=!0};rg.inherits(hs,cs);hs.prototype.pack=function(n,r,t,e){if(this.emit("data",Buffer.from(tg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,t)),e)this.emit("data",this._packer.packGAMA(e));let i=this._packer.filterData(n,r,t);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var bs=an((ht,as)=>{var ls=Gn("assert").ok,Rr=Gn("zlib"),ig=Gn("util"),ms=Gn("buffer").kMaxLength;function Er(n){if(!(this instanceof Er))return new Er(n);if(n&&n.chunkSize<Rr.Z_MIN_CHUNK)n.chunkSize=Rr.Z_MIN_CHUNK;if(Rr.Inflate.call(this,n),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,n&&n.maxLength!=null)this._maxLength=n.maxLength}function og(n){return new Er(n)}function ds(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}Er.prototype._processChunk=function(n,r,t){if(typeof t==="function")return Rr.Inflate._processChunk.call(this,n,r,t);let e=this,i=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(a){f=a});function g(a,w){if(e._hadError)return;let F=o-w;if(ls(F>=0,"have should not go down"),F>0){let v=e._buffer.slice(e._offset,e._offset+F);if(e._offset+=F,v.length>s)v=v.slice(0,s);if(c.push(v),h+=v.length,s-=v.length,s===0)return!1}if(w===0||e._offset>=e._chunkSize)o=e._chunkSize,e._offset=0,e._buffer=Buffer.allocUnsafe(e._chunkSize);if(w===0)return u+=i-a,i=a,!0;return!1}ls(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=ms)throw ds(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ms.toString(16)+" bytes");let $=Buffer.concat(c,h);return ds(this),$};ig.inherits(Er,Rr.Inflate);function sg(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let t=n._finishFlushFlag;if(t==null)t=Rr.Z_FINISH;return n._processChunk(r,t)}function $s(n,r){return sg(new Er(r),n)}as.exports=ht=$s;ht.Inflate=Er;ht.createInflate=og;ht.inflateSync=$s});var Ye=an((n$,Es)=>{var ws=Es.exports=function(n){this._buffer=n,this._reads=[]};ws.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};ws.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let n=this._reads[0];if(this._buffer.length&&(this._buffer.length>=n.length||n.allowLess)){this._reads.shift();let r=this._buffer;this._buffer=r.slice(n.length),n.func.call(this,r.slice(0,n.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var ks=an((hg)=>{var ug=Ye(),cg=Oe();hg.process=function(n,r){let t=[],e=new ug(n);return new cg(r,{read:e.read.bind(e),write:function(o){t.push(o)},complete:function(){}}).start(),e.process(),Buffer.concat(t)}});var vs=an((t$,Is)=>{var Ms=!0,Fs=Gn("zlib"),gg=bs();if(!Fs.deflateSync)Ms=!1;var lg=Ye(),mg=ks(),dg=Ue(),$g=qe(),ag=We();Is.exports=function(n,r){if(!Ms)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function e(p){t=p}let i;function o(p){i=p}function s(p){i.transColor=p}function u(p){i.palette=p}function c(){i.alpha=!0}let h;function f(p){h=p}let g=[];function l(p){g.push(p)}let $=new lg(n);if(new dg(r,{read:$.read.bind($),error:e,metadata:o,gamma:f,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),$.process(),t)throw t;let w=Buffer.concat(g);g.length=0;let F;if(i.interlace)F=Fs.inflateSync(w);else{let b=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;F=gg(w,{chunkSize:b,maxLength:b})}if(w=null,!F||!F.length)throw Error("bad png - invalid inflate data response");let v=mg.process(F,i);w=null;let j=$g.dataToBitMap(v,i);v=null;let M=ag(j,i,r.skipRescale);return i.data=M,i.gamma=h||0,i}});var Ss=an((e$,Hs)=>{var ps=!0,Ns=Gn("zlib");if(!Ns.deflateSync)ps=!1;var bg=Kr(),wg=Ve();Hs.exports=function(n,r){if(!ps)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e=new wg(r||{}),i=[];if(i.push(Buffer.from(bg.PNG_SIGNATURE)),i.push(e.packIHDR(n.width,n.height)),n.gamma)i.push(e.packGAMA(n.gamma));let o=e.filterData(n.data,n.width,n.height),s=Ns.deflateSync(o,e.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(e.packIDAT(s)),i.push(e.packIEND()),Buffer.concat(i)}});var js=an((Mg)=>{var Eg=vs(),kg=Ss();Mg.read=function(n,r){return Eg(n,r||{})};Mg.write=function(n,r){return kg(n,r)}});var Js=an((Sg)=>{var vg=Gn("util"),Gs=Gn("stream"),pg=rs(),Ng=gs(),Hg=js(),Kn=Sg.PNG=function(n){if(Gs.call(this),n=n||{},this.width=n.width|0,this.height=n.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,n.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new pg(n),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(r){this.data=r,this.emit("parsed",r)}.bind(this)),this._packer=new Ng(n),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};vg.inherits(Kn,Gs);Kn.sync=Hg;Kn.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Kn.prototype.parse=function(n,r){if(r){let t,e;t=function(i){this.removeListener("error",e),this.data=i,r(null,this)}.bind(this),e=function(i){this.removeListener("parsed",t),r(i,null)}.bind(this),this.once("parsed",t),this.once("error",e)}return this.end(n),this};Kn.prototype.write=function(n){return this._parser.write(n),!0};Kn.prototype.end=function(n){this._parser.end(n)};Kn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Kn.prototype._gamma=function(n){this.gamma=n};Kn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Kn.bitblt=function(n,r,t,e,i,o,s,u){if(t|=0,e|=0,i|=0,o|=0,s|=0,u|=0,t>n.width||e>n.height||t+i>n.width||e+o>n.height)throw Error("bitblt reading outside image");if(s>r.width||u>r.height||s+i>r.width||u+o>r.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)n.data.copy(r.data,(u+c)*r.width+s<<2,(e+c)*n.width+t<<2,(e+c)*n.width+t+i<<2)};Kn.prototype.bitblt=function(n,r,t,e,i,o,s){return Kn.bitblt(this,n,r,t,e,i,o,s),this};Kn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let t=0;t<n.width;t++){let e=n.width*r+t<<2;for(let i=0;i<3;i++){let o=n.data[e+i]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[e+i]=Math.round(o*255)}}n.gamma=0}};Kn.prototype.adjustGamma=function(){Kn.adjustGamma(this)}});var pi=an((va,Kc)=>{var vi={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let t="";if(n<0)t+=`\x1B[${-n}D`;else if(n>0)t+=`\x1B[${n}C`;if(r<0)t+=`\x1B[${-r}A`;else if(r>0)t+=`\x1B[${r}B`;return t},up:(n=1)=>`\x1B[${n}A`,down:(n=1)=>`\x1B[${n}B`,forward:(n=1)=>`\x1B[${n}C`,backward:(n=1)=>`\x1B[${n}D`,nextLine:(n=1)=>"\x1B[E".repeat(n),prevLine:(n=1)=>"\x1B[F".repeat(n),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Wm={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},Xm={screen:"\x1B[2J",up:(n=1)=>"\x1B[1J".repeat(n),down:(n=1)=>"\x1B[J".repeat(n),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(n){let r="";for(let t=0;t<n;t++)r+=this.line+(t<n-1?vi.up():"");if(n)r+=vi.left;return r}};Kc.exports={cursor:vi,scroll:Wm,erase:Xm,beep:"\x07"}});import{isMainThread as Pd}from"node:worker_threads";import{parseArgs as Xd}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.1",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as Go}from"node:fs";import{basename as cf,join as ct}from"node:path";var Xh=/^#[0-9a-f]{6}$/;function oo(n){return Xh.test(n)}function On(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function er(n){let[r,t,e]=On(n).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*r+0.7152*t+0.0722*e}function br(n,r){let t=er(n),e=er(r);return(Math.max(t,e)+0.05)/(Math.min(t,e)+0.05)}function $e(n,r){return Math.round(br(n,r)*100)/100}var rt=7,so=3,ae=0.15,uo=1.6,co=[1,2,3,4,5,6,9,10,11,12,13,14],ho=[7,15];function tt(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function be(n,r,t){let e=n.background;return r.flatMap((i)=>{let o=tt(n,i);return br(o,e)<t?[`ANSI ${i} ${o} on ${e} is ${$e(o,e)}:1, needs ${t}:1`]:[]})}function fo(n,r){return Math.min(...r.map((t)=>br(tt(n,t),n.background)))}var Kt=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:rt,measure:({foreground:n,background:r})=>br(n,r),check:({foreground:n,background:r})=>br(n,r)<rt?[`foreground ${n} on ${r} is ${$e(n,r)}:1, needs ${rt}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:so,measure:(n)=>fo(n,co),check:(n)=>be(n,co,so)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ae,measure:(n)=>er(tt(n,0)),check:(n)=>{let r=tt(n,0);return er(r)>ae?[`ANSI 0 ${r} has luminance ${er(r).toFixed(3)}, needs <= ${ae}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:rt,measure:(n)=>fo(n,ho),check:(n)=>be(n,ho,rt)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:uo,measure:(n)=>br(tt(n,8),n.background),check:(n)=>be(n,[8],uo)}],Bd=Kt.map((n)=>n.rule),Rt=Kt.map(({rule:n,label:r,unit:t,min:e,max:i})=>({rule:n,label:r,unit:t,...e===void 0?{}:{min:e},...i===void 0?{}:{max:i}}));function go(n){return Kt.map((r)=>Math.round(r.measure(n)*1000)/1000)}function we(n){return Kt.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function lo(n){return n.flatMap(we)}var Vh=["black","red","green","yellow","blue","magenta","cyan","white"];function mo(n,r){return[n,...Vh.map((t,e)=>`${t} = '${r[e]}'`),""].join(`
3
- `)}var et={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...jr(n),"","[colors.primary]",`background = '${n.background}'`,`foreground = '${n.foreground}'`,"","[colors.cursor]",`cursor = '${n.cursor}'`,`text = '${n.background}'`,"","[colors.selection]",`background = '${n.selectionBackground}'`,`text = '${n.foreground}'`,"",mo("[colors.normal]",n.ansi.slice(0,8)),mo("[colors.bright]",n.ansi.slice(8,16))].join(`
2
+ import{createRequire as qh}from"node:module";var Rh=Object.create;var{getPrototypeOf:yh,defineProperty:io,getOwnPropertyNames:Oh}=Object;var Lh=Object.prototype.hasOwnProperty;function Qh(n){return this[n]}var Zh,Uh,Jt=(n,r,t)=>{var e=n!=null&&typeof n==="object";if(e){var i=r?Zh??=new WeakMap:Uh??=new WeakMap,o=i.get(n);if(o)return o}t=n!=null?Rh(yh(n)):{};let s=r||!n||!n.__esModule?io(t,"default",{value:n,enumerable:!0}):t;for(let u of Oh(n))if(!Lh.call(s,u))io(s,u,{get:Qh.bind(n,u),enumerable:!0});if(e)i.set(n,s);return s};var an=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=qh(import.meta.url);var Oo=an((L0,qt)=>{var yo=yo||function(n){return Buffer.from(n).toString("base64")};function gf(n){var r=this,t=Math.round,e=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,h,f,g,l=Array(65535),$=Array(65535),a=Array(64),w=Array(64),F=[],v=0,j=7,M=Array(64),N=Array(64),b=Array(64),K=Array(256),E=Array(2048),J,S=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],O=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Z=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],vn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],B=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],kn=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function mn(m){var y=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var q=0;q<64;q++){var Q=e((y[q]*m+50)/100);if(Q<1)Q=1;else if(Q>255)Q=255;i[S[q]]=Q}var Y=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var P=0;P<64;P++){var en=e((Y[P]*m+50)/100);if(en<1)en=1;else if(en>255)en=255;o[S[P]]=en}var on=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],In=0;for(var $n=0;$n<8;$n++)for(var I=0;I<8;I++)s[In]=1/(i[S[In]]*on[$n]*on[I]*8),u[In]=1/(o[S[In]]*on[$n]*on[I]*8),In++}function x(m,y){var q=0,Q=0,Y=[];for(var P=1;P<=16;P++){for(var en=1;en<=m[P];en++)Y[y[Q]]=[],Y[y[Q]][0]=q,Y[y[Q]][1]=P,Q++,q++;q*=2}return Y}function Nn(){c=x(O,R),h=x(vn,U),f=x(A,Z),g=x(B,kn)}function sn(){var m=1,y=2;for(var q=1;q<=15;q++){for(var Q=m;Q<y;Q++)$[32767+Q]=q,l[32767+Q]=[],l[32767+Q][1]=q,l[32767+Q][0]=Q;for(var Y=-(y-1);Y<=-m;Y++)$[32767+Y]=q,l[32767+Y]=[],l[32767+Y][1]=q,l[32767+Y][0]=y-1+Y;m<<=1,y<<=1}}function nn(){for(var m=0;m<256;m++)E[m]=19595*m,E[m+256>>0]=38470*m,E[m+512>>0]=7471*m+32768,E[m+768>>0]=-11059*m,E[m+1024>>0]=-21709*m,E[m+1280>>0]=32768*m+8421375,E[m+1536>>0]=-27439*m,E[m+1792>>0]=-5329*m}function C(m){var y=m[0],q=m[1]-1;while(q>=0){if(y&1<<q)v|=1<<j;if(q--,j--,j<0){if(v==255)d(255),d(0);else d(v);j=7,v=0}}}function d(m){F.push(m)}function L(m){d(m>>8&255),d(m&255)}function hn(m,y){var q,Q,Y,P,en,on,In,$n,I=0,G,V=8,Mn=64;for(G=0;G<V;++G){q=m[I],Q=m[I+1],Y=m[I+2],P=m[I+3],en=m[I+4],on=m[I+5],In=m[I+6],$n=m[I+7];var z=q+$n,D=q-$n,gn=Q+In,W=Q-In,un=Y+on,jn=Y-on,En=P+en,qn=P-en,xn=z+En,wr=z-En,Sr=gn+un,jr=gn-un;m[I]=xn+Sr,m[I+4]=xn-Sr;var Tr=(jr+wr)*0.707106781;m[I+2]=wr+Tr,m[I+6]=wr-Tr,xn=qn+jn,Sr=jn+W,jr=W+D;var _r=(xn-jr)*0.382683433,Ht=0.5411961*xn+_r,Br=1.306562965*jr+_r,xr=Sr*0.707106781,Dr=D+xr,nt=D-xr;m[I+5]=nt+Ht,m[I+3]=nt-Ht,m[I+1]=Dr+Br,m[I+7]=Dr-Br,I+=8}I=0;for(G=0;G<V;++G){q=m[I],Q=m[I+8],Y=m[I+16],P=m[I+24],en=m[I+32],on=m[I+40],In=m[I+48],$n=m[I+56];var Pi=q+$n,de=q-$n,zi=Q+In,Ai=Q-In,Ci=Y+on,Ti=Y-on,_i=P+en,Kh=P-en,rt=Pi+_i,$e=Pi-_i,St=zi+Ci,jt=zi-Ci;m[I]=rt+St,m[I+32]=rt-St;var Bi=(jt+$e)*0.707106781;m[I+16]=$e+Bi,m[I+48]=$e-Bi,rt=Kh+Ti,St=Ti+Ai,jt=Ai+de;var xi=(rt-jt)*0.382683433,Di=0.5411961*rt+xi,no=1.306562965*jt+xi,ro=St*0.707106781,to=de+ro,eo=de-ro;m[I+40]=eo+Di,m[I+24]=eo-Di,m[I+8]=to+no,m[I+56]=to-no,I++}var Gt;for(G=0;G<Mn;++G)Gt=m[G]*y[G],a[G]=Gt>0?Gt+0.5|0:Gt-0.5|0;return a}function fn(){L(65504),L(16),d(74),d(70),d(73),d(70),d(0),d(1),d(1),d(0),L(1),L(1),d(0),d(0)}function rn(m){if(!m)return;if(L(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)L(m.length+2);else L(m.length+5+2),d(69),d(120),d(105),d(102),d(0);for(var y=0;y<m.length;y++)d(m[y])}function tn(m,y){L(65472),L(17),d(8),L(y),L(m),d(3),d(1),d(17),d(0),d(2),d(17),d(1),d(3),d(17),d(1)}function T(){L(65499),L(132),d(0);for(var m=0;m<64;m++)d(i[m]);d(1);for(var y=0;y<64;y++)d(o[y])}function H(){L(65476),L(418),d(0);for(var m=0;m<16;m++)d(O[m+1]);for(var y=0;y<=11;y++)d(R[y]);d(16);for(var q=0;q<16;q++)d(A[q+1]);for(var Q=0;Q<=161;Q++)d(Z[Q]);d(1);for(var Y=0;Y<16;Y++)d(vn[Y+1]);for(var P=0;P<=11;P++)d(U[P]);d(17);for(var en=0;en<16;en++)d(B[en+1]);for(var on=0;on<=161;on++)d(kn[on])}function p(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((y)=>{if(typeof y!=="string")return;L(65534);var q=y.length;L(q+2);var Q;for(Q=0;Q<q;Q++)d(y.charCodeAt(Q))})}function dn(){L(65498),L(12),d(3),d(1),d(0),d(2),d(17),d(3),d(17),d(0),d(63),d(0)}function X(m,y,q,Q,Y){var P=Y[0],en=Y[240],on,In=16,$n=63,I=64,G=hn(m,y);for(var V=0;V<I;++V)w[S[V]]=G[V];var Mn=w[0]-q;if(q=w[0],Mn==0)C(Q[0]);else on=32767+Mn,C(Q[$[on]]),C(l[on]);var z=63;for(;z>0&&w[z]==0;z--);if(z==0)return C(P),q;var D=1,gn;while(D<=z){var W=D;for(;w[D]==0&&D<=z;++D);var un=D-W;if(un>=In){gn=un>>4;for(var jn=1;jn<=gn;++jn)C(en);un=un&15}on=32767+w[D],C(Y[(un<<4)+$[on]]),C(l[on]),D++}if(z!=$n)C(P);return q}function _(){var m=String.fromCharCode;for(var y=0;y<256;y++)K[y]=m(y)}this.encode=function(m,y){var q=new Date().getTime();if(y)Un(y);F=[],v=0,j=7,L(65496),fn(),p(m.comments),rn(m.exifBuffer),T(),tn(m.width,m.height),H(),dn();var Q=0,Y=0,P=0;v=0,j=7,this.encode.displayName="_encode_";var{data:en,width:on,height:In}=m,$n=on*4,I=on*3,G,V=0,Mn,z,D,gn,W,un,jn,En;while(V<In){G=0;while(G<$n){gn=$n*V+G,W=gn,un=-1,jn=0;for(En=0;En<64;En++){if(jn=En>>3,un=(En&7)*4,W=gn+jn*$n+un,V+jn>=In)W-=$n*(V+1+jn-In);if(G+un>=$n)W-=G+un-$n+4;Mn=en[W++],z=en[W++],D=en[W++],M[En]=(E[Mn]+E[z+256>>0]+E[D+512>>0]>>16)-128,N[En]=(E[Mn+768>>0]+E[z+1024>>0]+E[D+1280>>0]>>16)-128,b[En]=(E[Mn+1280>>0]+E[z+1536>>0]+E[D+1792>>0]>>16)-128}Q=X(M,s,Q,c,f),Y=X(N,u,Y,h,g),P=X(b,u,P,h,g),G+=32}V+=8}if(j>=0){var qn=[];qn[1]=j+1,qn[0]=(1<<j+1)-1,C(qn)}if(L(65497),typeof qt>"u")return new Uint8Array(F);return Buffer.from(F);var xn,wr};function Un(m){if(m<=0)m=1;if(m>100)m=100;if(J==m)return;var y=0;if(m<50)y=Math.floor(5000/m);else y=Math.floor(200-m*2);mn(y),J=m}function An(){var m=new Date().getTime();if(!n)n=50;_(),Nn(),sn(),nn(),Un(n);var y=new Date().getTime()-m}An()}if(typeof qt<"u")qt.exports=Ro;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ro;function Ro(n,r){if(typeof r>"u")r=50;var t=new gf(r),e=t.encode(n,r);return{data:e,width:n.width,height:n.height}}});var Qo=an((Q0,Je)=>{var Ge=function(){var r=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,e=799,i=3406,o=2276,s=1567,u=3784,c=5793,h=2896;function f(){}function g(j,M){var N=0,b=[],K,E,J=16;while(J>0&&!j[J-1])J--;b.push({children:[],index:0});var S=b[0],O;for(K=0;K<J;K++){for(E=0;E<j[K];E++){S=b.pop(),S.children[S.index]=M[N];while(S.index>0){if(b.length===0)throw Error("Could not recreate Huffman Table");S=b.pop()}S.index++,b.push(S);while(b.length<=K)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O;N++}if(K+1<J)b.push(O={children:[],index:0}),S.children[S.index]=O.children,S=O}return b[0].children}function l(j,M,N,b,K,E,J,S,O,R){var{precision:A,samplesPerLine:Z,scanLines:vn,mcusPerLine:U,progressive:B,maxH:kn,maxV:mn}=N,x=M,Nn=0,sn=0;function nn(){if(sn>0)return sn--,Nn>>sn&1;if(Nn=j[M++],Nn==255){var I=j[M++];if(I)throw Error("unexpected marker: "+(Nn<<8|I).toString(16))}return sn=7,Nn>>>7}function C(I){var G=I,V;while((V=nn())!==null){if(G=G[V],typeof G==="number")return G;if(typeof G!=="object")throw Error("invalid huffman sequence")}return null}function d(I){var G=0;while(I>0){var V=nn();if(V===null)return;G=G<<1|V,I--}return G}function L(I){var G=d(I);if(G>=1<<I-1)return G;return G+(-1<<I)+1}function hn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V);G[0]=I.pred+=Mn;var z=1;while(z<64){var D=C(I.huffmanTableAC),gn=D&15,W=D>>4;if(gn===0){if(W<15)break;z+=16;continue}z+=W;var un=r[z];G[un]=L(gn),z++}}function fn(I,G){var V=C(I.huffmanTableDC),Mn=V===0?0:L(V)<<O;G[0]=I.pred+=Mn}function rn(I,G){G[0]|=nn()<<O}var tn=0;function T(I,G){if(tn>0){tn--;return}var V=E,Mn=J;while(V<=Mn){var z=C(I.huffmanTableAC),D=z&15,gn=z>>4;if(D===0){if(gn<15){tn=d(gn)+(1<<gn)-1;break}V+=16;continue}V+=gn;var W=r[V];G[W]=L(D)*(1<<O),V++}}var H=0,p;function dn(I,G){var V=E,Mn=J,z=0;while(V<=Mn){var D=r[V],gn=G[D]<0?-1:1;switch(H){case 0:var W=C(I.huffmanTableAC),un=W&15,z=W>>4;if(un===0)if(z<15)tn=d(z)+(1<<z),H=4;else z=16,H=1;else{if(un!==1)throw Error("invalid ACn encoding");p=L(un),H=z?2:3}continue;case 1:case 2:if(G[D])G[D]+=(nn()<<O)*gn;else if(z--,z===0)H=H==2?3:0;break;case 3:if(G[D])G[D]+=(nn()<<O)*gn;else G[D]=p<<O,H=0;break;case 4:if(G[D])G[D]+=(nn()<<O)*gn;break}V++}if(H===4){if(tn--,tn===0)H=0}}function X(I,G,V,Mn,z){var D=V/U|0,gn=V%U,W=D*I.v+Mn,un=gn*I.h+z;if(I.blocks[W]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[W][un])}function _(I,G,V){var Mn=V/I.blocksPerLine|0,z=V%I.blocksPerLine;if(I.blocks[Mn]===void 0&&R.tolerantDecoding)return;G(I,I.blocks[Mn][z])}var Un=b.length,An,m,y,q,Q,Y;if(B)if(E===0)Y=S===0?fn:rn;else Y=S===0?T:dn;else Y=hn;var P=0,en,on;if(Un==1)on=b[0].blocksPerLine*b[0].blocksPerColumn;else on=U*N.mcusPerColumn;if(!K)K=on;var In,$n;while(P<on){for(m=0;m<Un;m++)b[m].pred=0;if(tn=0,Un==1){An=b[0];for(Q=0;Q<K;Q++)_(An,Y,P),P++}else for(Q=0;Q<K;Q++){for(m=0;m<Un;m++){An=b[m],In=An.h,$n=An.v;for(y=0;y<$n;y++)for(q=0;q<In;q++)X(An,Y,P,y,q)}if(P++,P===on)break}if(P===on)do{if(j[M]===255){if(j[M+1]!==0)break}M+=1}while(M<j.length-2);if(sn=0,en=j[M]<<8|j[M+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)M+=2;else break}return M-x}function $(j,M){var N=[],b=M.blocksPerLine,K=M.blocksPerColumn,E=b<<3,J=new Int32Array(64),S=new Uint8Array(64);function O(x,Nn,sn){var nn=M.quantizationTable,C,d,L,hn,fn,rn,tn,T,H,p=sn,dn;for(dn=0;dn<64;dn++)p[dn]=x[dn]*nn[dn];for(dn=0;dn<8;++dn){var X=8*dn;if(p[1+X]==0&&p[2+X]==0&&p[3+X]==0&&p[4+X]==0&&p[5+X]==0&&p[6+X]==0&&p[7+X]==0){H=c*p[0+X]+512>>10,p[0+X]=H,p[1+X]=H,p[2+X]=H,p[3+X]=H,p[4+X]=H,p[5+X]=H,p[6+X]=H,p[7+X]=H;continue}C=c*p[0+X]+128>>8,d=c*p[4+X]+128>>8,L=p[2+X],hn=p[6+X],fn=h*(p[1+X]-p[7+X])+128>>8,T=h*(p[1+X]+p[7+X])+128>>8,rn=p[3+X]<<4,tn=p[5+X]<<4,H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+128>>8,L=L*s-hn*u+128>>8,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,p[0+X]=C+T,p[7+X]=C-T,p[1+X]=d+tn,p[6+X]=d-tn,p[2+X]=L+rn,p[5+X]=L-rn,p[3+X]=hn+fn,p[4+X]=hn-fn}for(dn=0;dn<8;++dn){var _=dn;if(p[8+_]==0&&p[16+_]==0&&p[24+_]==0&&p[32+_]==0&&p[40+_]==0&&p[48+_]==0&&p[56+_]==0){H=c*sn[dn+0]+8192>>14,p[0+_]=H,p[8+_]=H,p[16+_]=H,p[24+_]=H,p[32+_]=H,p[40+_]=H,p[48+_]=H,p[56+_]=H;continue}C=c*p[0+_]+2048>>12,d=c*p[32+_]+2048>>12,L=p[16+_],hn=p[48+_],fn=h*(p[8+_]-p[56+_])+2048>>12,T=h*(p[8+_]+p[56+_])+2048>>12,rn=p[24+_],tn=p[40+_],H=C-d+1>>1,C=C+d+1>>1,d=H,H=L*u+hn*s+2048>>12,L=L*s-hn*u+2048>>12,hn=H,H=fn-tn+1>>1,fn=fn+tn+1>>1,tn=H,H=T+rn+1>>1,rn=T-rn+1>>1,T=H,H=C-hn+1>>1,C=C+hn+1>>1,hn=H,H=d-L+1>>1,d=d+L+1>>1,L=H,H=fn*o+T*i+2048>>12,fn=fn*i-T*o+2048>>12,T=H,H=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=H,p[0+_]=C+T,p[56+_]=C-T,p[8+_]=d+tn,p[48+_]=d-tn,p[16+_]=L+rn,p[40+_]=L-rn,p[24+_]=hn+fn,p[32+_]=hn-fn}for(dn=0;dn<64;++dn){var Un=128+(p[dn]+8>>4);Nn[dn]=Un<0?0:Un>255?255:Un}}v(E*K*8);var R,A;for(var Z=0;Z<K;Z++){var vn=Z<<3;for(R=0;R<8;R++)N.push(new Uint8Array(E));for(var U=0;U<b;U++){O(M.blocks[Z][U],S,J);var B=0,kn=U<<3;for(A=0;A<8;A++){var mn=N[vn+A];for(R=0;R<8;R++)mn[kn+R]=S[B++]}}}return N}function a(j){return j<0?0:j>255?255:j}f.prototype={load:function(M){var N=new XMLHttpRequest;N.open("GET",M,!0),N.responseType="arraybuffer",N.onload=function(){var b=new Uint8Array(N.response||N.mozResponseArrayBuffer);if(this.parse(b),this.onload)this.onload()}.bind(this),N.send(null)},parse:function(M){var N=this.opts.maxResolutionInMP*1000*1000,b=0,K=M.length;function E(){var W=M[b]<<8|M[b+1];return b+=2,W}function J(){var W=E(),un=M.subarray(b,b+W-2);return b+=un.length,un}function S(W){var un=1,jn=1,En,qn;for(qn in W.components)if(W.components.hasOwnProperty(qn)){if(En=W.components[qn],un<En.h)un=En.h;if(jn<En.v)jn=En.v}var xn=Math.ceil(W.samplesPerLine/8/un),wr=Math.ceil(W.scanLines/8/jn);for(qn in W.components)if(W.components.hasOwnProperty(qn)){En=W.components[qn];var Sr=Math.ceil(Math.ceil(W.samplesPerLine/8)*En.h/un),jr=Math.ceil(Math.ceil(W.scanLines/8)*En.v/jn),Tr=xn*En.h,_r=wr*En.v,Ht=_r*Tr,Br=[];v(Ht*256);for(var xr=0;xr<_r;xr++){var Dr=[];for(var nt=0;nt<Tr;nt++)Dr.push(new Int32Array(64));Br.push(Dr)}En.blocksPerLine=Sr,En.blocksPerColumn=jr,En.blocks=Br}W.maxH=un,W.maxV=jn,W.mcusPerLine=xn,W.mcusPerColumn=wr}var O=null,R=null,A=null,Z,vn,U=[],B=[],kn=[],mn=[],x=E(),Nn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=E();while(x!=65497){var sn,nn,C;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var d=J();if(x===65534){var L=String.fromCharCode.apply(null,d);this.comments.push(L)}if(x===65504){if(d[0]===74&&d[1]===70&&d[2]===73&&d[3]===70&&d[4]===0)O={version:{major:d[5],minor:d[6]},densityUnits:d[7],xDensity:d[8]<<8|d[9],yDensity:d[10]<<8|d[11],thumbWidth:d[12],thumbHeight:d[13],thumbData:d.subarray(14,14+3*d[12]*d[13])}}if(x===65505){if(d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102&&d[4]===0)this.exifBuffer=d.subarray(5,d.length)}if(x===65518){if(d[0]===65&&d[1]===100&&d[2]===111&&d[3]===98&&d[4]===101&&d[5]===0)R={version:d[6],flags0:d[7]<<8|d[8],flags1:d[9]<<8|d[10],transformCode:d[11]}}break;case 65499:var hn=E(),fn=hn+b-2;while(b<fn){var rn=M[b++];v(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=M[b++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var T=r[nn];tn[T]=E()}else throw Error("DQT: invalid table spec");U[rn&15]=tn}break;case 65472:case 65473:case 65474:E(),Z={},Z.extended=x===65473,Z.progressive=x===65474,Z.precision=M[b++],Z.scanLines=E(),Z.samplesPerLine=E(),Z.components={},Z.componentsOrder=[];var H=Z.scanLines*Z.samplesPerLine;if(H>N){var p=Math.ceil((H-N)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${p}MP`)}var dn=M[b++],X,_=0,Un=0;for(sn=0;sn<dn;sn++){X=M[b];var An=M[b+1]>>4,m=M[b+1]&15,y=M[b+2];if(An<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");Z.componentsOrder.push(X),Z.components[X]={h:An,v:m,quantizationIdx:y},b+=3}S(Z),B.push(Z);break;case 65476:var q=E();for(sn=2;sn<q;){var Q=M[b++],Y=new Uint8Array(16),P=0;for(nn=0;nn<16;nn++,b++)P+=Y[nn]=M[b];v(16+P);var en=new Uint8Array(P);for(nn=0;nn<P;nn++,b++)en[nn]=M[b];sn+=17+P,(Q>>4===0?mn:kn)[Q&15]=g(Y,en)}break;case 65501:E(),vn=E();break;case 65500:E(),E();break;case 65498:var on=E(),In=M[b++],$n=[],I;for(sn=0;sn<In;sn++){I=Z.components[M[b++]];var G=M[b++];I.huffmanTableDC=mn[G>>4],I.huffmanTableAC=kn[G&15],$n.push(I)}var V=M[b++],Mn=M[b++],z=M[b++],D=l(M,b,Z,$n,vn,V,Mn,z>>4,z&15,this.opts);b+=D;break;case 65535:if(M[b]!==255)b--;break;default:if(M[b-3]==255&&M[b-2]>=192&&M[b-2]<=254){b-=3;break}else if(x===224||x==225){if(Nn!==-1)throw Error(`first unknown JPEG marker at offset ${Nn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(b-1).toString(16)}`);Nn=b-1;let W=E();if(M[b+W-2]===255){b+=W-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=E()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var sn=0;sn<B.length;sn++){var gn=B[sn].components;for(var nn in gn)gn[nn].quantizationTable=U[gn[nn].quantizationIdx],delete gn[nn].quantizationIdx}this.width=Z.samplesPerLine,this.height=Z.scanLines,this.jfif=O,this.adobe=R,this.components=[];for(var sn=0;sn<Z.componentsOrder.length;sn++){var I=Z.components[Z.componentsOrder[sn]];this.components.push({lines:$(Z,I),scaleX:I.h/Z.maxH,scaleY:I.v/Z.maxV})}},getData:function(M,N){var b=this.width/M,K=this.height/N,E,J,S,O,R,A,Z,vn,U,B,kn=0,mn,x,Nn,sn,nn,C,d,L,hn,fn,rn,tn=M*N*this.components.length;v(tn);var T=new Uint8Array(tn);switch(this.components.length){case 1:E=this.components[0];for(B=0;B<N;B++){R=E.lines[0|B*E.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn}break;case 2:E=this.components[0],J=this.components[1];for(B=0;B<N;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K];for(U=0;U<M;U++)mn=R[0|U*E.scaleX*b],T[kn++]=mn,mn=A[0|U*J.scaleX*b],T[kn++]=mn}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;E=this.components[0],J=this.components[1],S=this.components[2];for(B=0;B<N;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K];for(U=0;U<M;U++){if(!rn)L=R[0|U*E.scaleX*b],hn=A[0|U*J.scaleX*b],fn=Z[0|U*S.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],Nn=Z[0|U*S.scaleX*b],L=a(mn+1.402*(Nn-128)),hn=a(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),fn=a(mn+1.772*(x-128));T[kn++]=L,T[kn++]=hn,T[kn++]=fn}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(rn=!1,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;E=this.components[0],J=this.components[1],S=this.components[2],O=this.components[3];for(B=0;B<N;B++){R=E.lines[0|B*E.scaleY*K],A=J.lines[0|B*J.scaleY*K],Z=S.lines[0|B*S.scaleY*K],vn=O.lines[0|B*O.scaleY*K];for(U=0;U<M;U++){if(!rn)nn=R[0|U*E.scaleX*b],C=A[0|U*J.scaleX*b],d=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b];else mn=R[0|U*E.scaleX*b],x=A[0|U*J.scaleX*b],Nn=Z[0|U*S.scaleX*b],sn=vn[0|U*O.scaleX*b],nn=255-a(mn+1.402*(Nn-128)),C=255-a(mn-0.3441363*(x-128)-0.71413636*(Nn-128)),d=255-a(mn+1.772*(x-128));T[kn++]=255-nn,T[kn++]=255-C,T[kn++]=255-d,T[kn++]=255-sn}}break;default:throw Error("Unsupported color mode")}return T},copyToImageData:function(M,N){var{width:b,height:K,data:E}=M,J=this.getData(b,K),S=0,O=0,R,A,Z,vn,U,B,kn,mn,x;switch(this.components.length){case 1:for(A=0;A<K;A++)for(R=0;R<b;R++)if(Z=J[S++],E[O++]=Z,E[O++]=Z,E[O++]=Z,N)E[O++]=255;break;case 3:for(A=0;A<K;A++)for(R=0;R<b;R++)if(kn=J[S++],mn=J[S++],x=J[S++],E[O++]=kn,E[O++]=mn,E[O++]=x,N)E[O++]=255;break;case 4:for(A=0;A<K;A++)for(R=0;R<b;R++)if(U=J[S++],B=J[S++],Z=J[S++],vn=J[S++],kn=255-a(U*(1-vn/255)+vn),mn=255-a(B*(1-vn/255)+vn),x=255-a(Z*(1-vn/255)+vn),E[O++]=kn,E[O++]=mn,E[O++]=x,N)E[O++]=255;break;default:throw Error("Unsupported color mode")}}};var w=0,F=0;function v(j=0){var M=w+j;if(M>F){var N=Math.ceil((M-F)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${N}MB`)}w=M}return f.resetMaxMemoryUsage=function(j){w=0,F=j},f.getBytesAllocated=function(){return w},f.requestMemoryAllocation=v,f}();if(typeof Je<"u")Je.exports=Lo;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Lo;function Lo(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},e={...t,...r},i=new Uint8Array(n),o=new Ge;o.opts=e,Ge.resetMaxMemoryUsage(e.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=e.formatAsRGBA?4:3,u=o.width*o.height*s;try{Ge.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:e.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(c,e.formatAsRGBA),c}});var Uo=an((Z0,Zo)=>{var lf=Oo(),mf=Qo();Zo.exports={encode:lf,decode:mf}});var Ke=an((U0,Wo)=>{var df=Gn("util"),qo=Gn("stream"),Cn=Wo.exports=function(){qo.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};df.inherits(Cn,qo);Cn.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Cn.prototype.write=function(n,r){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(n))t=n;else t=Buffer.from(n,r||this._encoding);if(this._buffers.push(t),this._buffered+=t.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Cn.prototype.end=function(n,r){if(n)this.write(n,r);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Cn.prototype.destroySoon=Cn.prototype.end;Cn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Cn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Cn.prototype._processReadAllowingLess=function(n){this._reads.shift();let r=this._buffers[0];if(r.length>n.length)this._buffered-=n.length,this._buffers[0]=r.slice(n.length),n.func.call(this,r.slice(0,n.length));else this._buffered-=r.length,this._buffers.shift(),n.func.call(this,r)};Cn.prototype._processRead=function(n){this._reads.shift();let r=0,t=0,e=Buffer.alloc(n.length);while(r<n.length){let i=this._buffers[t++],o=Math.min(i.length,n.length-r);if(i.copy(e,r,0,o),r+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,e)};Cn.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let n=this._reads[0];if(n.allowLess)this._processReadAllowingLess(n);else if(this._buffered>=n.length)this._processRead(n);else break}if(this._buffers&&!this.writable)this._end()}catch(n){this.emit("error",n)}}});var Re=an(($f)=>{var mr=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];$f.getImagePasses=function(n,r){let t=[],e=n%8,i=r%8,o=(n-e)/8,s=(r-i)/8;for(let u=0;u<mr.length;u++){let c=mr[u],h=o*c.x.length,f=s*c.y.length;for(let g=0;g<c.x.length;g++)if(c.x[g]<e)h++;else break;for(let g=0;g<c.y.length;g++)if(c.y[g]<i)f++;else break;if(h>0&&f>0)t.push({width:h,height:f,index:u})}return t};$f.getInterlaceIterator=function(n){return function(r,t,e){let i=r%mr[e].x.length,o=(r-i)/mr[e].x.length*8+mr[e].x[i],s=t%mr[e].y.length,u=(t-s)/mr[e].y.length*8+mr[e].y[s];return o*4+u*n*4}}});var ye=an((W0,Xo)=>{Xo.exports=function(r,t,e){let i=r+t-e,o=Math.abs(i-r),s=Math.abs(i-t),u=Math.abs(i-e);if(o<=s&&o<=u)return r;if(s<=u)return t;return e}});var Oe=an((X0,Yo)=>{var wf=Re(),Ef=ye();function Vo(n,r,t){let e=n*r;if(t!==8)e=Math.ceil(e/(8/t));return e}var Kr=Yo.exports=function(n,r){let{width:t,height:e,interlace:i,bpp:o,depth:s}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=wf.getImagePasses(t,e);for(let c=0;c<u.length;c++)this._images.push({byteWidth:Vo(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:Vo(t,o,s),height:e,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Kr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Kr.prototype._unFilterType1=function(n,r,t){let e=this._xComparison,i=e-1;for(let o=0;o<t;o++){let s=n[1+o],u=o>i?r[o-e]:0;r[o]=s+u}};Kr.prototype._unFilterType2=function(n,r,t){let e=this._lastLine;for(let i=0;i<t;i++){let o=n[1+i],s=e?e[i]:0;r[i]=o+s}};Kr.prototype._unFilterType3=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=Math.floor((h+c)/2);r[s]=u+f}};Kr.prototype._unFilterType4=function(n,r,t){let e=this._xComparison,i=e-1,o=this._lastLine;for(let s=0;s<t;s++){let u=n[1+s],c=o?o[s]:0,h=s>i?r[s-e]:0,f=s>i&&o?o[s-e]:0,g=Ef(h,c,f);r[s]=u+g}};Kr.prototype._reverseFilterLine=function(n){let r=n[0],t,e=this._images[this._imageIndex],i=e.byteWidth;if(r===0)t=n.slice(1,i+1);else switch(t=Buffer.alloc(i),r){case 1:this._unFilterType1(n,t,i);break;case 2:this._unFilterType2(n,t,i);break;case 3:this._unFilterType3(n,t,i);break;case 4:this._unFilterType4(n,t,i);break;default:throw Error("Unrecognised filter type - "+r)}if(this.write(t),e.lineIndex++,e.lineIndex>=e.height)this._lastLine=null,this._imageIndex++,e=this._images[this._imageIndex];else this._lastLine=t;if(e)this.read(e.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ao=an((V0,zo)=>{var kf=Gn("util"),Po=Ke(),Mf=Oe(),Ff=zo.exports=function(n){Po.call(this);let r=[],t=this;this._filter=new Mf(n,{read:this.read.bind(this),write:function(e){r.push(e)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};kf.inherits(Ff,Po)});var Rr=an((Y0,Co)=>{Co.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var Ze=an((P0,To)=>{var Le=[];(function(){for(let n=0;n<256;n++){let r=n;for(let t=0;t<8;t++)if(r&1)r=3988292384^r>>>1;else r=r>>>1;Le[n]=r}})();var Qe=To.exports=function(){this._crc=-1};Qe.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=Le[(this._crc^n[r])&255]^this._crc>>>8;return!0};Qe.prototype.crc32=function(){return this._crc^-1};Qe.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=Le[(r^n[t])&255]^r>>>8;return r^-1}});var Ue=an((z0,_o)=>{var Hn=Rr(),If=Ze(),Sn=_o.exports=function(n,r){this._options=n,n.checkCRC=n.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Hn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Hn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Hn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Hn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Hn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Hn.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=r.read,this.error=r.error,this.metadata=r.metadata,this.gamma=r.gamma,this.transColor=r.transColor,this.palette=r.palette,this.parsed=r.parsed,this.inflateData=r.inflateData,this.finished=r.finished,this.simpleTransparency=r.simpleTransparency,this.headersFinished=r.headersFinished||function(){}};Sn.prototype.start=function(){this.read(Hn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Sn.prototype._parseSignature=function(n){let r=Hn.PNG_SIGNATURE;for(let t=0;t<r.length;t++)if(n[t]!==r[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e="";for(let o=4;o<8;o++)e+=String.fromCharCode(n[o]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Hn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new If,this._crc.write(Buffer.from(e)),this._chunks[t])return this._chunks[t](r);if(!i){this.error(Error("Unsupported critical chunk type "+e));return}this.read(r+4,this._skipChunk.bind(this))};Sn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Sn.prototype._parseChunkEnd=function(n){let r=n.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==r){this.error(Error("Crc error - "+r+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Sn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};Sn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e=n[8],i=n[9],o=n[10],s=n[11],u=n[12];if(e!==8&&e!==4&&e!==2&&e!==1&&e!==16){this.error(Error("Unsupported bit depth "+e));return}if(!(i in Hn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(u!==0&&u!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=Hn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:t,depth:e,interlace:Boolean(u),palette:Boolean(i&Hn.COLORTYPE_PALETTE),color:Boolean(i&Hn.COLORTYPE_COLOR),alpha:Boolean(i&Hn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Sn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};Sn.prototype._parsePLTE=function(n){this._crc.write(n);let r=Math.floor(n.length/3);for(let t=0;t<r;t++)this._palette.push([n[t*3],n[t*3+1],n[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Sn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};Sn.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Hn.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(n.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let r=0;r<n.length;r++)this._palette[r][3]=n[r];this.palette(this._palette)}if(this._colorType===Hn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Hn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};Sn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};Sn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Hn.GAMMA_DIVISION),this._handleChunkEnd()};Sn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};Sn.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Hn.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(r);let t=n-r.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};Sn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};Sn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var qe=an((jf)=>{var Bo=Re(),vf=[function(){},function(n,r,t,e){if(e===r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=255},function(n,r,t,e){if(e+1>=r.length)throw Error("Ran out of data");let i=r[e];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=r[e+1]},function(n,r,t,e){if(e+2>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=255},function(n,r,t,e){if(e+3>=r.length)throw Error("Ran out of data");n[t]=r[e],n[t+1]=r[e+1],n[t+2]=r[e+2],n[t+3]=r[e+3]}],Nf=[function(){},function(n,r,t,e){let i=r[0];n[t]=i,n[t+1]=i,n[t+2]=i,n[t+3]=e},function(n,r,t){let e=r[0];n[t]=e,n[t+1]=e,n[t+2]=e,n[t+3]=r[1]},function(n,r,t,e){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=e},function(n,r,t){n[t]=r[0],n[t+1]=r[1],n[t+2]=r[2],n[t+3]=r[3]}];function pf(n,r){let t=[],e=0;function i(){if(e===n.length)throw Error("Ran out of data");let o=n[e];e++;let s,u,c,h,f,g,l,$;switch(r){default:throw Error("unrecognised depth");case 16:l=n[e],e++,t.push((o<<8)+l);break;case 4:l=o&15,$=o>>4,t.push($,l);break;case 2:f=o&3,g=o>>2&3,l=o>>4&3,$=o>>6&3,t.push($,l,g,f);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,h=o>>3&1,f=o>>4&1,g=o>>5&1,l=o>>6&1,$=o>>7&1,t.push($,l,g,f,h,c,u,s);break}}return{get:function(o){while(t.length<o)i();let s=t.slice(0,o);return t=t.slice(o),s},resetAfterLine:function(){t.length=0},end:function(){if(e!==n.length)throw Error("extra data found")}}}function Hf(n,r,t,e,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<s;f++){let g=t(f,h,c);vf[e](r,i,g,o),o+=e}return o}function Sf(n,r,t,e,i,o){let{width:s,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<s;f++){let g=i.get(e),l=t(f,h,c);Nf[e](r,g,l,o)}i.resetAfterLine()}}jf.dataToBitMap=function(n,r){let{width:t,height:e,depth:i,bpp:o,interlace:s}=r,u;if(i!==8)u=pf(n,i);let c;if(i<=8)c=Buffer.alloc(t*e*4);else c=new Uint16Array(t*e*4);let h=Math.pow(2,i)-1,f=0,g,l;if(s)g=Bo.getImagePasses(t,e),l=Bo.getInterlaceIterator(t,e);else{let $=0;l=function(){let a=$;return $+=4,a},g=[{width:t,height:e}]}for(let $=0;$<g.length;$++)if(i===8)f=Hf(g[$],c,l,o,n,f);else Sf(g[$],c,l,o,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var We=an((C0,xo)=>{function Jf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=i[n[o]];if(!c)throw Error("index "+n[o]+" not in palette");for(let h=0;h<4;h++)r[o+h]=c[h];o+=4}}function Kf(n,r,t,e,i){let o=0;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===n[o])c=!0}else if(i[0]===n[o]&&i[1]===n[o+1]&&i[2]===n[o+2])c=!0;if(c)for(let h=0;h<4;h++)r[o+h]=0;o+=4}}function Rf(n,r,t,e,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<e;c++)for(let h=0;h<t;h++){for(let f=0;f<4;f++)r[u+f]=Math.floor(n[u+f]*o/s+0.5);u+=4}}xo.exports=function(n,r,t=!1){let{depth:e,width:i,height:o,colorType:s,transColor:u,palette:c}=r,h=n;if(s===3)Jf(n,h,i,o,c);else{if(u)Kf(n,h,i,o,u);if(e!==8&&!t){if(e===16)h=Buffer.alloc(i*o*4);Rf(n,h,i,o,e)}}return h}});var rs=an((T0,ns)=>{var yf=Gn("util"),Xe=Gn("zlib"),Do=Ke(),Of=Ao(),Lf=Ue(),Qf=qe(),Zf=We(),nr=ns.exports=function(n){Do.call(this),this._parser=new Lf(n,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=n,this.writable=!0,this._parser.start()};yf.inherits(nr,Do);nr.prototype._handleError=function(n){if(this.emit("error",n),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};nr.prototype._inflateData=function(n){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Xe.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let t=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,e=Math.max(t,Xe.Z_MIN_CHUNK);this._inflate=Xe.createInflate({chunkSize:e});let i=t,o=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;o(u)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(u){if(!i)return;if(u.length>i)u=u.slice(0,i);i-=u.length,s(u)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(n)};nr.prototype._handleMetaData=function(n){this._metaData=n,this._bitmapInfo=Object.create(n),this._filter=new Of(this._bitmapInfo)};nr.prototype._handleTransColor=function(n){this._bitmapInfo.transColor=n};nr.prototype._handlePalette=function(n){this._bitmapInfo.palette=n};nr.prototype._simpleTransparency=function(){this._metaData.alpha=!0};nr.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};nr.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};nr.prototype._complete=function(n){if(this.errord)return;let r;try{let t=Qf.dataToBitMap(n,this._bitmapInfo);r=Zf(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var es=an((_0,ts)=>{var Xn=Rr();ts.exports=function(n,r,t,e){let i=[Xn.COLORTYPE_COLOR_ALPHA,Xn.COLORTYPE_ALPHA].indexOf(e.colorType)!==-1;if(e.colorType===e.inputColorType){let a=function(){let w=new ArrayBuffer(2);return new DataView(w).setInt16(0,256,!0),new Int16Array(w)[0]!==256}();if(e.bitDepth===8||e.bitDepth===16&&a)return n}let o=e.bitDepth!==16?n:new Uint16Array(n.buffer),s=255,u=Xn.COLORTYPE_TO_BPP_MAP[e.inputColorType];if(u===4&&!e.inputHasAlpha)u=3;let c=Xn.COLORTYPE_TO_BPP_MAP[e.colorType];if(e.bitDepth===16)s=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=e.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function $(){let a,w,F,v=s;switch(e.inputColorType){case Xn.COLORTYPE_COLOR_ALPHA:v=o[f+3],a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_COLOR:a=o[f],w=o[f+1],F=o[f+2];break;case Xn.COLORTYPE_ALPHA:v=o[f+1],a=o[f],w=a,F=a;break;case Xn.COLORTYPE_GRAYSCALE:a=o[f],w=a,F=a;break;default:throw Error("input color type:"+e.inputColorType+" is not supported at present")}if(e.inputHasAlpha){if(!i)v/=s,a=Math.min(Math.max(Math.round((1-v)*l.red+v*a),0),s),w=Math.min(Math.max(Math.round((1-v)*l.green+v*w),0),s),F=Math.min(Math.max(Math.round((1-v)*l.blue+v*F),0),s)}return{red:a,green:w,blue:F,alpha:v}}for(let a=0;a<t;a++)for(let w=0;w<r;w++){let F=$(o,f);switch(e.colorType){case Xn.COLORTYPE_COLOR_ALPHA:case Xn.COLORTYPE_COLOR:if(e.bitDepth===8){if(h[g]=F.red,h[g+1]=F.green,h[g+2]=F.blue,i)h[g+3]=F.alpha}else if(h.writeUInt16BE(F.red,g),h.writeUInt16BE(F.green,g+2),h.writeUInt16BE(F.blue,g+4),i)h.writeUInt16BE(F.alpha,g+6);break;case Xn.COLORTYPE_ALPHA:case Xn.COLORTYPE_GRAYSCALE:{let v=(F.red+F.green+F.blue)/3;if(e.bitDepth===8){if(h[g]=v,i)h[g+1]=F.alpha}else if(h.writeUInt16BE(v,g),i)h.writeUInt16BE(F.alpha,g+2);break}default:throw Error("unrecognised color Type "+e.colorType)}f+=u,g+=c}return h}});var ss=an((B0,os)=>{var is=ye();function Uf(n,r,t,e,i){for(let o=0;o<t;o++)e[i+o]=n[r+o]}function qf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++)e+=Math.abs(n[o]);return e}function Wf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=n[r+s]-u;e[i+s]=c}}function Xf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=n[r+o]-s;i+=Math.abs(u)}return i}function Vf(n,r,t,e,i){for(let o=0;o<t;o++){let s=r>0?n[r+o-t]:0,u=n[r+o]-s;e[i+o]=u}}function Yf(n,r,t){let e=0,i=r+t;for(let o=r;o<i;o++){let s=r>0?n[o-t]:0,u=n[o]-s;e+=Math.abs(u)}return e}function Pf(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=n[r+s]-(u+c>>1);e[i+s]=h}}function zf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=n[r+o]-(s+u>>1);i+=Math.abs(c)}return i}function Af(n,r,t,e,i,o){for(let s=0;s<t;s++){let u=s>=o?n[r+s-o]:0,c=r>0?n[r+s-t]:0,h=r>0&&s>=o?n[r+s-(t+o)]:0,f=n[r+s]-is(u,c,h);e[i+s]=f}}function Cf(n,r,t,e){let i=0;for(let o=0;o<t;o++){let s=o>=e?n[r+o-e]:0,u=r>0?n[r+o-t]:0,c=r>0&&o>=e?n[r+o-(t+e)]:0,h=n[r+o]-is(s,u,c);i+=Math.abs(h)}return i}var Tf={0:Uf,1:Wf,2:Vf,3:Pf,4:Af},_f={0:qf,1:Xf,2:Yf,3:zf,4:Cf};os.exports=function(n,r,t,e,i){let o;if(!("filterType"in e)||e.filterType===-1)o=[0,1,2,3,4];else if(typeof e.filterType==="number")o=[e.filterType];else throw Error("unrecognised filter types");if(e.bitDepth===16)i*=2;let s=r*i,u=0,c=0,h=Buffer.alloc((s+1)*t),f=o[0];for(let g=0;g<t;g++){if(o.length>1){let l=1/0;for(let $=0;$<o.length;$++){let a=_f[o[$]](n,c,s,i);if(a<l)f=o[$],l=a}}h[u]=f,u++,Tf[f](n,c,s,h,u,i),u+=s,c+=s}return h}});var Ve=an((x0,us)=>{var Jn=Rr(),Bf=Ze(),xf=es(),Df=ss(),ng=Gn("zlib"),dr=us.exports=function(n){if(this._options=n,n.deflateChunkSize=n.deflateChunkSize||32768,n.deflateLevel=n.deflateLevel!=null?n.deflateLevel:9,n.deflateStrategy=n.deflateStrategy!=null?n.deflateStrategy:3,n.inputHasAlpha=n.inputHasAlpha!=null?n.inputHasAlpha:!0,n.deflateFactory=n.deflateFactory||ng.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Jn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Jn.COLORTYPE_COLOR_ALPHA,[Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Jn.COLORTYPE_GRAYSCALE,Jn.COLORTYPE_COLOR,Jn.COLORTYPE_COLOR_ALPHA,Jn.COLORTYPE_ALPHA].indexOf(n.inputColorType)===-1)throw Error("option input color type:"+n.inputColorType+" is not supported at present");if(n.bitDepth!==8&&n.bitDepth!==16)throw Error("option bit depth:"+n.bitDepth+" is not supported at present")};dr.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};dr.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};dr.prototype.filterData=function(n,r,t){let e=xf(n,r,t,this._options),i=Jn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Df(e,r,t,this._options,i)};dr.prototype._packChunk=function(n,r){let t=r?r.length:0,e=Buffer.alloc(t+12);if(e.writeUInt32BE(t,0),e.writeUInt32BE(n,4),r)r.copy(e,8);return e.writeInt32BE(Bf.crc32(e.slice(4,e.length-4)),e.length-4),e};dr.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Jn.GAMMA_DIVISION),0),this._packChunk(Jn.TYPE_gAMA,r)};dr.prototype.packIHDR=function(n,r){let t=Buffer.alloc(13);return t.writeUInt32BE(n,0),t.writeUInt32BE(r,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Jn.TYPE_IHDR,t)};dr.prototype.packIDAT=function(n){return this._packChunk(Jn.TYPE_IDAT,n)};dr.prototype.packIEND=function(){return this._packChunk(Jn.TYPE_IEND,null)}});var gs=an((D0,fs)=>{var rg=Gn("util"),cs=Gn("stream"),tg=Rr(),eg=Ve(),hs=fs.exports=function(n){cs.call(this);let r=n||{};this._packer=new eg(r),this._deflate=this._packer.createDeflate(),this.readable=!0};rg.inherits(hs,cs);hs.prototype.pack=function(n,r,t,e){if(this.emit("data",Buffer.from(tg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(r,t)),e)this.emit("data",this._packer.packGAMA(e));let i=this._packer.filterData(n,r,t);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var bs=an((ht,as)=>{var ls=Gn("assert").ok,yr=Gn("zlib"),ig=Gn("util"),ms=Gn("buffer").kMaxLength;function kr(n){if(!(this instanceof kr))return new kr(n);if(n&&n.chunkSize<yr.Z_MIN_CHUNK)n.chunkSize=yr.Z_MIN_CHUNK;if(yr.Inflate.call(this,n),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,n&&n.maxLength!=null)this._maxLength=n.maxLength}function og(n){return new kr(n)}function ds(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}kr.prototype._processChunk=function(n,r,t){if(typeof t==="function")return yr.Inflate._processChunk.call(this,n,r,t);let e=this,i=n&&n.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(a){f=a});function g(a,w){if(e._hadError)return;let F=o-w;if(ls(F>=0,"have should not go down"),F>0){let v=e._buffer.slice(e._offset,e._offset+F);if(e._offset+=F,v.length>s)v=v.slice(0,s);if(c.push(v),h+=v.length,s-=v.length,s===0)return!1}if(w===0||e._offset>=e._chunkSize)o=e._chunkSize,e._offset=0,e._buffer=Buffer.allocUnsafe(e._chunkSize);if(w===0)return u+=i-a,i=a,!0;return!1}ls(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=ms)throw ds(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ms.toString(16)+" bytes");let $=Buffer.concat(c,h);return ds(this),$};ig.inherits(kr,yr.Inflate);function sg(n,r){if(typeof r==="string")r=Buffer.from(r);if(!(r instanceof Buffer))throw TypeError("Not a string or buffer");let t=n._finishFlushFlag;if(t==null)t=yr.Z_FINISH;return n._processChunk(r,t)}function $s(n,r){return sg(new kr(r),n)}as.exports=ht=$s;ht.Inflate=kr;ht.createInflate=og;ht.inflateSync=$s});var Ye=an((n$,Es)=>{var ws=Es.exports=function(n){this._buffer=n,this._reads=[]};ws.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};ws.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let n=this._reads[0];if(this._buffer.length&&(this._buffer.length>=n.length||n.allowLess)){this._reads.shift();let r=this._buffer;this._buffer=r.slice(n.length),n.func.call(this,r.slice(0,n.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var ks=an((hg)=>{var ug=Ye(),cg=Oe();hg.process=function(n,r){let t=[],e=new ug(n);return new cg(r,{read:e.read.bind(e),write:function(o){t.push(o)},complete:function(){}}).start(),e.process(),Buffer.concat(t)}});var vs=an((t$,Is)=>{var Ms=!0,Fs=Gn("zlib"),gg=bs();if(!Fs.deflateSync)Ms=!1;var lg=Ye(),mg=ks(),dg=Ue(),$g=qe(),ag=We();Is.exports=function(n,r){if(!Ms)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function e(N){t=N}let i;function o(N){i=N}function s(N){i.transColor=N}function u(N){i.palette=N}function c(){i.alpha=!0}let h;function f(N){h=N}let g=[];function l(N){g.push(N)}let $=new lg(n);if(new dg(r,{read:$.read.bind($),error:e,metadata:o,gamma:f,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),$.process(),t)throw t;let w=Buffer.concat(g);g.length=0;let F;if(i.interlace)F=Fs.inflateSync(w);else{let b=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;F=gg(w,{chunkSize:b,maxLength:b})}if(w=null,!F||!F.length)throw Error("bad png - invalid inflate data response");let v=mg.process(F,i);w=null;let j=$g.dataToBitMap(v,i);v=null;let M=ag(j,i,r.skipRescale);return i.data=M,i.gamma=h||0,i}});var Ss=an((e$,Hs)=>{var Ns=!0,ps=Gn("zlib");if(!ps.deflateSync)Ns=!1;var bg=Rr(),wg=Ve();Hs.exports=function(n,r){if(!Ns)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e=new wg(r||{}),i=[];if(i.push(Buffer.from(bg.PNG_SIGNATURE)),i.push(e.packIHDR(n.width,n.height)),n.gamma)i.push(e.packGAMA(n.gamma));let o=e.filterData(n.data,n.width,n.height),s=ps.deflateSync(o,e.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(e.packIDAT(s)),i.push(e.packIEND()),Buffer.concat(i)}});var js=an((Mg)=>{var Eg=vs(),kg=Ss();Mg.read=function(n,r){return Eg(n,r||{})};Mg.write=function(n,r){return kg(n,r)}});var Js=an((Sg)=>{var vg=Gn("util"),Gs=Gn("stream"),Ng=rs(),pg=gs(),Hg=js(),Kn=Sg.PNG=function(n){if(Gs.call(this),n=n||{},this.width=n.width|0,this.height=n.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,n.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Ng(n),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(r){this.data=r,this.emit("parsed",r)}.bind(this)),this._packer=new pg(n),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};vg.inherits(Kn,Gs);Kn.sync=Hg;Kn.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Kn.prototype.parse=function(n,r){if(r){let t,e;t=function(i){this.removeListener("error",e),this.data=i,r(null,this)}.bind(this),e=function(i){this.removeListener("parsed",t),r(i,null)}.bind(this),this.once("parsed",t),this.once("error",e)}return this.end(n),this};Kn.prototype.write=function(n){return this._parser.write(n),!0};Kn.prototype.end=function(n){this._parser.end(n)};Kn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Kn.prototype._gamma=function(n){this.gamma=n};Kn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Kn.bitblt=function(n,r,t,e,i,o,s,u){if(t|=0,e|=0,i|=0,o|=0,s|=0,u|=0,t>n.width||e>n.height||t+i>n.width||e+o>n.height)throw Error("bitblt reading outside image");if(s>r.width||u>r.height||s+i>r.width||u+o>r.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)n.data.copy(r.data,(u+c)*r.width+s<<2,(e+c)*n.width+t<<2,(e+c)*n.width+t+i<<2)};Kn.prototype.bitblt=function(n,r,t,e,i,o,s){return Kn.bitblt(this,n,r,t,e,i,o,s),this};Kn.adjustGamma=function(n){if(n.gamma){for(let r=0;r<n.height;r++)for(let t=0;t<n.width;t++){let e=n.width*r+t<<2;for(let i=0;i<3;i++){let o=n.data[e+i]/255;o=Math.pow(o,0.45454545454545453/n.gamma),n.data[e+i]=Math.round(o*255)}}n.gamma=0}};Kn.prototype.adjustGamma=function(){Kn.adjustGamma(this)}});var Ni=an((va,Kc)=>{var vi={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let t="";if(n<0)t+=`\x1B[${-n}D`;else if(n>0)t+=`\x1B[${n}C`;if(r<0)t+=`\x1B[${-r}A`;else if(r>0)t+=`\x1B[${r}B`;return t},up:(n=1)=>`\x1B[${n}A`,down:(n=1)=>`\x1B[${n}B`,forward:(n=1)=>`\x1B[${n}C`,backward:(n=1)=>`\x1B[${n}D`,nextLine:(n=1)=>"\x1B[E".repeat(n),prevLine:(n=1)=>"\x1B[F".repeat(n),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Wm={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},Xm={screen:"\x1B[2J",up:(n=1)=>"\x1B[1J".repeat(n),down:(n=1)=>"\x1B[J".repeat(n),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(n){let r="";for(let t=0;t<n;t++)r+=this.line+(t<n-1?vi.up():"");if(n)r+=vi.left;return r}};Kc.exports={cursor:vi,scroll:Wm,erase:Xm,beep:"\x07"}});import{isMainThread as Pd}from"node:worker_threads";import{parseArgs as Xd}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.2",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","dist/ghostty/ttheme.conf","shell","!shell/check.zsh","ghostty/shaders"],description:"Character terminal palettes for ghostty, kitty, alacritty, wezterm and iTerm2",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as Go}from"node:fs";import{basename as cf,join as ct}from"node:path";var Xh=/^#[0-9a-f]{6}$/;function oo(n){return Xh.test(n)}function On(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function er(n){let[r,t,e]=On(n).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*r+0.7152*t+0.0722*e}function ir(n,r){let t=er(n),e=er(r);return(Math.max(t,e)+0.05)/(Math.min(t,e)+0.05)}function Kt(n,r){return Math.round(ir(n,r)*100)/100}var gr=7,so=3,ae=0.15,uo=1.6,co=[1,2,3,4,5,6,9,10,11,12,13,14],ho=[7,15];function tt(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function be(n,r,t){let e=n.background;return r.flatMap((i)=>{let o=tt(n,i);return ir(o,e)<t?[`ANSI ${i} ${o} on ${e} is ${Kt(o,e)}:1, needs ${t}:1`]:[]})}function fo(n,r){return Math.min(...r.map((t)=>ir(tt(n,t),n.background)))}var Rt=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:gr,measure:({foreground:n,background:r})=>ir(n,r),check:({foreground:n,background:r})=>ir(n,r)<gr?[`foreground ${n} on ${r} is ${Kt(n,r)}:1, needs ${gr}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:so,measure:(n)=>fo(n,co),check:(n)=>be(n,co,so)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ae,measure:(n)=>er(tt(n,0)),check:(n)=>{let r=tt(n,0);return er(r)>ae?[`ANSI 0 ${r} has luminance ${er(r).toFixed(3)}, needs <= ${ae}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:gr,measure:(n)=>fo(n,ho),check:(n)=>be(n,ho,gr)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:uo,measure:(n)=>ir(tt(n,8),n.background),check:(n)=>be(n,[8],uo)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:gr,measure:({foreground:n,selectionBackground:r})=>r===void 0?Number.NaN:ir(n,r),check:({foreground:n,selectionBackground:r})=>r!==void 0&&ir(n,r)<gr?[`foreground ${n} on selection ${r} is ${Kt(n,r)}:1, needs ${gr}:1`]:[]}],Bd=Rt.map((n)=>n.rule),yt=Rt.map(({rule:n,label:r,unit:t,min:e,max:i})=>({rule:n,label:r,unit:t,...e===void 0?{}:{min:e},...i===void 0?{}:{max:i}}));function go(n){return Rt.map((r)=>Math.round(r.measure(n)*1000)/1000)}function we(n){return Rt.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function lo(n){return n.flatMap(we)}var Vh=["black","red","green","yellow","blue","magenta","cyan","white"];function mo(n,r){return[n,...Vh.map((t,e)=>`${t} = '${r[e]}'`),""].join(`
3
+ `)}var et={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Gr(n),"","[colors.primary]",`background = '${n.background}'`,`foreground = '${n.foreground}'`,"","[colors.cursor]",`cursor = '${n.cursor}'`,`text = '${n.background}'`,"","[colors.selection]",`background = '${n.selectionBackground}'`,`text = '${n.foreground}'`,"",mo("[colors.normal]",n.ansi.slice(0,8)),mo("[colors.bright]",n.ansi.slice(8,16))].join(`
4
4
  `),t=[`# ${n.name} — font settings.`,`# Pair with the palette: import = ["~/.config/alacritty/themes/${n.name}.toml"]`,"","[font]",`size = ${n.font.size}`,"","[font.normal]",`family = '${n.font.family}'`,""].join(`
5
- `);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:t}]}};import{isDeepStrictEqual as Yh}from"node:util";var it={id:"ghostty",emit(n){let r=[...jr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((t,e)=>`palette = ${e}=${t}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${n.ghostty.iconGhost}`,`macos-icon-screen-color = ${n.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
5
+ `);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:t}]}};import{isDeepStrictEqual as Yh}from"node:util";var it={id:"ghostty",emit(n){let r=[...Gr(n),`background = ${n.background}`,`foreground = ${n.foreground}`,`cursor-color = ${n.cursor}`,`selection-background = ${n.selectionBackground}`,`selection-foreground = ${n.foreground}`,...n.ansi.map((t,e)=>`palette = ${e}=${t}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${n.ghostty.iconGhost}`,`macos-icon-screen-color = ${n.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
6
6
  `);return[{path:`ghostty/themes/${n.name}`,content:r}]},emitShared(n){let[r]=n;if(!r)return[];for(let e of n)if(!Yh(e.font,r.font)||e.ghostty.shader!==r.ghostty.shader)throw Error(`${e.name}: per-theme font/shader overrides cannot be expressed in the shared ghostty/ttheme.conf`);return[{path:"ghostty/ttheme.conf",content:["# ttheme — shared font and shader, identical for every palette.","# Pick colors with: theme = <palette>",`font-family = ${r.font.family}`,`font-size = ${r.font.size}`,...r.font.codepointMap.map((e)=>`font-codepoint-map = ${e.range}=${e.family}`),...r.ghostty.shader?["",`custom-shader = ~/.config/ghostty/shaders/${r.ghostty.shader}`,"custom-shader-animation = true"]:[],""].join(`
7
- `)}]}};function fr(n){let[r,t,e]=On(n);return{"Alpha Component":1,"Blue Component":e/255,"Color Space":"P3","Green Component":t/255,"Red Component":r/255}}function $o(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,fr(r)])),"Background Color":fr(n.background),"Bold Color":fr(n.foreground),"Cursor Color":fr(n.cursor),"Cursor Text Color":fr(n.background),"Foreground Color":fr(n.foreground),"Selected Text Color":fr(n.foreground),"Selection Color":fr(n.selectionBackground)}}function Ph(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function ao(n,r,t,e){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...e?{"Dynamic Profile Parent GUID":e}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Ph(r.get(s.name)),...$o(s)}),o=[...t?[i(t,"default")]:[],...n.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
7
+ `)}]}};function lr(n){let[r,t,e]=On(n);return{"Alpha Component":1,"Blue Component":e/255,"Color Space":"P3","Green Component":t/255,"Red Component":r/255}}function $o(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,lr(r)])),"Background Color":lr(n.background),"Bold Color":lr(n.foreground),"Cursor Color":lr(n.cursor),"Cursor Text Color":lr(n.background),"Foreground Color":lr(n.foreground),"Selected Text Color":lr(n.foreground),"Selection Color":lr(n.selectionBackground)}}function Ph(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function ao(n,r,t,e){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...e?{"Dynamic Profile Parent GUID":e}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Ph(r.get(s.name)),...$o(s)}),o=[...t?[i(t,"default")]:[],...n.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
8
8
  `}function zh(n,r){return[` <key>${n}</key>`,"\t<dict>",...Object.entries(r).flatMap(([t,e])=>[` <key>${t}</key>`,typeof e==="string"?` <string>${e}</string>`:` <real>${e}</real>`]),"\t</dict>"].join(`
9
9
  `)}var ot={id:"iterm2",limits:"colors only — font lives in the profile; colors are Display P3, the space iTerm2 reads OSC colors in",emit(n){let r=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries($o(n)).map(([t,e])=>zh(t,e)),"</dict>","</plist>",""].join(`
10
- `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var st={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...jr(n),`background ${n.background}`,`foreground ${n.foreground}`,`cursor ${n.cursor}`,`cursor_text_color ${n.background}`,`selection_background ${n.selectionBackground}`,`selection_foreground ${n.foreground}`,...n.ansi.map((e,i)=>`color${i} ${e}`),""].join(`
10
+ `);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var st={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Gr(n),`background ${n.background}`,`foreground ${n.foreground}`,`cursor ${n.cursor}`,`cursor_text_color ${n.background}`,`selection_background ${n.selectionBackground}`,`selection_foreground ${n.foreground}`,...n.ansi.map((e,i)=>`color${i} ${e}`),""].join(`
11
11
  `),t=[`# ${n.name} — font settings.`,`# Pair with the palette: include themes/${n.name}.conf`,`font_family ${n.font.family}`,`font_size ${n.font.size}`,""].join(`
12
- `);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:t}]}};function Ee(n){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},...n.lead?{lead:!0}:{},order:n.order,ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.role==="default"?{default:!0}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,signature:n.signature,signatureSlots:n.signatureSlots,ansi:n.ansi,gate:go(n),...n.waive.length>0?{waived:n.waive}:{}}}function Gr(n){return n.filter((r)=>r.default!==!0)}function Ah(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:Rt,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(Ee)}}var ke={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(Ah(n),null,2)}
13
- `}]}};import{readdirSync as Ch,readFileSync as Me}from"node:fs";import{basename as Th,join as Fe}from"node:path";var _h="_defaults.toml",ir="_groups.toml",bo=3,wo=["background","foreground","cursor","selection"],Bh=new Set(["next","help","preview","pin","unpin","config"]);function Nn(n,r){throw Error(`${n}: ${r}`)}function wr(n,r,t){if(typeof t!=="string"||!oo(t))Nn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Wn(n,r,t){if(typeof t!=="string"||t.length===0)Nn(n,`${r} must be a non-empty string`);return t}function or(n){return n&&typeof n==="object"?n:{}}function xh(n,r,t){let e={...or(t),...or(r)},i=e.codepoint_map??[];if(!Array.isArray(i))Nn(n,"font.codepoint_map must be an array");return{family:Wn(n,"font.family",e.family),size:Number(e.size),codepointMap:i.map((o)=>{let s=or(o);return{range:Wn(n,"font.codepoint_map[].range",s.range),family:Wn(n,"font.codepoint_map[].family",s.family)}})}}function Dh(n,r,t){if(r===void 0)return[t.cursor,t.selectionBackground,t.background];let e=Array.isArray(r)?r:[r];if(e.length===0)Nn(n,"ghostty.icon_screen must not be empty");return e.map((i,o)=>wr(n,`ghostty.icon_screen[${o}]`,i))}function nf(n,r,t,e){let i={...or(t),...or(r)};return{shader:i.shader===void 0?void 0:Wn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?e.cursor:wr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Dh(n,i.icon_screen,e)}}function rf(n){return new Map([...wo.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function tf(n,r,t){if(!Array.isArray(r)||r.length!==bo)Nn(n,`meta.signature must name exactly ${bo} palette slots`);let e=rf(t),i=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=Wn(n,c,u),f=e.get(h);if(f===void 0)Nn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${wo.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)Nn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function ef(n){let t=Bun.TOML.parse(Me(Fe(n,ir),"utf8")).group;if(!Array.isArray(t)||t.length===0)Nn(ir,"needs at least one [[group]] table");return t.map((e)=>{let i=or(e);return{name:Wn(ir,"group.name",i.name),native:i.native===void 0?void 0:Wn(ir,"group.native",i.native),lead:Wn(ir,"group.lead",i.lead)}})}function of(n,r,t,e){let i=Bun.TOML.parse(r),o=or(i.meta),s=or(i.colors),u=or(i.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)Nn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Wn(n,"meta.name",o.name);if(h!==Th(n,".toml"))Nn(n,`meta.name "${h}" does not match the filename`);if(Bh.has(h))Nn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))Nn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")Nn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=Wn(n,"meta.group",o.group),l=e.get(g);if(!l)Nn(n,`meta.group "${g}" has no [[group]] table in ${ir}`);let $=wr(n,"colors.background",s.background),a=wr(n,"colors.foreground",s.foreground),w=wr(n,"colors.cursor",s.cursor),F=wr(n,"colors.selection_background",s.selection_background),v=c.map((b,K)=>wr(n,`colors.ansi[${K}]`,b)),j=tf(n,o.signature,{background:$,foreground:a,cursor:w,selection:F,ansi:v}),M=o.booru===void 0?void 0:Wn(n,"meta.booru",o.booru);if(M!==void 0&&/\s/.test(M))Nn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(M)}`);let p=Array.isArray(u.waive)?u.waive.map(String):[];if(p.length>0&&typeof u.reason!=="string")Nn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:Wn(n,"meta.ansi_source",o.ansi_source),...M?{booru:M}:{},background:$,foreground:a,cursor:w,selectionBackground:F,ansi:v,signature:j.colors,signatureSlots:j.names,font:xh(n,i.font,t.font),ghostty:nf(n,i.ghostty,t.ghostty,{background:$,cursor:w,selectionBackground:F}),waive:p,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Eo(n){let r=Bun.TOML.parse(Me(Fe(n,_h),"utf8")),t=ef(n),e=new Map(t.map((s)=>[s.name,s]));if(e.size!==t.length)Nn(ir,"group.name must be unique");let i=Ch(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>of(s,Me(Fe(n,s),"utf8"),r,e)).sort((s,u)=>s.order-u.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let u=i.filter((c)=>c.group===s.name);if(u.length===0)Nn(ir,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))Nn(ir,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function ko(n){return n.filter((r)=>r.role===void 0)}function ut(n){let r=(t,e)=>t<e?-1:t>e?1:0;return[...n].sort((t,e)=>r(t.group.toLowerCase(),e.group.toLowerCase())||r(t.name,e.name))}var yt=["ghostty","kitty","alacritty","iterm2"];var Mo=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Ot(n,r){let t=`# ttheme begin
12
+ `);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:t}]}};function Ee(n){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},...n.lead?{lead:!0}:{},order:n.order,ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},...n.role==="default"?{default:!0}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,signature:n.signature,signatureSlots:n.signatureSlots,ansi:n.ansi,gate:go(n),...n.waive.length>0?{waived:n.waive}:{}}}function Jr(n){return n.filter((r)=>r.default!==!0)}function Ah(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:yt,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(Ee)}}var ke={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(Ah(n),null,2)}
13
+ `}]}};import{readdirSync as Ch,readFileSync as Me}from"node:fs";import{basename as Th,join as Fe}from"node:path";var _h="_defaults.toml",or="_groups.toml",bo=3,wo=["background","foreground","cursor","selection"],Bh=new Set(["next","help","preview","pin","unpin","config"]);function pn(n,r){throw Error(`${n}: ${r}`)}function Er(n,r,t){if(typeof t!=="string"||!oo(t))pn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Wn(n,r,t){if(typeof t!=="string"||t.length===0)pn(n,`${r} must be a non-empty string`);return t}function sr(n){return n&&typeof n==="object"?n:{}}function xh(n,r,t){let e={...sr(t),...sr(r)},i=e.codepoint_map??[];if(!Array.isArray(i))pn(n,"font.codepoint_map must be an array");return{family:Wn(n,"font.family",e.family),size:Number(e.size),codepointMap:i.map((o)=>{let s=sr(o);return{range:Wn(n,"font.codepoint_map[].range",s.range),family:Wn(n,"font.codepoint_map[].family",s.family)}})}}function Dh(n,r,t){if(r===void 0)return[t.cursor,t.selectionBackground,t.background];let e=Array.isArray(r)?r:[r];if(e.length===0)pn(n,"ghostty.icon_screen must not be empty");return e.map((i,o)=>Er(n,`ghostty.icon_screen[${o}]`,i))}function nf(n,r,t,e){let i={...sr(t),...sr(r)};return{shader:i.shader===void 0?void 0:Wn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?e.cursor:Er(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Dh(n,i.icon_screen,e)}}function rf(n){return new Map([...wo.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function tf(n,r,t){if(!Array.isArray(r)||r.length!==bo)pn(n,`meta.signature must name exactly ${bo} palette slots`);let e=rf(t),i=[],o=[];for(let[s,u]of r.entries()){let c=`meta.signature[${s}]`,h=Wn(n,c,u),f=e.get(h);if(f===void 0)pn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${wo.join(", ")} or ansi0-ansi15`);i.push(h),o.push(f)}if(new Set(o).size!==o.length)pn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function ef(n){let t=Bun.TOML.parse(Me(Fe(n,or),"utf8")).group;if(!Array.isArray(t)||t.length===0)pn(or,"needs at least one [[group]] table");return t.map((e)=>{let i=sr(e);return{name:Wn(or,"group.name",i.name),native:i.native===void 0?void 0:Wn(or,"group.native",i.native),lead:Wn(or,"group.lead",i.lead)}})}function of(n,r,t,e){let i=Bun.TOML.parse(r),o=sr(i.meta),s=sr(i.colors),u=sr(i.contrast),c=s.ansi;if(!Array.isArray(c)||c.length!==16)pn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Wn(n,"meta.name",o.name);if(h!==Th(n,".toml"))pn(n,`meta.name "${h}" does not match the filename`);if(Bh.has(h))pn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))pn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=o.role;if(f!==void 0&&f!=="default")pn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=Wn(n,"meta.group",o.group),l=e.get(g);if(!l)pn(n,`meta.group "${g}" has no [[group]] table in ${or}`);let $=Er(n,"colors.background",s.background),a=Er(n,"colors.foreground",s.foreground),w=Er(n,"colors.cursor",s.cursor),F=Er(n,"colors.selection_background",s.selection_background),v=c.map((b,K)=>Er(n,`colors.ansi[${K}]`,b)),j=tf(n,o.signature,{background:$,foreground:a,cursor:w,selection:F,ansi:v}),M=o.booru===void 0?void 0:Wn(n,"meta.booru",o.booru);if(M!==void 0&&/\s/.test(M))pn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(M)}`);let N=Array.isArray(u.waive)?u.waive.map(String):[];if(N.length>0&&typeof u.reason!=="string")pn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(o.order),role:f,ansiSource:Wn(n,"meta.ansi_source",o.ansi_source),...M?{booru:M}:{},background:$,foreground:a,cursor:w,selectionBackground:F,ansi:v,signature:j.colors,signatureSlots:j.names,font:xh(n,i.font,t.font),ghostty:nf(n,i.ghostty,t.ghostty,{background:$,cursor:w,selectionBackground:F}),waive:N,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Eo(n){let r=Bun.TOML.parse(Me(Fe(n,_h),"utf8")),t=ef(n),e=new Map(t.map((s)=>[s.name,s]));if(e.size!==t.length)pn(or,"group.name must be unique");let i=Ch(n).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>of(s,Me(Fe(n,s),"utf8"),r,e)).sort((s,u)=>s.order-u.order);if(new Set(i.map((s)=>s.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let u=i.filter((c)=>c.group===s.name);if(u.length===0)pn(or,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))pn(or,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return i}function ko(n){return n.filter((r)=>r.role===void 0)}function ut(n){let r=(t,e)=>t<e?-1:t>e?1:0;return[...n].sort((t,e)=>r(t.group.toLowerCase(),e.group.toLowerCase())||r(t.name,e.name))}var Ot=["ghostty","kitty","alacritty","iterm2"];var Mo=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Lt(n,r){let t=`# ttheme begin
14
14
  ${r}
15
15
  # ttheme end
16
16
  `;if(Mo.test(n))return n.replace(Mo,t);if(n==="")return t;return`${n.replace(/\n*$/,`
17
17
  `)}
18
18
  ${t}`}function Fo(n){if(n.GHOSTTY_RESOURCES_DIR||n.TERM_PROGRAM==="ghostty")return"ghostty";if(n.KITTY_WINDOW_ID)return"kitty";if(n.WEZTERM_PANE)return"wezterm";if(n.ALACRITTY_WINDOW_ID)return"alacritty";if(n.ITERM_SESSION_ID||n.TERM_PROGRAM==="iTerm.app")return"iterm2";if(n.TERM?.startsWith("foot"))return"foot";return"unknown"}function Io(n,r){let t=[`command = ${n}/launch-tab.zsh`,"shell-integration = zsh"];if(r)t.push(`theme = ${r}`);return t.push(`config-file = ${n}/ttheme.conf`,`config-file = ?${n}/backgrounds/shown.conf`),t.join(`
19
- `)}function vo(n){return`source ${n}/ttheme.zsh`}var sf="# ttheme settings — exported variables win over this file",Ie={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "safebooru=transparent_background yande=transparent_png,vector" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: newest or score (default newest)",default:"newest"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "konachan=https://konachan.com danbooru=https://danbooru.donmai.us" (default none)',default:""}};function ve(n,r){return`: \${${n}:=${r}}`}function po(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function uf(n,r){if(po(r).test(n))return n;let t=Ie[r];return`${n.replace(/\n*$/,`
19
+ `)}function vo(n){return`source ${n}/ttheme.zsh`}var sf="# ttheme settings — exported variables win over this file",Ie={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "safebooru=transparent_background yande=transparent_png,vector" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: newest or score (default newest)",default:"newest"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "konachan=https://konachan.com danbooru=https://danbooru.donmai.us" (default none)',default:""}};function ve(n,r){return`: \${${n}:=${r}}`}function No(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function uf(n,r){if(No(r).test(n))return n;let t=Ie[r];return`${n.replace(/\n*$/,`
20
20
  `)}
21
21
  ${t.doc}
22
22
  ${ve(r,t.default)}
23
- `}function pe(){let n=Object.entries(Ie).map(([r,t])=>`${t.doc}
23
+ `}function Ne(){let n=Object.entries(Ie).map(([r,t])=>`${t.doc}
24
24
  ${ve(r,t.default)}`);return`${[sf,...n].join(`
25
25
 
26
26
  `)}
27
- `}function Lt(n,r,t){let e=ve(r,t),i=po(r);if(i.test(n))return n.replace(i,e);return`${n.replace(/\n*$/,`
27
+ `}function Qt(n,r,t){let e=ve(r,t),i=No(r);if(i.test(n))return n.replace(i,e);return`${n.replace(/\n*$/,`
28
28
  `)}
29
29
  ${e}
30
- `}function No(n){if(n==="")return pe();return Object.keys(Ie).reduce(uf,n)}function Ho(n){return n?`include themes/${n}.conf`:""}function So(n){return n?`[general]
31
- import = ["${n}"]`:""}function Ne(n,r,t=[]){for(let u of n)for(let c of[u.name,u.group,u.native??"",u.ansiSource])if(/["$`\\]/.test(c))throw Error(`${u.name}: "${c}" contains a character that breaks zsh quoting`);let e=Math.max(0,...n.map((u)=>u.name.length)),i=(u,c)=>` ${u.name.padEnd(e)} "${c}"`,o=(u)=>u.map((c)=>c.name).join(" "),s=Gr(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Dn.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${r??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${t.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${pe().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...n.map((u)=>i(u,[u.background,u.foreground,u.cursor,u.selection,...u.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(ut(s))})`,"","typeset -gA TTHEME_GROUP=(",...n.map((u)=>i(u,u.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...n.filter((u)=>u.native).map((u)=>i(u,u.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...n.map((u)=>i(u,u.ansiSource)),")",""].join(`
32
- `)}var He={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:Ne(n.map(Ee))}]}};var jo=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,Se={id:"wezterm",limits:"no shaders; runtime overrides are per-window, never per-pane",emit(n){let r=["[metadata]",`name = "${n.name}"`,`origin_url = "${n.ansiSource}"`,"","[colors]",`foreground = "${n.foreground}"`,`background = "${n.background}"`,`cursor_bg = "${n.cursor}"`,`cursor_border = "${n.cursor}"`,`cursor_fg = "${n.background}"`,`selection_bg = "${n.selectionBackground}"`,`selection_fg = "${n.foreground}"`,"",`ansi = ${jo(n.ansi.slice(0,8))}`,`brights = ${jo(n.ansi.slice(8,16))}`,""].join(`
30
+ `}function po(n){if(n==="")return Ne();return Object.keys(Ie).reduce(uf,n)}function Ho(n){return n?`include themes/${n}.conf`:""}function So(n){return n?`[general]
31
+ import = ["${n}"]`:""}function pe(n,r,t=[]){for(let u of n)for(let c of[u.name,u.group,u.native??"",u.ansiSource])if(/["$`\\]/.test(c))throw Error(`${u.name}: "${c}" contains a character that breaks zsh quoting`);let e=Math.max(0,...n.map((u)=>u.name.length)),i=(u,c)=>` ${u.name.padEnd(e)} "${c}"`,o=(u)=>u.map((c)=>c.name).join(" "),s=Jr(n);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Dn.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${r??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${t.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Ne().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...n.map((u)=>i(u,[u.background,u.foreground,u.cursor,u.selection,...u.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(ut(s))})`,"","typeset -gA TTHEME_GROUP=(",...n.map((u)=>i(u,u.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...n.filter((u)=>u.native).map((u)=>i(u,u.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...n.map((u)=>i(u,u.ansiSource)),")",""].join(`
32
+ `)}var He={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:pe(n.map(Ee))}]}};var jo=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,Se={id:"wezterm",limits:"no shaders; runtime overrides are per-window, never per-pane",emit(n){let r=["[metadata]",`name = "${n.name}"`,`origin_url = "${n.ansiSource}"`,"","[colors]",`foreground = "${n.foreground}"`,`background = "${n.background}"`,`cursor_bg = "${n.cursor}"`,`cursor_border = "${n.cursor}"`,`cursor_fg = "${n.background}"`,`selection_bg = "${n.selectionBackground}"`,`selection_fg = "${n.foreground}"`,"",`ansi = ${jo(n.ansi.slice(0,8))}`,`brights = ${jo(n.ansi.slice(8,16))}`,""].join(`
33
33
  `),t=[`-- ${n.name} — font settings.`,"-- Merge into your wezterm.lua config table:",`-- local t = require("ttheme.${n.name}")`,`-- config.color_scheme = "${n.name}"`,"-- config.font = t.font","-- config.font_size = t.font_size","return {",` font = require("wezterm").font("${n.font.family}"),`,` font_size = ${n.font.size},`,"}",""].join(`
34
- `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function jr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Jo=ct(import.meta.dirname,".."),hf=ct(Jo,"themes"),je=ct(Jo,"dist"),Qt=[it,st,et,Se,ot],ff=[He,ke],Ko=Qt.map((n)=>n.id);async function Zt({only:n}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let r=n&&n.length>0?Qt.filter((o)=>n.includes(o.id)):Qt,t=Eo(hf),e=lo(t);if(e.length>0){for(let o of e)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${e.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===Qt.length)Go(je,{recursive:!0,force:!0});else for(let o of r)Go(ct(je,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...r,...ff]){let s=t.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(t)??[];for(let h of[...s,...u])await Bun.write(ct(je,h.path),h.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>cf(h.path)).join(" ");console.log(` ${o.id.padEnd(10)} ${c}`)}console.log(`
35
- ${t.length} themes (${ko(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as mc}from"node:child_process";import{existsSync as Vr,mkdirSync as wi,mkdtempSync as $m,readFileSync as dc,rmSync as di,statSync as am,writeFileSync as Ei}from"node:fs";import{tmpdir as bm}from"node:os";import{dirname as fc,join as ur}from"node:path";import{createHash as Jg}from"node:crypto";import{mkdirSync as Vs,readdirSync as kr,readFileSync as Ys,renameSync as Ps,rmSync as Lr,statSync as Kg,utimesSync as Rg,writeFileSync as Xt}from"node:fs";import{isAbsolute as yg,join as Fn}from"node:path";var ys=Jt(Uo(),1),qt=Jt(Js(),1),Ks=[137,80,78,71,13,10,26,10],Os=13;function Ls(n){return n.length>=Ks.length&&Ks.every((r,t)=>n[t]===r)}function jg(n){let r=qt.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Qs(n,r){if(Ls(n)){let t=Pe(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return jg(n)}if(n[0]===255&&n[1]===216){let t=ys.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function yr(n){let r=new qt.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),qt.PNG.sync.write(r)}function Rs(n,r){for(let t=0;t+r.length<=n.length;t++){let e=!0;for(let i=0;i<r.length&&e;i++)e=n[t+i]===r.charCodeAt(i);if(e)return t}return-1}function Pe(n){if(n.length<33||!Ls(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),t=r.getUint32(16),e=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:t,height:e,alpha:!0};let i=Rs(n,"IDAT");return{width:t,height:e,alpha:Rs(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function Zs(n,r=Os){let{width:t,height:e}=n,i=-1,o=-1;for(let s=0;s<n.height;s++)for(let u=0;u<n.width;u++)if((n.data[(s*n.width+u)*4+3]??0)>=r)t=Math.min(t,u),i=Math.max(i,u),e=Math.min(e,s),o=Math.max(o,s);return i<0?null:{x:t,y:e,w:i-t+1,h:o-e+1}}function Wt(n){let r=0;for(let t=3;t<n.data.length;t+=4)if((n.data[t]??0)<Os)r++;return Math.round(r*100/(n.width*n.height))}function Gg(n,r){if(r<=1)return n;let t=Math.max(1,Math.floor(n.width/r)),e=Math.max(1,Math.floor(n.height/r)),i=new Uint8Array(t*e*4),o=n.data;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let $=0;$<r;$++)for(let a=0;a<r;a++){let w=((s*r+$)*n.width+u*r+a)*4,F=o[w+3]??0;c+=(o[w]??0)*F,h+=(o[w+1]??0)*F,f+=(o[w+2]??0)*F,g+=F}let l=(s*t+u)*4;if(g>0)i[l]=Math.round(c/g),i[l+1]=Math.round(h/g),i[l+2]=Math.round(f/g);i[l+3]=Math.round(g/(r*r))}return{width:t,height:e,data:i}}function Us(n,r,t){let e=Math.min(r/n.width,t/n.height),i=Math.max(1,Math.round(n.width*e)),o=Math.max(1,Math.round(n.height*e)),s=Or(n,{x:0,y:0,w:n.width,h:n.height},i,o),u=new Uint8Array(r*t*4),c=Math.floor((r-i)/2),h=Math.floor((t-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:t,data:u}}function Or(n,r,t,e){let i=Math.max(1,Math.floor(Math.min(r.w/t,r.h/e))),o=Gg(n,i),s=o.data,u=new Uint8Array(t*e*4);for(let c=0;c<e;c++){let h=Math.min(o.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/e-0.5)),f=Math.floor(h),g=Math.min(o.height-1,f+1),l=h-f;for(let $=0;$<t;$++){let a=Math.min(o.width-1,Math.max(0,r.x/i+($+0.5)*r.w/i/t-0.5)),w=Math.floor(a),F=Math.min(o.width-1,w+1),v=a-w,j=(f*o.width+w)*4,M=(f*o.width+F)*4,p=(g*o.width+w)*4,b=(g*o.width+F)*4,K=(s[j+3]??0)*(1-v)*(1-l),E=(s[M+3]??0)*v*(1-l),J=(s[p+3]??0)*(1-v)*l,S=(s[b+3]??0)*v*l,O=K+E+J+S,R=(c*t+$)*4;if(O>0)for(let A=0;A<3;A++){let Z=(s[j+A]??0)*K+(s[M+A]??0)*E+(s[p+A]??0)*J+(s[b+A]??0)*S;u[R+A]=Math.round(Z/O)}u[R+3]=Math.round(O)}}return{width:t,height:e,data:u}}var Vn={width:2560,height:1550},Og=2560,Lg=0.1,zs=0.15,Qg=0.55,Zg=0.65,Ug=3,qg=er(ze("#19161e","#9b86c8",0.2)),Wg="shelf";function ze(n,r,t){let e=On(n),i=On(r);return`#${e.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Xg(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let t=/^ansi(\d|1[0-5])$/.exec(r),e=t?n.ansi[Number(t[1])]:void 0;if(!e)throw Error(`${n.name} has no slot ${r}`);return e}function qs(n){if(n(1))return 1;let r=0,t=1;for(let e=0;e<40;e++){let i=(r+t)/2;if(n(i))r=i;else t=i}return r}function Ws(n,r){let t=Xg(n,r),i=qs((h)=>we({name:n.name,background:ze(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=qs((h)=>er(ze(n.background,t,h))<=qg),s=Math.floor(Math.min(i,o)*1000)/1000,u=On(n.background),c=Math.hypot(...On(t).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:t,cap:i,matched:o,opacity:s,reach:c}}function As(n,r){let t=Ws(n,"cursor");if(t.opacity>=Lg)return t;return r.filter((e)=>e!=="cursor"&&e!=="background").map((e)=>Ws(n,e)).reduce((e,i)=>i.reach>e.reach?i:e,t)}function Ae(n,r,t){let e=On(r),i=On(t),o=n.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((e[c]??0)+((i[c]??0)-(e[c]??0))*u)}return n}function Vg(n,r,t){let e=On(r),i=n.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*t;for(let c=0;c<3;c++)o[s+c]=Math.round((e[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Cs(n){return Zs(n)??{x:0,y:0,w:n.width,h:n.height}}function Ts(n){return Math.min(0.5,(zs+0.5)*(n.w*Vn.height/Vn.width/n.h))}function _s(n,r,t){let e=Math.min(Math.max(0,t*n.h-r/2),n.h-r);return{x:n.x,y:n.y+e,w:n.w,h:r}}function Yg(n,r,t,e){let i=n.w*t/r;if(i<=n.h)return _s(n,i,e);let o=n.h*r/t;return{x:n.x+(n.w-o)/2,y:n.y,w:o,h:n.h}}function Xs(n,r,t){if(n.w*t>n.h*r){let i=n.h*r/t;return{x:n.x+(n.w-i)/2,y:n.y,w:i,h:n.h}}let e=n.w*t/r;return{x:n.x,y:n.y+(n.h-e)/2,w:n.w,h:e}}function Pg(n,r){let t=Math.min(1,Og/Math.max(r.w,r.h));return Or(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Bs(n,r,t,e,i){let o=Qg*n.h,s=n.w*t/r;if(i<Ug||s>o)return{crop:Yg(n,r,t,e),at:{x:0,y:0,w:r,h:t},inset:!1};let u=1-s/o,c=t*(1-zs*u),h=n.w*c/o;return{crop:_s(n,o,e),at:{x:(r-h)*Zg,y:t-c,w:h,h:c},inset:!0}}function xs(n,r,t,e){let i=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=Or(n,r.crop,i,o),u=new Uint8Array(t*e*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let g=h+f,l=Math.max(0,-c),$=Math.min(i,t-c);if(g<0||g>=e||$<=l)continue;u.set(s.data.subarray((f*i+l)*4,(f*i+$)*4),(g*t+c+l)*4)}return{width:t,height:e,data:u}}function zg(n,r,t,e){let i=Bs(r,Vn.width,Vn.height,t,e);return i.inset?xs(n,i,Vn.width,Vn.height):Or(n,i.crop,Vn.width,Vn.height)}function Ds(n,r,t,e,i,o){let s=Cs(n),u=Bs(s,Vn.width,Vn.height,Ts(s),o),c;if(u.inset){let h=Xs({x:0,y:0,w:Vn.width,h:Vn.height},e,i),f=e/h.w;c=xs(n,{...u,at:{x:(u.at.x-h.x)*f,y:(u.at.y-h.y)*f,w:u.at.w*f,h:u.at.h*f}},e,i)}else c=Or(n,Xs(u.crop,e,i),e,i);return Vg(Ae(c,r.background,t.color),r.background,t.opacity)}function Qr(n){return Fn(n,"ttheme","backgrounds")}function Ag(n,r,t,e,i){return[...e?[`# from ${e}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = center",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
34
+ `);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function Gr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Jo=ct(import.meta.dirname,".."),hf=ct(Jo,"themes"),je=ct(Jo,"dist"),Zt=[it,st,et,Se,ot],ff=[He,ke],Ko=Zt.map((n)=>n.id);async function Ut({only:n}={}){if(typeof Bun>"u")throw Error("ttheme build needs bun — run it from a checkout: bun src/bin.ts build");let r=n&&n.length>0?Zt.filter((o)=>n.includes(o.id)):Zt,t=Eo(hf),e=lo(t);if(e.length>0){for(let o of e)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${e.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(r.length===Zt.length)Go(je,{recursive:!0,force:!0});else for(let o of r)Go(ct(je,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...r,...ff]){let s=t.flatMap((h)=>o.emit?.(h)??[]),u=o.emitShared?.(t)??[];for(let h of[...s,...u])await Bun.write(ct(je,h.path),h.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((h)=>cf(h.path)).join(" ");console.log(` ${o.id.padEnd(10)} ${c}`)}console.log(`
35
+ ${t.length} themes (${ko(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as mc}from"node:child_process";import{existsSync as Yr,mkdirSync as wi,mkdtempSync as $m,readFileSync as dc,rmSync as di,statSync as am,writeFileSync as Ei}from"node:fs";import{tmpdir as bm}from"node:os";import{dirname as fc,join as cr}from"node:path";import{createHash as Jg}from"node:crypto";import{mkdirSync as Vs,readdirSync as Mr,readFileSync as Ys,renameSync as Ps,rmSync as Qr,statSync as Kg,utimesSync as Rg,writeFileSync as Vt}from"node:fs";import{isAbsolute as yg,join as Fn}from"node:path";var ys=Jt(Uo(),1),Wt=Jt(Js(),1),Ks=[137,80,78,71,13,10,26,10],Os=13;function Ls(n){return n.length>=Ks.length&&Ks.every((r,t)=>n[t]===r)}function jg(n){let r=Wt.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Qs(n,r){if(Ls(n)){let t=Pe(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return jg(n)}if(n[0]===255&&n[1]===216){let t=ys.decode(n,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:r/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function Or(n){let r=new Wt.PNG({width:n.width,height:n.height});return r.data=Buffer.from(n.data),Wt.PNG.sync.write(r)}function Rs(n,r){for(let t=0;t+r.length<=n.length;t++){let e=!0;for(let i=0;i<r.length&&e;i++)e=n[t+i]===r.charCodeAt(i);if(e)return t}return-1}function Pe(n){if(n.length<33||!Ls(n))return null;let r=new DataView(n.buffer,n.byteOffset,n.byteLength),t=r.getUint32(16),e=r.getUint32(20);if(n[25]===4||n[25]===6)return{width:t,height:e,alpha:!0};let i=Rs(n,"IDAT");return{width:t,height:e,alpha:Rs(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function Zs(n,r=Os){let{width:t,height:e}=n,i=-1,o=-1;for(let s=0;s<n.height;s++)for(let u=0;u<n.width;u++)if((n.data[(s*n.width+u)*4+3]??0)>=r)t=Math.min(t,u),i=Math.max(i,u),e=Math.min(e,s),o=Math.max(o,s);return i<0?null:{x:t,y:e,w:i-t+1,h:o-e+1}}function Xt(n){let r=0;for(let t=3;t<n.data.length;t+=4)if((n.data[t]??0)<Os)r++;return Math.round(r*100/(n.width*n.height))}function Gg(n,r){if(r<=1)return n;let t=Math.max(1,Math.floor(n.width/r)),e=Math.max(1,Math.floor(n.height/r)),i=new Uint8Array(t*e*4),o=n.data;for(let s=0;s<e;s++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let $=0;$<r;$++)for(let a=0;a<r;a++){let w=((s*r+$)*n.width+u*r+a)*4,F=o[w+3]??0;c+=(o[w]??0)*F,h+=(o[w+1]??0)*F,f+=(o[w+2]??0)*F,g+=F}let l=(s*t+u)*4;if(g>0)i[l]=Math.round(c/g),i[l+1]=Math.round(h/g),i[l+2]=Math.round(f/g);i[l+3]=Math.round(g/(r*r))}return{width:t,height:e,data:i}}function Us(n,r,t){let e=Math.min(r/n.width,t/n.height),i=Math.max(1,Math.round(n.width*e)),o=Math.max(1,Math.round(n.height*e)),s=Lr(n,{x:0,y:0,w:n.width,h:n.height},i,o),u=new Uint8Array(r*t*4),c=Math.floor((r-i)/2),h=Math.floor((t-o)/2);for(let f=0;f<o;f++)u.set(s.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:t,data:u}}function Lr(n,r,t,e){let i=Math.max(1,Math.floor(Math.min(r.w/t,r.h/e))),o=Gg(n,i),s=o.data,u=new Uint8Array(t*e*4);for(let c=0;c<e;c++){let h=Math.min(o.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/e-0.5)),f=Math.floor(h),g=Math.min(o.height-1,f+1),l=h-f;for(let $=0;$<t;$++){let a=Math.min(o.width-1,Math.max(0,r.x/i+($+0.5)*r.w/i/t-0.5)),w=Math.floor(a),F=Math.min(o.width-1,w+1),v=a-w,j=(f*o.width+w)*4,M=(f*o.width+F)*4,N=(g*o.width+w)*4,b=(g*o.width+F)*4,K=(s[j+3]??0)*(1-v)*(1-l),E=(s[M+3]??0)*v*(1-l),J=(s[N+3]??0)*(1-v)*l,S=(s[b+3]??0)*v*l,O=K+E+J+S,R=(c*t+$)*4;if(O>0)for(let A=0;A<3;A++){let Z=(s[j+A]??0)*K+(s[M+A]??0)*E+(s[N+A]??0)*J+(s[b+A]??0)*S;u[R+A]=Math.round(Z/O)}u[R+3]=Math.round(O)}}return{width:t,height:e,data:u}}var Vn={width:2560,height:1550},Og=2560,Lg=0.1,zs=0.15,Qg=0.55,Zg=0.65,Ug=3,qg=er(ze("#19161e","#9b86c8",0.2)),Wg="shelf";function ze(n,r,t){let e=On(n),i=On(r);return`#${e.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Xg(n,r){if(r==="background"||r==="foreground"||r==="cursor")return n[r];if(r==="selection"&&n.selection)return n.selection;let t=/^ansi(\d|1[0-5])$/.exec(r),e=t?n.ansi[Number(t[1])]:void 0;if(!e)throw Error(`${n.name} has no slot ${r}`);return e}function qs(n){if(n(1))return 1;let r=0,t=1;for(let e=0;e<40;e++){let i=(r+t)/2;if(n(i))r=i;else t=i}return r}function Ws(n,r){let t=Xg(n,r),i=qs((h)=>we({name:n.name,background:ze(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),o=qs((h)=>er(ze(n.background,t,h))<=qg),s=Math.floor(Math.min(i,o)*1000)/1000,u=On(n.background),c=Math.hypot(...On(t).map((h,f)=>(h-(u[f]??0))*s));return{slot:r,color:t,cap:i,matched:o,opacity:s,reach:c}}function As(n,r){let t=Ws(n,"cursor");if(t.opacity>=Lg)return t;return r.filter((e)=>e!=="cursor"&&e!=="background").map((e)=>Ws(n,e)).reduce((e,i)=>i.reach>e.reach?i:e,t)}function Ae(n,r,t){let e=On(r),i=On(t),o=n.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((e[c]??0)+((i[c]??0)-(e[c]??0))*u)}return n}function Vg(n,r,t){let e=On(r),i=n.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*t;for(let c=0;c<3;c++)o[s+c]=Math.round((e[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:n.width,height:n.height,data:o}}function Cs(n){return Zs(n)??{x:0,y:0,w:n.width,h:n.height}}function Ts(n){return Math.min(0.5,(zs+0.5)*(n.w*Vn.height/Vn.width/n.h))}function _s(n,r,t){let e=Math.min(Math.max(0,t*n.h-r/2),n.h-r);return{x:n.x,y:n.y+e,w:n.w,h:r}}function Yg(n,r,t,e){let i=n.w*t/r;if(i<=n.h)return _s(n,i,e);let o=n.h*r/t;return{x:n.x+(n.w-o)/2,y:n.y,w:o,h:n.h}}function Xs(n,r,t){if(n.w*t>n.h*r){let i=n.h*r/t;return{x:n.x+(n.w-i)/2,y:n.y,w:i,h:n.h}}let e=n.w*t/r;return{x:n.x,y:n.y+(n.h-e)/2,w:n.w,h:e}}function Pg(n,r){let t=Math.min(1,Og/Math.max(r.w,r.h));return Lr(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Bs(n,r,t,e,i){let o=Qg*n.h,s=n.w*t/r;if(i<Ug||s>o)return{crop:Yg(n,r,t,e),at:{x:0,y:0,w:r,h:t},inset:!1};let u=1-s/o,c=t*(1-zs*u),h=n.w*c/o;return{crop:_s(n,o,e),at:{x:(r-h)*Zg,y:t-c,w:h,h:c},inset:!0}}function xs(n,r,t,e){let i=Math.max(1,Math.round(r.at.w)),o=Math.max(1,Math.round(r.at.h)),s=Lr(n,r.crop,i,o),u=new Uint8Array(t*e*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<o;f++){let g=h+f,l=Math.max(0,-c),$=Math.min(i,t-c);if(g<0||g>=e||$<=l)continue;u.set(s.data.subarray((f*i+l)*4,(f*i+$)*4),(g*t+c+l)*4)}return{width:t,height:e,data:u}}function zg(n,r,t,e){let i=Bs(r,Vn.width,Vn.height,t,e);return i.inset?xs(n,i,Vn.width,Vn.height):Lr(n,i.crop,Vn.width,Vn.height)}function Ds(n,r,t,e,i,o){let s=Cs(n),u=Bs(s,Vn.width,Vn.height,Ts(s),o),c;if(u.inset){let h=Xs({x:0,y:0,w:Vn.width,h:Vn.height},e,i),f=e/h.w;c=xs(n,{...u,at:{x:(u.at.x-h.x)*f,y:(u.at.y-h.y)*f,w:u.at.w*f,h:u.at.h*f}},e,i)}else c=Lr(n,Xs(u.crop,e,i),e,i);return Vg(Ae(c,r.background,t.color),r.background,t.opacity)}function Zr(n){return Fn(n,"ttheme","backgrounds")}function Ag(n,r,t,e,i){return[...e?[`# from ${e}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = center",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
36
36
  `)}function nu(n,r,t){let e=new Map;for(let s of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=Ys(Fn(n,s),"utf8")}catch{if(s===`${r}.conf`)return;continue}for(let c of u.split(`
37
- `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(c);if(h)e.set(h[1],h[2])}}let i=e.get("background-image")??"";if(i==="")return;let o=Number(e.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Fn(t,i.slice(2)):yg(i)?i:Fn(n,i),opacity:Number.isFinite(o)?o:1,cover:e.get("background-image-fit")==="cover"}}function Cg(n,r){for(let t of kr(n))if(Ce(t,r))Lr(Fn(n,t))}function Tg(n){return`${n.site}_${n.id}`}function Vt(n,r){return Fn(n,Wg,r)}function Ce(n,r){let t=n.slice(r.length);return n.startsWith(r)&&(t===".conf"||t===".tune.conf"||t===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(t))}function ft(n,r){try{return/^# image (\S+)$/m.exec(Ys(Fn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function _g(n,r){try{return kr(Vt(n,r))}catch{return[]}}function ru(n,r){let t=ft(n,r);return[...t?[t]:[],..._g(n,r)].sort()}function tu(n,r){let t=ft(n,r);if(!t)return;let e=Fn(Vt(n,r),t);Lr(e,{recursive:!0,force:!0}),Vs(e,{recursive:!0});for(let i of kr(n))if(Ce(i,r))Ps(Fn(n,i),Fn(e,i.slice(r.length)))}function eu(n,r,t){let e=Fn(Vt(n,r),t);for(let i of kr(e))Ps(Fn(e,i),Fn(n,`${r}${i}`));Lr(e,{recursive:!0})}function iu(n,r,t){try{return kr(Fn(n,"originals")).find((e)=>e.startsWith(`${r}-${t}.`))}catch{return}}function ou(n,r,t){let e=iu(n,r,t);if(e){let i=new Date;Rg(Fn(n,"originals",e),i,i)}}function su(n,r,t){let e=Qr(n),i=ru(e,r),o=ft(e,r);if(!o||i.length<2)throw Error(`${r} has no other image`);let s=(i.indexOf(o)+t+i.length)%i.length,u=i[s];return tu(e,r),eu(e,r,u),ou(e,r,u),{key:u,at:s+1,of:i.length}}function uu(n,r){let t=Qr(n),e=kr(t).filter((h)=>Ce(h,r));if(e.length===0)throw Error(`${r} has no image`);let i=ru(t,r),o=ft(t,r),s=o&&iu(t,r,o);if(s)Lr(Fn(t,"originals",s));for(let h of e)Lr(Fn(t,h));let u=i.filter((h)=>h!==o),c=u[(o?i.indexOf(o):0)%u.length];if(c)eu(t,r,c),ou(t,r,c);return{key:o,left:u.length}}function Bg(n,r,t){if(ft(n,r)!==t)tu(n,r);if(t)Lr(Fn(Vt(n,r),t),{recursive:!0,force:!0});Cg(n,r)}function cu(n,r,t,e,i){let o=Qr(n),s=r.name,u=Tg(i);Vs(Fn(o,"originals"),{recursive:!0}),Bg(o,s,u);let c=Cs(e),h=Ts(c),f=Wt(e),g=yr(Ae(Pg(e,c),r.background,t.color)),l=yr(Ae(zg(e,c,h,f),r.background,t.color)),$=Fn(o,`${s}.${Jg("sha1").update(g).update(l).digest("hex").slice(0,8)}`),a=`${$}.png`,w=`${$}@fill-${Math.round(h*100)}.png`,F=Fn(o,`${s}.conf`),v=Fn(o,"originals",`${s}-${i.site}_${i.id}.${i.ext}`);return Xt(a,g),Xt(w,l),Xt(F,Ag(s,w,t.opacity,i.from,u)),Xt(v,i.bytes),[a,w,F,v]}function hu(n){let r=Fn(Qr(n),"originals"),t=new Map,e;try{e=kr(r)}catch{return new Map}for(let i of e){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=Kg(Fn(r,i)).mtimeMs,f=t.get(s);if(!f||h>f.at)t.set(s,{site:u,id:Number(c),at:h})}return new Map([...t].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}import{readdirSync as xg,rmSync as Dg,statSync as nl}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as rl}from"node:net";import{homedir as tl}from"node:os";import{join as lt}from"node:path";import{setTimeout as el}from"node:timers/promises";var mt=100,Te=25000000,il=536870912,zt=["safe","questionable","explicit"],Mr=["nudity","underwear"],ol={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},gt={safe:"s",questionable:"q",explicit:"e"},lu=new Set(["danbooru","gelbooru","konachan","yande.re","sankaku"]),sl=8191,ul=20000,cl=3000,mu=60000,hl=3,fl=`ttheme/${Dn.version} (+${Dn.homepage})`,gl=["orig","tile","thumb","cut"],du=new Map,ll=kl(process.env.TTHEME_FIND_HOSTS),ml=El(process.env.TTHEME_FIND_CUTOUTS);rl(cl);function fu(n){try{return xg(n)}catch{return[]}}function dt(n){return n.startsWith("//")?`https:${n}`:n}function Zr(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function _e(n){let r=n.trim();if(!r)return[];let t=JSON.parse(r);if(Array.isArray(t))return t;let e=t.posts;return Array.isArray(e)?e:[]}function dl(n){let r=n.trim(),e=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(e).map(([i,o])=>[i,String(o)]))}function Yt(n,r,t){let e=dt(String(n??""));return{file:e,width:Number(r)||0,height:Number(t)||0,ext:Zr(e)}}function Be(n,r){let t=dt(String(r.preview??""));if(!r.file||!t||!Number(n.id))return[];let e=Number(n.width??n.image_width)||0,i=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:e,height:i,file:r.file,preview:t,ext:r.ext,owner:String(r.owner??""),artist:r.artist,score:Number(n.score)||0,rating:String(n.rating??""),md5:String(r.md5??""),source:String(n.source??""),tags:r.tags.split(/\s+/).filter(Boolean),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<e*i)}]}function $l(n,r="https://safebooru.org"){return _e(n).flatMap((t)=>{let e=t.directory&&t.image?`${r}/images/${t.directory}/${t.image}`:"",i=dt(String(t.file_url||e));return Be(t,{preview:t.preview_url,file:i,ext:Zr(i),owner:t.owner,artist:"",md5:t.hash??t.md5,tags:String(t.tags??""),versions:[Yt(t.sample_url,t.sample_width,t.sample_height)]})})}function al(n){let r=dl(n);return _e(n).flatMap((t)=>{let e=dt(String(t.file_url??"")),i=String(t.tags??"");return Be(t,{preview:t.preview_url,file:e,ext:String(t.file_ext||Zr(e)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:t.md5,tags:i,versions:[Yt(t.jpeg_url,t.jpeg_width,t.jpeg_height),Yt(t.sample_url,t.sample_width,t.sample_height)]})})}function bl(n){return _e(n).flatMap((r)=>{let t=dt(String(r.file_url??"")),e=r.media_asset??{};return Be(r,{preview:r.preview_file_url,file:t,ext:String(r.file_ext||Zr(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:String(r.tag_string??""),versions:(e.variants??[]).map((i)=>Yt(i.url,i.width,i.height)).filter((i)=>i.ext==="jpg"||i.ext==="png").sort((i,o)=>o.width*o.height-i.width*i.height)})})}function $u(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function wl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function El(n){let r=new Map;for(let t of(n??"").split(/\s+/).filter(Boolean)){let e=t.indexOf("=");if(e>0)r.set(t.slice(0,e),t.slice(e+1).split(",").filter(Boolean))}return r}function kl(n){let r=new Map;for(let t of(n??"").split(/[\s,]+/).filter(Boolean)){let e=t.indexOf("="),i=t.slice(0,e);try{let o=new URL(t.slice(e+1));if(i&&o.protocol==="https:")r.set(i,o.origin)}catch{}}return r}function au(n,r,t,e){let i=(n??"").split(/\s+/);if(e!==void 0&&i.includes(e))return[];let o=r.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function At(n){return au(n,zt,["safe"])}function Ct(n){return au(n,Mr,Mr,"none")}function xe(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function De(n){let r=ll.get(n.key),t=ml.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:t??n.cutouts,vouched:n.vouched&&t===void 0}}function ni(n,r){if(n.length<2)return n.join("");return r?`( ${n.join(" ~ ")} )`:n.map((t)=>`~${t}`).join(" ")}function Ml(n){let r=De(n),t=(e)=>`${r.origin}/index.php?${new URLSearchParams({page:"dapi",s:"post",q:"index",...e})}`;return{...r,cutouts:ni(r.cutouts,!0),ratings:xe(["safe","general"],["questionable"],["explicit"]),rate:()=>"",best:"sort:score:desc",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>t({json:"1",limit:String(mt),pid:String(i),tags:e}),countUrl:(e)=>t({limit:"0",tags:e}),postUrl:(e)=>t({json:"1",id:String(e)}),pageUrl:(e)=>`${r.origin}/index.php?page=post&s=view&id=${e}`,parse:(e)=>$l(e,r.origin),count:$u}}function gu(n){let r=De(n),t=(e)=>new URLSearchParams({api_version:"2",include_tags:"1",...e});return{...r,cutouts:ni(r.cutouts,!1),ratings:xe([gt.safe],[gt.questionable],[gt.explicit]),rate:(e)=>{let[i]=e;if(e.length===1&&i)return`rating:${gt[i]}`;let o=zt.filter((u)=>!e.includes(u)),[s]=o;return o.length===1&&s?`-rating:${gt[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>`${r.origin}/post.json?${t({limit:String(mt),page:String(i+1),tags:e})}`,countUrl:(e)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:e})}`,postUrl:(e)=>`${r.origin}/post.json?${t({tags:`id:${e}`})}`,pageUrl:(e)=>`${r.origin}/post/show/${e}`,parse:al,count:$u}}function Fl(n){let r=De(n);return{...r,cutouts:ni(r.cutouts,!1),ratings:xe(["g"],["s","q"],["e"]),rate:()=>"",best:"order:score",tagBudget:2,postsUrl:(t,e)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(mt),page:String(e+1),tags:t})}`,countUrl:(t)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:t})}`,postUrl:(t)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/posts/${t}`,parse:bl,count:wl}}function Il(n){return Yn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function ri(n){return n.split(/\s+/).filter(Boolean).length}function bu(n,r){let t=n.trim();if(/^\d+$/.test(t))return{site:r,id:Number(t)};let e=/^([\w.]+):(\d+)$/.exec(t);if(e){let u=Yn.find((c)=>c.key===e[1]||c.name===e[1]);return u&&{site:u,id:Number(e[2])}}let i;try{i=new URL(t)}catch{return}let o=Il(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var Yn=[Ml({key:"safebooru",name:"safebooru",origin:"https://safebooru.org",cutouts:["transparent_background","vector_trace"],vouched:!1,ansi:4}),gu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),gu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Fl({key:"danbooru",name:"danbooru",origin:"https://safebooru.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2})];function wu(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function Eu(n,r=Mr){return n.tags.filter((t)=>r.some((e)=>ol[e].has(t)))}function ku(n,r,t=["safe"]){return t.some((e)=>n.ratings[e].has(r.rating))}function $t(n){return[n,...n.smaller].find((r)=>r.width*r.height<=Te)}function Mu(n){return lu.has(n)}function Fu(n){let r=new Map;for(let[t,e]of[...n].sort(([i],[o])=>i<o?-1:1)){if(e===""||lu.has(e))continue;r.set(e,[...r.get(e)??[],t])}return r}function Iu(){return lt(process.env.XDG_CACHE_HOME??lt(tl(),".cache"),"ttheme")}function mr(n){return lt(Iu(),n.key)}function vu(n=il,r=Iu()){let t=[],e=0;for(let i of fu(r))for(let o of gl){let s=lt(r,i,o);for(let u of fu(s)){let c=lt(s,u);try{let{size:h,mtimeMs:f}=nl(c);t.push({path:c,size:h,at:f}),e+=h}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(e<=n)return;try{Dg(i.path,{force:!0}),e-=i.size}catch{}}}function vl(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let t=n===null?Number.NaN:Date.parse(n);return Number.isNaN(t)?mu:Math.max(0,t-r)}function Pt(n){return du.get(n.key)??0}function pl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function at(n,r,t,e={},i=ul){for(let o=1;;o++){let s=Pt(n)-Date.now();if(s>0)await el(s,void 0,{signal:t});let u=await fetch(r,{headers:{"User-Agent":fl,Referer:`${n.origin}/`,...e},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t});if(u.status===429&&o<hl){await u.body?.cancel();let c=vl(u.headers.get("retry-after"),Date.now());if(c>mu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);du.set(n.key,Math.max(Pt(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(pl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function pu(n,r,t,e){return n.parse(await(await at(n,n.postsUrl(r,t),e)).text())}async function Nu(n,r,t){return n.count(await(await at(n,n.countUrl(r),t)).text())}async function ti(n,r,t){let[e]=n.parse(await(await at(n,n.postUrl(r),t)).text());return e}async function Hu(n,r,t){let e=await at(n,r,t,{Range:`bytes=0-${sl}`});return Pe(new Uint8Array(await e.arrayBuffer()))}async function Su(n,r,t,e){let i=await at(n,r,t,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:g,value:l}=await s.read();if(g)break;u.push(l),c+=l.length,e?.(c,o)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}import{existsSync as Nl,mkdirSync as Hl,readFileSync as Sl,writeFileSync as jl}from"node:fs";import{dirname as Gl,join as Jl}from"node:path";var ju="https://kecan0406.github.io/ttheme/manifest.json",Kl=20000;function Tt(n){return Jl(n,"ttheme","catalog.json")}function _t(n,r){let t=Tt(n);Hl(Gl(t),{recursive:!0}),jl(t,`${JSON.stringify(r,null,2)}
38
- `)}function Qn(n){let r=Tt(n);if(!Nl(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return Gu(Sl(r,"utf8"))}function Gu(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let t=r;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let e of t.palettes)if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(e?.name)} is missing name or its 16 ANSI colors`);return t}async function Ju(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(Kl)})}catch(t){throw Error(`cannot reach the registry at ${n} — ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return Gu(await r.text())}function Ku(n){let r=new Set(n.waived??[]);return Rt.flatMap((t,e)=>{let i=n.gate?.[e];if(r.has(t.rule)||typeof i!=="number")return[];if(t.min!==void 0&&i<t.min)return[`${t.label} ${i} < ${t.min}`];if(t.max!==void 0&&i>t.max)return[`${t.label} ${i} > ${t.max}`];return[]})}function Bt(n,r){let t=n.find((e)=>e.name===r);if(!t)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return t}function Ru(n,r){let t=r.toLowerCase();return n.filter((e)=>[e.name,e.group,e.native??"",e.ansiSource].some((i)=>i.toLowerCase().includes(t)))}import{spawn as Rl}from"node:child_process";var yl=30000,Ol=3,Ll=97,Ql=`ObjC.import('Vision')
37
+ `)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(c);if(h)e.set(h[1],h[2])}}let i=e.get("background-image")??"";if(i==="")return;let o=Number(e.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Fn(t,i.slice(2)):yg(i)?i:Fn(n,i),opacity:Number.isFinite(o)?o:1,cover:e.get("background-image-fit")==="cover"}}function Cg(n,r){for(let t of Mr(n))if(Ce(t,r))Qr(Fn(n,t))}function Tg(n){return`${n.site}_${n.id}`}function Yt(n,r){return Fn(n,Wg,r)}function Ce(n,r){let t=n.slice(r.length);return n.startsWith(r)&&(t===".conf"||t===".tune.conf"||t===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(t))}function ft(n,r){try{return/^# image (\S+)$/m.exec(Ys(Fn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function _g(n,r){try{return Mr(Yt(n,r))}catch{return[]}}function ru(n,r){let t=ft(n,r);return[...t?[t]:[],..._g(n,r)].sort()}function tu(n,r){let t=ft(n,r);if(!t)return;let e=Fn(Yt(n,r),t);Qr(e,{recursive:!0,force:!0}),Vs(e,{recursive:!0});for(let i of Mr(n))if(Ce(i,r))Ps(Fn(n,i),Fn(e,i.slice(r.length)))}function eu(n,r,t){let e=Fn(Yt(n,r),t);for(let i of Mr(e))Ps(Fn(e,i),Fn(n,`${r}${i}`));Qr(e,{recursive:!0})}function iu(n,r,t){try{return Mr(Fn(n,"originals")).find((e)=>e.startsWith(`${r}-${t}.`))}catch{return}}function ou(n,r,t){let e=iu(n,r,t);if(e){let i=new Date;Rg(Fn(n,"originals",e),i,i)}}function su(n,r,t){let e=Zr(n),i=ru(e,r),o=ft(e,r);if(!o||i.length<2)throw Error(`${r} has no other image`);let s=(i.indexOf(o)+t+i.length)%i.length,u=i[s];return tu(e,r),eu(e,r,u),ou(e,r,u),{key:u,at:s+1,of:i.length}}function uu(n,r){let t=Zr(n),e=Mr(t).filter((h)=>Ce(h,r));if(e.length===0)throw Error(`${r} has no image`);let i=ru(t,r),o=ft(t,r),s=o&&iu(t,r,o);if(s)Qr(Fn(t,"originals",s));for(let h of e)Qr(Fn(t,h));let u=i.filter((h)=>h!==o),c=u[(o?i.indexOf(o):0)%u.length];if(c)eu(t,r,c),ou(t,r,c);return{key:o,left:u.length}}function Bg(n,r,t){if(ft(n,r)!==t)tu(n,r);if(t)Qr(Fn(Yt(n,r),t),{recursive:!0,force:!0});Cg(n,r)}function cu(n,r,t,e,i){let o=Zr(n),s=r.name,u=Tg(i);Vs(Fn(o,"originals"),{recursive:!0}),Bg(o,s,u);let c=Cs(e),h=Ts(c),f=Xt(e),g=Or(Ae(Pg(e,c),r.background,t.color)),l=Or(Ae(zg(e,c,h,f),r.background,t.color)),$=Fn(o,`${s}.${Jg("sha1").update(g).update(l).digest("hex").slice(0,8)}`),a=`${$}.png`,w=`${$}@fill-${Math.round(h*100)}.png`,F=Fn(o,`${s}.conf`),v=Fn(o,"originals",`${s}-${i.site}_${i.id}.${i.ext}`);return Vt(a,g),Vt(w,l),Vt(F,Ag(s,w,t.opacity,i.from,u)),Vt(v,i.bytes),[a,w,F,v]}function hu(n){let r=Fn(Zr(n),"originals"),t=new Map,e;try{e=Mr(r)}catch{return new Map}for(let i of e){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,u,c]=o??[];if(!s||!u||!c)continue;let h=Kg(Fn(r,i)).mtimeMs,f=t.get(s);if(!f||h>f.at)t.set(s,{site:u,id:Number(c),at:h})}return new Map([...t].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}import{readdirSync as xg,rmSync as Dg,statSync as nl}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as rl}from"node:net";import{homedir as tl}from"node:os";import{join as lt}from"node:path";import{setTimeout as el}from"node:timers/promises";var mt=100,Te=25000000,il=536870912,At=["safe","questionable","explicit"],Fr=["nudity","underwear"],ol={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},gt={safe:"s",questionable:"q",explicit:"e"},lu=new Set(["danbooru","gelbooru","konachan","yande.re","sankaku"]),sl=8191,ul=20000,cl=3000,mu=60000,hl=3,fl=`ttheme/${Dn.version} (+${Dn.homepage})`,gl=["orig","tile","thumb","cut"],du=new Map,ll=kl(process.env.TTHEME_FIND_HOSTS),ml=El(process.env.TTHEME_FIND_CUTOUTS);rl(cl);function fu(n){try{return xg(n)}catch{return[]}}function dt(n){return n.startsWith("//")?`https:${n}`:n}function Ur(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function _e(n){let r=n.trim();if(!r)return[];let t=JSON.parse(r);if(Array.isArray(t))return t;let e=t.posts;return Array.isArray(e)?e:[]}function dl(n){let r=n.trim(),e=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(e).map(([i,o])=>[i,String(o)]))}function Pt(n,r,t){let e=dt(String(n??""));return{file:e,width:Number(r)||0,height:Number(t)||0,ext:Ur(e)}}function Be(n,r){let t=dt(String(r.preview??""));if(!r.file||!t||!Number(n.id))return[];let e=Number(n.width??n.image_width)||0,i=Number(n.height??n.image_height)||0;return[{id:Number(n.id),width:e,height:i,file:r.file,preview:t,ext:r.ext,owner:String(r.owner??""),artist:r.artist,score:Number(n.score)||0,rating:String(n.rating??""),md5:String(r.md5??""),source:String(n.source??""),tags:r.tags.split(/\s+/).filter(Boolean),smaller:r.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<e*i)}]}function $l(n,r="https://safebooru.org"){return _e(n).flatMap((t)=>{let e=t.directory&&t.image?`${r}/images/${t.directory}/${t.image}`:"",i=dt(String(t.file_url||e));return Be(t,{preview:t.preview_url,file:i,ext:Ur(i),owner:t.owner,artist:"",md5:t.hash??t.md5,tags:String(t.tags??""),versions:[Pt(t.sample_url,t.sample_width,t.sample_height)]})})}function al(n){let r=dl(n);return _e(n).flatMap((t)=>{let e=dt(String(t.file_url??"")),i=String(t.tags??"");return Be(t,{preview:t.preview_url,file:e,ext:String(t.file_ext||Ur(e)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>r.get(o)==="artist")??"",md5:t.md5,tags:i,versions:[Pt(t.jpeg_url,t.jpeg_width,t.jpeg_height),Pt(t.sample_url,t.sample_width,t.sample_height)]})})}function bl(n){return _e(n).flatMap((r)=>{let t=dt(String(r.file_url??"")),e=r.media_asset??{};return Be(r,{preview:r.preview_file_url,file:t,ext:String(r.file_ext||Ur(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:String(r.tag_string??""),versions:(e.variants??[]).map((i)=>Pt(i.url,i.width,i.height)).filter((i)=>i.ext==="jpg"||i.ext==="png").sort((i,o)=>o.width*o.height-i.width*i.height)})})}function $u(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function wl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function El(n){let r=new Map;for(let t of(n??"").split(/\s+/).filter(Boolean)){let e=t.indexOf("=");if(e>0)r.set(t.slice(0,e),t.slice(e+1).split(",").filter(Boolean))}return r}function kl(n){let r=new Map;for(let t of(n??"").split(/[\s,]+/).filter(Boolean)){let e=t.indexOf("="),i=t.slice(0,e);try{let o=new URL(t.slice(e+1));if(i&&o.protocol==="https:")r.set(i,o.origin)}catch{}}return r}function au(n,r,t,e){let i=(n??"").split(/\s+/);if(e!==void 0&&i.includes(e))return[];let o=r.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function Ct(n){return au(n,At,["safe"])}function Tt(n){return au(n,Fr,Fr,"none")}function xe(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function De(n){let r=ll.get(n.key),t=ml.get(n.key);return{...n,origin:r??n.origin,moved:r!==void 0&&r!==n.origin,cutouts:t??n.cutouts,vouched:n.vouched&&t===void 0}}function ni(n,r){if(n.length<2)return n.join("");return r?`( ${n.join(" ~ ")} )`:n.map((t)=>`~${t}`).join(" ")}function Ml(n){let r=De(n),t=(e)=>`${r.origin}/index.php?${new URLSearchParams({page:"dapi",s:"post",q:"index",...e})}`;return{...r,cutouts:ni(r.cutouts,!0),ratings:xe(["safe","general"],["questionable"],["explicit"]),rate:()=>"",best:"sort:score:desc",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>t({json:"1",limit:String(mt),pid:String(i),tags:e}),countUrl:(e)=>t({limit:"0",tags:e}),postUrl:(e)=>t({json:"1",id:String(e)}),pageUrl:(e)=>`${r.origin}/index.php?page=post&s=view&id=${e}`,parse:(e)=>$l(e,r.origin),count:$u}}function gu(n){let r=De(n),t=(e)=>new URLSearchParams({api_version:"2",include_tags:"1",...e});return{...r,cutouts:ni(r.cutouts,!1),ratings:xe([gt.safe],[gt.questionable],[gt.explicit]),rate:(e)=>{let[i]=e;if(e.length===1&&i)return`rating:${gt[i]}`;let o=At.filter((u)=>!e.includes(u)),[s]=o;return o.length===1&&s?`-rating:${gt[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>`${r.origin}/post.json?${t({limit:String(mt),page:String(i+1),tags:e})}`,countUrl:(e)=>`${r.origin}/post.xml?${new URLSearchParams({limit:"1",tags:e})}`,postUrl:(e)=>`${r.origin}/post.json?${t({tags:`id:${e}`})}`,pageUrl:(e)=>`${r.origin}/post/show/${e}`,parse:al,count:$u}}function Fl(n){let r=De(n);return{...r,cutouts:ni(r.cutouts,!1),ratings:xe(["g"],["s","q"],["e"]),rate:()=>"",best:"order:score",tagBudget:2,postsUrl:(t,e)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(mt),page:String(e+1),tags:t})}`,countUrl:(t)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:t})}`,postUrl:(t)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${t}`})}`,pageUrl:(t)=>`${r.origin}/posts/${t}`,parse:bl,count:wl}}function Il(n){return Yn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function ri(n){return n.split(/\s+/).filter(Boolean).length}function bu(n,r){let t=n.trim();if(/^\d+$/.test(t))return{site:r,id:Number(t)};let e=/^([\w.]+):(\d+)$/.exec(t);if(e){let u=Yn.find((c)=>c.key===e[1]||c.name===e[1]);return u&&{site:u,id:Number(e[2])}}let i;try{i=new URL(t)}catch{return}let o=Il(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var Yn=[Ml({key:"safebooru",name:"safebooru",origin:"https://safebooru.org",cutouts:["transparent_background","vector_trace"],vouched:!1,ansi:4}),gu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),gu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Fl({key:"danbooru",name:"danbooru",origin:"https://safebooru.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2})];function wu(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function Eu(n,r=Fr){return n.tags.filter((t)=>r.some((e)=>ol[e].has(t)))}function ku(n,r,t=["safe"]){return t.some((e)=>n.ratings[e].has(r.rating))}function $t(n){return[n,...n.smaller].find((r)=>r.width*r.height<=Te)}function Mu(n){return lu.has(n)}function Fu(n){let r=new Map;for(let[t,e]of[...n].sort(([i],[o])=>i<o?-1:1)){if(e===""||lu.has(e))continue;r.set(e,[...r.get(e)??[],t])}return r}function Iu(){return lt(process.env.XDG_CACHE_HOME??lt(tl(),".cache"),"ttheme")}function $r(n){return lt(Iu(),n.key)}function vu(n=il,r=Iu()){let t=[],e=0;for(let i of fu(r))for(let o of gl){let s=lt(r,i,o);for(let u of fu(s)){let c=lt(s,u);try{let{size:h,mtimeMs:f}=nl(c);t.push({path:c,size:h,at:f}),e+=h}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(e<=n)return;try{Dg(i.path,{force:!0}),e-=i.size}catch{}}}function vl(n,r){if(n!==null&&/^\s*\d+\s*$/.test(n))return Number(n)*1000;let t=n===null?Number.NaN:Date.parse(n);return Number.isNaN(t)?mu:Math.max(0,t-r)}function zt(n){return du.get(n.key)??0}function Nl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function at(n,r,t,e={},i=ul){for(let o=1;;o++){let s=zt(n)-Date.now();if(s>0)await el(s,void 0,{signal:t});let u=await fetch(r,{headers:{"User-Agent":fl,Referer:`${n.origin}/`,...e},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t});if(u.status===429&&o<hl){await u.body?.cancel();let c=vl(u.headers.get("retry-after"),Date.now());if(c>mu)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);du.set(n.key,Math.max(zt(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(Nl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function Nu(n,r,t,e){return n.parse(await(await at(n,n.postsUrl(r,t),e)).text())}async function pu(n,r,t){return n.count(await(await at(n,n.countUrl(r),t)).text())}async function ti(n,r,t){let[e]=n.parse(await(await at(n,n.postUrl(r),t)).text());return e}async function Hu(n,r,t){let e=await at(n,r,t,{Range:`bytes=0-${sl}`});return Pe(new Uint8Array(await e.arrayBuffer()))}async function Su(n,r,t,e){let i=await at(n,r,t,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:g,value:l}=await s.read();if(g)break;u.push(l),c+=l.length,e?.(c,o)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}import{existsSync as pl,mkdirSync as Hl,readFileSync as Sl,writeFileSync as jl}from"node:fs";import{dirname as Gl,join as Jl}from"node:path";var ju="https://kecan0406.github.io/ttheme/manifest.json",Kl=20000;function _t(n){return Jl(n,"ttheme","catalog.json")}function Bt(n,r){let t=_t(n);Hl(Gl(t),{recursive:!0}),jl(t,`${JSON.stringify(r,null,2)}
38
+ `)}function Qn(n){let r=_t(n);if(!pl(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return Gu(Sl(r,"utf8"))}function Gu(n){let r;try{r=JSON.parse(n)}catch{throw Error("catalog is not valid JSON")}let t=r;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let e of t.palettes)if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(e?.name)} is missing name or its 16 ANSI colors`);return t}async function Ju(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(Kl)})}catch(t){throw Error(`cannot reach the registry at ${n} — ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw Error(`registry at ${n} answered ${r.status}`);return Gu(await r.text())}function Ku(n){let r=new Set(n.waived??[]);return yt.flatMap((t,e)=>{let i=n.gate?.[e];if(r.has(t.rule)||typeof i!=="number")return[];if(t.min!==void 0&&i<t.min)return[`${t.label} ${i} < ${t.min}`];if(t.max!==void 0&&i>t.max)return[`${t.label} ${i} > ${t.max}`];return[]})}function xt(n,r){let t=n.find((e)=>e.name===r);if(!t)throw Error(`no palette named ${r} in the catalog — \`ttheme list\` shows what is there`);return t}function Ru(n,r){let t=r.toLowerCase();return n.filter((e)=>[e.name,e.group,e.native??"",e.ansiSource].some((i)=>i.toLowerCase().includes(t)))}import{spawn as Rl}from"node:child_process";var yl=30000,Ol=3,Ll=97,Ql=`ObjC.import('Vision')
39
39
  ObjC.import('CoreImage')
40
40
  ObjC.import('CoreGraphics')
41
41
  function run(argv) {
@@ -55,54 +55,54 @@ function run(argv) {
55
55
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
56
56
  if (!written) throw new Error('write failed')
57
57
  }`;function ei(){return process.platform==="darwin"}function yu(n){return n>=Ol&&n<=Ll}function Ou(n,r,t){return new Promise((e,i)=>{let o=Rl("osascript",["-l","JavaScript","-e",Ql,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(yl)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){e();return}i(Error(s.trim().split(`
58
- `).at(-1)||`osascript exited ${u}`))})})}var Ln={pitch:25,cols:22,rows:9,height:13},Ir={cols:25,rows:16},Zl=2147483648,Ul=-1073741826,ql=1600,Wl="\x1B[0m",vr="\x1B[1m",bn="\x1B[2m",bt="\x1B[31m",Fr="\x1B[32m",Pn="\x1B[33m",xt="\x1B[1;34m",Xl="\x1B[35m",Vl={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn"};function Qu(n){let r=[],t=0;while(t<n.length){let e=n[t]??"";if(e==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(t+1));if(i){r.push(Vl[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}r.push("esc"),t++;continue}r.push(e==="\r"||e===`
59
- `?"enter":e==="\t"?"tab":e==="\x03"?"ctrl-c":e===""||e==="\b"?"backspace":e),t++}return r}var Zu="\x1B]1337;ReportCellSize\x07\x1B[16t",Lu="\x1B]1337;ReportCellSize=";function ui(n){let r=n.indexOf(Lu);if(r!==-1){let i=n.slice(r+Lu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:n.slice(0,r)+i.slice(s+(i[s]==="\x07"?1:2))}}}let t=n.indexOf("\x1B[6;"),e=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(n.slice(t+1));if(!e)return null;return{cell:{h:Number(e[1]),w:Number(e[2])},rest:n.slice(0,t)+n.slice(t+1+e[0].length)}}function Et(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Ln.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Ln.height))}}function Uu(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function qu(n){return`\x1B[${n.row+1};${n.col+1}H\x1B_Ga=p,i=${n.id},p=${n.id},c=${n.cols},r=${n.rows},C=1,z=${n.z},q=2\x1B\\`}function Wu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function Xu(n){return`\x1B[38;2;${On(n).join(";")}m`}function ii(n){return`\x1B[48;2;${On(n).join(";")}m`}function rr(n){return Array.from(n).length}class oi{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+rr(r)}run(n,r){let t=n;for(let[e,i]of r)t=this.put(t,e,i);return t}right(n,r){this.run(n-r.reduce((t,[e])=>t+rr(e),0),r)}render(){let n="";for(let{col:r,text:t,sgr:e}of this.parts){if(r>=this.cols||r<0)continue;let i=Array.from(t).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${e}${i}${e?Wl:""}`}return n}}function Vu(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Yl(n,r){if(!r)return Vu(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Yu(n){return n.replace(/_\([^)]*\)?$/,"")}function Pu(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<ql?Pn:bn]}function wt(n,r,t,e){let i=[...e.keys??[]],o=e.lead,s=e.right,u=()=>{let f=[...o?[rr(o[0])]:[],...i.map(([l,$])=>rr(l)+1+rr($))];return(e.badge?rr(e.badge)+4:0)+f.reduce((l,$)=>l+$,0)+3*Math.max(0,f.length-1)+(s?3+rr(s[0])+1+rr(s[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>r){let f=Math.max(0,rr(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(e.badge)c=n.put(0,` ${e.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([f,g])=>[[f,vr],[` ${g}`,bn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),s)n.right(r,[[s[0],vr],[` ${s[1]}`,bn]])}function Pl(n,r,t,e,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=e<44?3:4;if(e>=56)h=Math.min(7,Math.floor((e+1)/8)-1);let f=t;for(let a=0;a<8;a++)f=(n[r]?.put(f,"▀".repeat(h),Xu(s[a]??c)+ii(s[a+8]??c))??f)+1;let g=["❯ ",Fr],l=[[["~/code/demo",xt],[" on ",bn],["main",Xl],[" +2",Fr],[" ~1",Pn]]];if(l.push([g,["git status -sb",""]]),e>=44)l.push([["## ",""],["main",Fr],["...",""],["origin/main",bt],[" [ahead 1]",Pn]]);if(l.push([[" M",bt],[" src/main.rs",""]]),l.push([["??",bt],[" notes.md",""]]),l.push([]),e>=44)l.push([g,["ls",""]]),l.push([["docs",xt],[" ",""],["src",xt],[" ",""],["tests",xt],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",Fr],[" parses config",""]]);let $=[[" ✗",bt],[" renders frame",""]];if(e>=44)$.push([" expected ",bn],["3",Fr],[", received ",bn],["2",bt]);l.push($),l.push([]),l.push([g,["echo ",""],["selected text",ii(u)],[" ",""],[" ",ii(c)]]),l.forEach((a,w)=>{let F=r+2+w;if(F<=i)n[F]?.run(t,a)})}function zl(n,r,t,e,i,o){n[r]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=r+1;s<r+e-1;s++)n[s]?.put(t,"│",o),n[s]?.put(t+i-1,"│",o);n[r+e-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function si(n,r=n.site){return[` ${r} `,`\x1B[7;${30+n.siteAnsi}m`]}function Al(n,r,t){let e=Yn.flatMap((o,s)=>{let u=`${o.name}${o.moved?"*":""}`,c=o.name===t.site?si(t,u):[` ${u} `,bn];return s?[[" ",""],c]:[c]}),i=e.reduce((o,[s])=>o+rr(s),0)<=r;n.run(0,i?e:[si(t)])}function Cl(n,r,t,e){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",e],[t.editing,""],["█",e]]);n.put(u,t.editing?" enter searches":` a tag, a post url or an id — ${t.tag||"esc leaves"}`,bn);return}let i=n.run(0,[["⌕ ",e],[t.tag||"nothing yet — / searches",t.tag?"":bn]]),o=Mr.filter((u)=>!t.block.includes(u)),s=[t.preset,t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(i,` ${s.join(" ")}`,bn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,bn]);n.right(r,u)}}function Tl(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,Fr]];if(n.cut==="off")return[["opaque · x cuts out",Pn]];if(n.cut==="failed")return[["opaque · no cut-out",Pn]];return[n.clear>0?[`${n.clear}% transparent`,Fr]:["opaque",Pn]]}function zu(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${n.site} ${n.installing}`,Pn];if(n.error)return[n.error,Pn];if(n.waiting!==void 0)return[`${n.site} asked to slow down · ${n.waiting}s`,Pn];if(n.fetching)return[`fetching ${n.fetching.id} · ${Yl(n.fetching.got,n.fetching.size)}`,Pn];if(n.cutting!==void 0)return[`cutting out ${n.cutting}`,Pn];if(n.preparing!==void 0)return[`preparing ${n.preparing}`,Pn];if(n.note)return[n.note,bn];return}function _l(n,r,t,e,i,o){let{perRow:s,rowsVis:u}=Et(t,e);Cl(n[0],t,i,o),Al(n[1],t,i);for(let $=0;$<s*u;$++){let a=i.top*s+$,w=i.tiles[a];if(!w)break;let F=2+Math.floor($/s)*Ln.height,v=$%s*Ln.pitch,j=a===i.focus;if(j)zl(n,F,v,Ln.height,Ln.pitch-1,o);if(w.thumb)r.push({id:w.id,path:w.thumb,row:F+1,col:v+1,cols:Ln.cols,rows:Ln.rows,z:-1});if(n[F+10]?.run(v+1,[[String(w.id),j?vr:""],[" ",""],Pu(w)]),w.mates.length>0)n[F+10]?.put(v+Ln.cols,"≈",o);let M=w.artist?Yu(w.artist):w.owner&&`@${w.owner}`;if(M)n[F+11]?.put(v+1,M.slice(0,Ln.cols-8),bn);let p=[];if(w.score>0)p.push([`★${w.score}`,bn]);if(w.variants>1)p.push([` ×${w.variants}`,o]);if(p.length>0)n[F+11]?.right(v+Ln.cols+1,p)}let c=i.top*s,h=i.tiles.length-(i.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[e-2]?.put(0,f.join(" "),bn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${i.site} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${i.site} — tab tries ${i.nextSite}`,bn);let g=n[e-1],l=zu(i);if(i.searching&&i.tiles.length===0&&!l){wt(g,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",bn],right:["esc","back"]});return}wt(g,t,o,{badge:"FIND",lead:l,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function Bl(n,r,t,e,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.id?i.shown:void 0,c=[si(i),[" ",""],[String(s.id),vr],[" ",""],Pu(s)];if(s.artist)c.push([` · ${Yu(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,bn]);if(u)c.push([` · ${Vu(u.bytes)}`,bn]);if(c.push([` · ${s.owner}`,bn]),s.origin)c.push([` · ${s.origin}`,bn]);if(u)c.push([" ",""],...Tl(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(t,[["≈ ",o],[s.mates.join(" "),bn]]);if(Pl(n,3,2,t-4,e-2,i),i.shown)r.push({id:Zl+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:e,z:Ul});let h=zu(i);wt(n[e-1],t,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var xl={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab ${Yn.map((n)=>n.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["grid","esc"],["close","? esc"]]};function Dl(n,r,t,e,i){let o=e.panel??0,s=Math.max(...e.settings.map((l)=>l.label.length)),u=Math.max(...e.settings.map((l)=>l.choices.reduce(($,a)=>$+a.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=e.settings.length+4,f=Math.floor((r-c)/2),g=Math.max(2,Math.floor((t-h)/2));n[g]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=g+1;l<g+h-1;l++)n[l]?.put(f,`│${" ".repeat(c-2)}│`);e.settings.forEach((l,$)=>{let a=n[g+2+$];a.put(f+3,l.label,$===o?vr:bn);let w=f+5+s,F=l.value.split(" ");l.choices.forEach((v,j)=>{let M=F.includes(v),p=l.multi&&$===o&&j===l.cursor?"4;":"",b=l.multi?` ${M?"[x]":"[ ]"} ${v} `:` ${v} `;w=a.put(w,b,M?`\x1B[${p}7;${30+e.siteAnsi}m`:p?`\x1B[4m${bn}`:bn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),wt(n[t-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function nm(n,r,t,e,i){let o=xl[e.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((t-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([f,g],l)=>{n[h+2+l]?.put(c+3,f,vr),n[h+2+l]?.put(c+13,g.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),wt(n[t-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function Au(n,r,t){let e=Array.from({length:t},()=>new oi(r)),i=[],o=Xu(n.colors.cursor);if(r<Ir.cols||t<Ir.rows)return e[0]?.put(0,"ttheme find",vr+o),e[1]?.put(0,`needs ${Ir.cols}×${Ir.rows} — now ${r}×${t}`),e[2]?.put(0,"esc quits",bn),{lines:e.map((s)=>s.render()),images:i};if(n.mode==="try")Bl(e,i,r,t,n,o);else _l(e,i,r,t,n,o);if(n.help||n.panel!==void 0){let s=n.mode==="try"?i:[];for(let u=0;u<t;u++)e[u]=new oi(r);if(n.help)nm(e,r,t,n,o);else Dl(e,r,t,n,o);return{lines:e.map((u)=>u.render()),images:s}}return{lines:e.map((s)=>s.render()),images:i}}import{execFileSync as rm}from"node:child_process";import{existsSync as ci,mkdirSync as Dt,readFileSync as Tu,rmSync as _u,writeFileSync as ne}from"node:fs";import{homedir as hi}from"node:os";import{dirname as re,join as Tn}from"node:path";var tm={ghostty:it,kitty:st,alacritty:et,iterm2:ot},Cu="ttheme-default";function Ur(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(t,e)=>rm(t,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?r("defaults",["read",n,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(t)=>{if(process.platform==="darwin")r("defaults",["write",n,"Default Bookmark Guid","-string",t])},running:()=>{try{return r("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function qr(n){return n.keepTheme?void 0:Wr(n)}function kt(n,r){if(!n.terminals.includes("iterm2"))return n;let t=r.read();return t&&!t.startsWith("ttheme-")?{...n,itermBase:t}:n}function Mt(n,r){if(!n.terminals.includes("iterm2"))return!1;let t=r.read(),e=qr(n)?Cu:t===Cu?n.itermBase:void 0;if(!e||e===t)return!1;return r.write(e),!0}function _n(){return process.env.XDG_CONFIG_HOME??Tn(hi(),".config")}function Bu(n){return Tn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function xu(n){return Tn(n,"ttheme","installed.json")}function sr(n){let r=xu(n);if(!ci(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(Tu(r,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:t.terminals.filter((e)=>yt.includes(e)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},palettes:t.palettes}}function Ft(n,r){let t=xu(n);Dt(re(t),{recursive:!0}),ne(t,`${JSON.stringify(r,null,2)}
58
+ `).at(-1)||`osascript exited ${u}`))})})}var Ln={pitch:25,cols:22,rows:9,height:13},vr={cols:25,rows:16},Zl=2147483648,Ul=-1073741826,ql=1600,Wl="\x1B[0m",Nr="\x1B[1m",bn="\x1B[2m",bt="\x1B[31m",Ir="\x1B[32m",Pn="\x1B[33m",Dt="\x1B[1;34m",Xl="\x1B[35m",Vl={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn"};function Qu(n){let r=[],t=0;while(t<n.length){let e=n[t]??"";if(e==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(n.slice(t+1));if(i){r.push(Vl[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}r.push("esc"),t++;continue}r.push(e==="\r"||e===`
59
+ `?"enter":e==="\t"?"tab":e==="\x03"?"ctrl-c":e===""||e==="\b"?"backspace":e),t++}return r}var Zu="\x1B]1337;ReportCellSize\x07\x1B[16t",Lu="\x1B]1337;ReportCellSize=";function ui(n){let r=n.indexOf(Lu);if(r!==-1){let i=n.slice(r+Lu.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),s=o.length>0?Math.min(...o):-1,u=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(u){let c=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*c),w:Math.round(Number(u[2])*c)},rest:n.slice(0,r)+i.slice(s+(i[s]==="\x07"?1:2))}}}let t=n.indexOf("\x1B[6;"),e=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(n.slice(t+1));if(!e)return null;return{cell:{h:Number(e[1]),w:Number(e[2])},rest:n.slice(0,t)+n.slice(t+1+e[0].length)}}function Et(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Ln.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Ln.height))}}function Uu(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function qu(n){return`\x1B[${n.row+1};${n.col+1}H\x1B_Ga=p,i=${n.id},p=${n.id},c=${n.cols},r=${n.rows},C=1,z=${n.z},q=2\x1B\\`}function Wu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function Xu(n){return`\x1B[38;2;${On(n).join(";")}m`}function ii(n){return`\x1B[48;2;${On(n).join(";")}m`}function rr(n){return Array.from(n).length}class oi{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+rr(r)}run(n,r){let t=n;for(let[e,i]of r)t=this.put(t,e,i);return t}right(n,r){this.run(n-r.reduce((t,[e])=>t+rr(e),0),r)}render(){let n="";for(let{col:r,text:t,sgr:e}of this.parts){if(r>=this.cols||r<0)continue;let i=Array.from(t).slice(0,this.cols-r).join("");n+=`\x1B[${r+1}G${e}${i}${e?Wl:""}`}return n}}function Vu(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function Yl(n,r){if(!r)return Vu(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function Yu(n){return n.replace(/_\([^)]*\)?$/,"")}function Pu(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<ql?Pn:bn]}function wt(n,r,t,e){let i=[...e.keys??[]],o=e.lead,s=e.right,u=()=>{let f=[...o?[rr(o[0])]:[],...i.map(([l,$])=>rr(l)+1+rr($))];return(e.badge?rr(e.badge)+4:0)+f.reduce((l,$)=>l+$,0)+3*Math.max(0,f.length-1)+(s?3+rr(s[0])+1+rr(s[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&u()>r){let f=Math.max(0,rr(o[0])-(u()-r)-1);o=[`${Array.from(o[0]).slice(0,f).join("")}…`,o[1]]}let c=0;if(e.badge)c=n.put(0,` ${e.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([f,g])=>[[f,Nr],[` ${g}`,bn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),s)n.right(r,[[s[0],Nr],[` ${s[1]}`,bn]])}function Pl(n,r,t,e,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,h=e<44?3:4;if(e>=56)h=Math.min(7,Math.floor((e+1)/8)-1);let f=t;for(let a=0;a<8;a++)f=(n[r]?.put(f,"▀".repeat(h),Xu(s[a]??c)+ii(s[a+8]??c))??f)+1;let g=["❯ ",Ir],l=[[["~/code/demo",Dt],[" on ",bn],["main",Xl],[" +2",Ir],[" ~1",Pn]]];if(l.push([g,["git status -sb",""]]),e>=44)l.push([["## ",""],["main",Ir],["...",""],["origin/main",bt],[" [ahead 1]",Pn]]);if(l.push([[" M",bt],[" src/main.rs",""]]),l.push([["??",bt],[" notes.md",""]]),l.push([]),e>=44)l.push([g,["ls",""]]),l.push([["docs",Dt],[" ",""],["src",Dt],[" ",""],["tests",Dt],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",Ir],[" parses config",""]]);let $=[[" ✗",bt],[" renders frame",""]];if(e>=44)$.push([" expected ",bn],["3",Ir],[", received ",bn],["2",bt]);l.push($),l.push([]),l.push([g,["echo ",""],["selected text",ii(u)],[" ",""],[" ",ii(c)]]),l.forEach((a,w)=>{let F=r+2+w;if(F<=i)n[F]?.run(t,a)})}function zl(n,r,t,e,i,o){n[r]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=r+1;s<r+e-1;s++)n[s]?.put(t,"│",o),n[s]?.put(t+i-1,"│",o);n[r+e-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function si(n,r=n.site){return[` ${r} `,`\x1B[7;${30+n.siteAnsi}m`]}function Al(n,r,t){let e=Yn.flatMap((o,s)=>{let u=`${o.name}${o.moved?"*":""}`,c=o.name===t.site?si(t,u):[` ${u} `,bn];return s?[[" ",""],c]:[c]}),i=e.reduce((o,[s])=>o+rr(s),0)<=r;n.run(0,i?e:[si(t)])}function Cl(n,r,t,e){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",e],[t.editing,""],["█",e]]);n.put(u,t.editing?" enter searches":` a tag, a post url or an id — ${t.tag||"esc leaves"}`,bn);return}let i=n.run(0,[["⌕ ",e],[t.tag||"nothing yet — / searches",t.tag?"":bn]]),o=Fr.filter((u)=>!t.block.includes(u)),s=[t.preset,t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(i,` ${s.join(" ")}`,bn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,bn]);n.right(r,u)}}function Tl(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,Ir]];if(n.cut==="off")return[["opaque · x cuts out",Pn]];if(n.cut==="failed")return[["opaque · no cut-out",Pn]];return[n.clear>0?[`${n.clear}% transparent`,Ir]:["opaque",Pn]]}function zu(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${n.site} ${n.installing}`,Pn];if(n.error)return[n.error,Pn];if(n.waiting!==void 0)return[`${n.site} asked to slow down · ${n.waiting}s`,Pn];if(n.fetching)return[`fetching ${n.fetching.id} · ${Yl(n.fetching.got,n.fetching.size)}`,Pn];if(n.cutting!==void 0)return[`cutting out ${n.cutting}`,Pn];if(n.preparing!==void 0)return[`preparing ${n.preparing}`,Pn];if(n.note)return[n.note,bn];return}function _l(n,r,t,e,i,o){let{perRow:s,rowsVis:u}=Et(t,e);Cl(n[0],t,i,o),Al(n[1],t,i);for(let $=0;$<s*u;$++){let a=i.top*s+$,w=i.tiles[a];if(!w)break;let F=2+Math.floor($/s)*Ln.height,v=$%s*Ln.pitch,j=a===i.focus;if(j)zl(n,F,v,Ln.height,Ln.pitch-1,o);if(w.thumb)r.push({id:w.id,path:w.thumb,row:F+1,col:v+1,cols:Ln.cols,rows:Ln.rows,z:-1});if(n[F+10]?.run(v+1,[[String(w.id),j?Nr:""],[" ",""],Pu(w)]),w.mates.length>0)n[F+10]?.put(v+Ln.cols,"≈",o);let M=w.artist?Yu(w.artist):w.owner&&`@${w.owner}`;if(M)n[F+11]?.put(v+1,M.slice(0,Ln.cols-8),bn);let N=[];if(w.score>0)N.push([`★${w.score}`,bn]);if(w.variants>1)N.push([` ×${w.variants}`,o]);if(N.length>0)n[F+11]?.right(v+Ln.cols+1,N)}let c=i.top*s,h=i.tiles.length-(i.top+u)*s,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[e-2]?.put(0,f.join(" "),bn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${i.site} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${i.site} — tab tries ${i.nextSite}`,bn);let g=n[e-1],l=zu(i);if(i.searching&&i.tiles.length===0&&!l){wt(g,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",bn],right:["esc","back"]});return}wt(g,t,o,{badge:"FIND",lead:l,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function Bl(n,r,t,e,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.id?i.shown:void 0,c=[si(i),[" ",""],[String(s.id),Nr],[" ",""],Pu(s)];if(s.artist)c.push([` · ${Yu(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,bn]);if(u)c.push([` · ${Vu(u.bytes)}`,bn]);if(c.push([` · ${s.owner}`,bn]),s.origin)c.push([` · ${s.origin}`,bn]);if(u)c.push([" ",""],...Tl(u));if(n[0]?.run(0,c),s.mates.length>0)n[0]?.right(t,[["≈ ",o],[s.mates.join(" "),bn]]);if(Pl(n,3,2,t-4,e-2,i),i.shown)r.push({id:Zl+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:e,z:Ul});let h=zu(i);wt(n[e-1],t,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var xl={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab ${Yn.map((n)=>n.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["grid","esc"],["close","? esc"]]};function Dl(n,r,t,e,i){let o=e.panel??0,s=Math.max(...e.settings.map((l)=>l.label.length)),u=Math.max(...e.settings.map((l)=>l.choices.reduce(($,a)=>$+a.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,s+u+8)),h=e.settings.length+4,f=Math.floor((r-c)/2),g=Math.max(2,Math.floor((t-h)/2));n[g]?.put(f,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=g+1;l<g+h-1;l++)n[l]?.put(f,`│${" ".repeat(c-2)}│`);e.settings.forEach((l,$)=>{let a=n[g+2+$];a.put(f+3,l.label,$===o?Nr:bn);let w=f+5+s,F=l.value.split(" ");l.choices.forEach((v,j)=>{let M=F.includes(v),N=l.multi&&$===o&&j===l.cursor?"4;":"",b=l.multi?` ${M?"[x]":"[ ]"} ${v} `:` ${v} `;w=a.put(w,b,M?`\x1B[${N}7;${30+e.siteAnsi}m`:N?`\x1B[4m${bn}`:bn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),wt(n[t-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function nm(n,r,t,e,i){let o=xl[e.mode],s=Math.min(r-2,50),u=o.length+4,c=Math.floor((r-s)/2),h=Math.max(2,Math.floor((t-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([f,g],l)=>{n[h+2+l]?.put(c+3,f,Nr),n[h+2+l]?.put(c+13,g.slice(0,s-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),wt(n[t-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function Au(n,r,t){let e=Array.from({length:t},()=>new oi(r)),i=[],o=Xu(n.colors.cursor);if(r<vr.cols||t<vr.rows)return e[0]?.put(0,"ttheme find",Nr+o),e[1]?.put(0,`needs ${vr.cols}×${vr.rows} — now ${r}×${t}`),e[2]?.put(0,"esc quits",bn),{lines:e.map((s)=>s.render()),images:i};if(n.mode==="try")Bl(e,i,r,t,n,o);else _l(e,i,r,t,n,o);if(n.help||n.panel!==void 0){let s=n.mode==="try"?i:[];for(let u=0;u<t;u++)e[u]=new oi(r);if(n.help)nm(e,r,t,n,o);else Dl(e,r,t,n,o);return{lines:e.map((u)=>u.render()),images:s}}return{lines:e.map((s)=>s.render()),images:i}}import{execFileSync as rm}from"node:child_process";import{existsSync as ci,mkdirSync as ne,readFileSync as Tu,rmSync as _u,writeFileSync as re}from"node:fs";import{homedir as hi}from"node:os";import{dirname as te,join as Tn}from"node:path";var tm={ghostty:it,kitty:st,alacritty:et,iterm2:ot},Cu="ttheme-default";function qr(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(t,e)=>rm(t,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?r("defaults",["read",n,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(t)=>{if(process.platform==="darwin")r("defaults",["write",n,"Default Bookmark Guid","-string",t])},running:()=>{try{return r("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function Wr(n){return n.keepTheme?void 0:Xr(n)}function kt(n,r){if(!n.terminals.includes("iterm2"))return n;let t=r.read();return t&&!t.startsWith("ttheme-")?{...n,itermBase:t}:n}function Mt(n,r){if(!n.terminals.includes("iterm2"))return!1;let t=r.read(),e=Wr(n)?Cu:t===Cu?n.itermBase:void 0;if(!e||e===t)return!1;return r.write(e),!0}function _n(){return process.env.XDG_CONFIG_HOME??Tn(hi(),".config")}function Bu(n){return Tn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function xu(n){return Tn(n,"ttheme","installed.json")}function ur(n){let r=xu(n);if(!ci(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(Tu(r,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${r} has no palettes or terminals`);return{terminals:t.terminals.filter((e)=>Ot.includes(e)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},palettes:t.palettes}}function Ft(n,r){let t=xu(n);ne(te(t),{recursive:!0}),re(t,`${JSON.stringify(r,null,2)}
60
60
  `)}function fi(n,r){return{name:n.name,group:n.group,...n.native?{native:n.native}:{},lead:n.lead===!0,order:n.order,...n.default?{role:"default"}:{},ansiSource:n.ansiSource,...n.booru?{booru:n.booru}:{},background:n.background,foreground:n.foreground,cursor:n.cursor,selectionBackground:n.selection,ansi:n.ansi,signature:n.signature,signatureSlots:n.signatureSlots,font:r.font,ghostty:{...r.shader?{shader:r.shader}:{},iconGhost:n.cursor,iconScreen:[n.cursor,n.selection,n.background]},waive:n.waived??[]}}function Du(n,r){let t=new Map(n.palettes.map((o)=>[o.name,o])),e=r.filter((o)=>!t.has(o));if(e.length>0)throw Error(`not in the catalog: ${e.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((o)=>{let s=Ku(t.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
61
61
  ${i.join(`
62
- `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function nc(n,r){return(tm[n].emit?.(r)??[]).flatMap((t)=>{let[,e,i]=t.path.split("/");return e==="themes"&&i!==void 0?[{file:i,content:t.content}]:[]})}function Wr(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function em(n,r,t){let e=Tn(r,"ttheme");if(n==="ghostty")return{file:Tn(r,"ghostty","config"),body:Io(e,t)};if(n==="kitty")return{file:Tn(r,"kitty","kitty.conf"),body:Ho(t)};let i=t?Tn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Tn(r,"alacritty","alacritty.toml"),body:So(i)}}function rc(n,r,t,e,i){let o=Qr(n),s=t.map((h)=>fi(h,r)),u=new Map;for(let h of s){let f=nu(o,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Gr(t).map((h)=>h.name));return ao(s.filter((h)=>c.has(h.name)),u,s.find((h)=>h.name===qr(e)),e.itermBase)}function Xr(n,r=hi()){let t=sr(n);if(!t.terminals.includes("iterm2"))return;let e=Qn(n),i=Bu(r);Dt(re(i),{recursive:!0}),ne(i,rc(n,e,Du(e,t.palettes),t,r))}function It(n,r,t,e=hi()){let i=Du(r,t.palettes),o=[],s=(h,f)=>{Dt(re(h),{recursive:!0}),ne(h,f),o.push(h)},u=qr(t);for(let h of t.terminals){if(h==="iterm2"){s(Bu(e),rc(n,r,i,t,e));continue}for(let $ of i)for(let{file:a,content:w}of nc(h,fi($,r)))s(Tn(n,h,"themes",a),w);let{file:f,body:g}=em(h,n,u),l=ci(f)?Tu(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;Dt(re(f),{recursive:!0}),ne(f,Ot(l,g)),o.push(f)}let c=Tn(n,"ttheme","palettes.zsh");return s(c,Ne(i,u,t.terminals)),_u(`${c}.zwc`,{force:!0}),o}function gi(n,r,t,e){let i=[];for(let o of t)for(let s of r.palettes.filter((u)=>e.includes(u.name)))for(let{file:u}of nc(o,fi(s,r))){let c=Tn(n,o,"themes",u);if(ci(c))_u(c,{force:!0}),i.push(c)}return i}import{mkdirSync as tc,readFileSync as ec,writeFileSync as ic}from"node:fs";import{dirname as oc}from"node:path";import{isMainThread as im,parentPort as sc,Worker as om}from"node:worker_threads";var sm={thumb:"tile",show:"view",backdrop:"view"};function um(n){let r=Qs(new Uint8Array(ec(n.from)),Te);if(n.job==="backdrop")return cu(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(ec(n.source))}),0;if(n.job==="thumb")return tc(oc(n.to),{recursive:!0}),ic(n.to,yr(Us(r,n.width,n.height))),0;let t=Wt(r);return tc(oc(n.to),{recursive:!0}),ic(n.to,yr(Ds(r,n.colors,n.tone,n.width,n.height,t))),t}function cm(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:um(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class uc{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((t,e)=>{let i=this.open();this.waiting.set(r,{ok:t,no:e}),i.ref(),i.postMessage({...n,id:r})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let n=new om(import.meta.filename);n.unref(),n.on("message",({id:t,value:e,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(e)});let r=(t)=>{if(this.worker===n)this.worker=void 0;this.drop(t instanceof Error?t:Error("renderer stopped"))};return n.on("error",r),n.on("exit",()=>r(void 0)),this.worker=n,n}drop(n){for(let r of this.waiting.values())r.no(n);this.waiting.clear()}}class li{lines=new Map;run(n){let r=sm[n.job],t=this.lines.get(r);if(!t)t=new uc,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!im&&sc)cm(sc);import{connect as hm,createServer as fm}from"node:net";var gm=20,cc=22;function mi(n){let r=new Uint8Array(n.reduce((e,i)=>e+i.length,0)),t=0;for(let e of n)r.set(e,t),t+=e.length;return r}function lm(n,r=gm){let t=n.subarray(5);if(n[0]!==cc||t.length<2)return[n];let e=Math.max(1,Math.min(r,t.length-1)),i=(o)=>mi([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,e)),i(t.subarray(e))]}function mm(n,r,t,e){let i=hm(t,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
62
+ `)}`);return n.palettes.filter((o)=>r.includes(o.name))}function nc(n,r){return(tm[n].emit?.(r)??[]).flatMap((t)=>{let[,e,i]=t.path.split("/");return e==="themes"&&i!==void 0?[{file:i,content:t.content}]:[]})}function Xr(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function em(n,r,t){let e=Tn(r,"ttheme");if(n==="ghostty")return{file:Tn(r,"ghostty","config"),body:Io(e,t)};if(n==="kitty")return{file:Tn(r,"kitty","kitty.conf"),body:Ho(t)};let i=t?Tn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Tn(r,"alacritty","alacritty.toml"),body:So(i)}}function rc(n,r,t,e,i){let o=Zr(n),s=t.map((h)=>fi(h,r)),u=new Map;for(let h of s){let f=nu(o,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Jr(t).map((h)=>h.name));return ao(s.filter((h)=>c.has(h.name)),u,s.find((h)=>h.name===Wr(e)),e.itermBase)}function Vr(n,r=hi()){let t=ur(n);if(!t.terminals.includes("iterm2"))return;let e=Qn(n),i=Bu(r);ne(te(i),{recursive:!0}),re(i,rc(n,e,Du(e,t.palettes),t,r))}function It(n,r,t,e=hi()){let i=Du(r,t.palettes),o=[],s=(h,f)=>{ne(te(h),{recursive:!0}),re(h,f),o.push(h)},u=Wr(t);for(let h of t.terminals){if(h==="iterm2"){s(Bu(e),rc(n,r,i,t,e));continue}for(let $ of i)for(let{file:a,content:w}of nc(h,fi($,r)))s(Tn(n,h,"themes",a),w);let{file:f,body:g}=em(h,n,u),l=ci(f)?Tu(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;ne(te(f),{recursive:!0}),re(f,Lt(l,g)),o.push(f)}let c=Tn(n,"ttheme","palettes.zsh");return s(c,pe(i,u,t.terminals)),_u(`${c}.zwc`,{force:!0}),o}function gi(n,r,t,e){let i=[];for(let o of t)for(let s of r.palettes.filter((u)=>e.includes(u.name)))for(let{file:u}of nc(o,fi(s,r))){let c=Tn(n,o,"themes",u);if(ci(c))_u(c,{force:!0}),i.push(c)}return i}import{mkdirSync as tc,readFileSync as ec,writeFileSync as ic}from"node:fs";import{dirname as oc}from"node:path";import{isMainThread as im,parentPort as sc,Worker as om}from"node:worker_threads";var sm={thumb:"tile",show:"view",backdrop:"view"};function um(n){let r=Qs(new Uint8Array(ec(n.from)),Te);if(n.job==="backdrop")return cu(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(ec(n.source))}),0;if(n.job==="thumb")return tc(oc(n.to),{recursive:!0}),ic(n.to,Or(Us(r,n.width,n.height))),0;let t=Xt(r);return tc(oc(n.to),{recursive:!0}),ic(n.to,Or(Ds(r,n.colors,n.tone,n.width,n.height,t))),t}function cm(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:um(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class uc{worker;next=1;waiting=new Map;send(n){let r=this.next++;return new Promise((t,e)=>{let i=this.open();this.waiting.set(r,{ok:t,no:e}),i.ref(),i.postMessage({...n,id:r})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let n=new om(import.meta.filename);n.unref(),n.on("message",({id:t,value:e,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(e)});let r=(t)=>{if(this.worker===n)this.worker=void 0;this.drop(t instanceof Error?t:Error("renderer stopped"))};return n.on("error",r),n.on("exit",()=>r(void 0)),this.worker=n,n}drop(n){for(let r of this.waiting.values())r.no(n);this.waiting.clear()}}class li{lines=new Map;run(n){let r=sm[n.job],t=this.lines.get(r);if(!t)t=new uc,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!im&&sc)cm(sc);import{connect as hm,createServer as fm}from"node:net";var gm=20,cc=22;function mi(n){let r=new Uint8Array(n.reduce((e,i)=>e+i.length,0)),t=0;for(let e of n)r.set(e,t),t+=e.length;return r}function lm(n,r=gm){let t=n.subarray(5);if(n[0]!==cc||t.length<2)return[n];let e=Math.max(1,Math.min(r,t.length-1)),i=(o)=>mi([Uint8Array.from([n[0],n[1],n[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,e)),i(t.subarray(e))]}function mm(n,r,t,e){let i=hm(t,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
63
63
  \r
64
64
  `);let o=e,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=mi([o,c]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==cc){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[f,g]=lm(o.subarray(0,5+h));i.write(f),setTimeout(()=>{if(g)i.write(g);i.write(o.subarray(5+h))},10)};if(n.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(n)});i.on("error",()=>n.destroy()),n.on("error",()=>i.destroy())}function dm(n){n.setNoDelay(!0);let r=new Uint8Array(0),t=(e)=>{r=mi([r,e]);let i=Buffer.from(r).toString("latin1"),o=i.indexOf(`\r
65
65
  \r
66
66
  `);if(o===-1)return;n.off("data",t);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){n.end(`HTTP/1.1 405 Method Not Allowed\r
67
67
  \r
68
- `);return}mm(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",t),n.on("error",()=>n.destroy())}function hc(){let n=fm(dm);return new Promise((r,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Yr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:zt,multi:{read:At}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Mr,multi:{read:Ct,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...ei()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function wm(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((t)=>t===r)??n.choices[0]}var gc=12,Em=12,km=2,Mm=150,Fm=30,Im=1280,vm=2;function $i(n,r){return{key:n,groups:[],sources:[],queue:[],seen:new Set,checked:0,total:0,focus:0,top:0,searching:r}}function ki(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return ki(n.errors[0]);if(n.cause)return ki(n.cause);let r=n.code;if(typeof r==="string")return r;let t=(n.message||n.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function lc(n,r){return`${n.name}: ${ki(r)}`}function pm(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function ai(n,r){try{return JSON.parse(dc(ur(mr(n),r),"utf8"))}catch{return{}}}function bi(n,r,t){wi(mr(n),{recursive:!0}),Ei(ur(mr(n),r),`${JSON.stringify(t)}
69
- `)}class $c{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;siteIndex=0;values=new Map(Yr.map((n)=>[n.name,wm(n,process.env[n.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new li;sent=new Map;placed=new Map;current;fetch;settle;partial;input="";probeWait;done;dirty=!1;scratch=$m(ur(bm(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,e){this.home=n,this.catalog=r,this.entry=t,this.tone=As(t,t.signatureSlots),this.view={palette:t.name,tag:e,site:this.site.name,siteAnsi:this.site.ansi,nextSite:this.nextSite.name,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",rating:At(this.setting("TTHEME_FIND_RATING")),block:Ct(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Yr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],checked:0,total:0,searching:e!=="",focus:0,top:0,mode:"grid",help:!1,editing:e===""?"":void 0},this.board=$i(this.boardKey,e!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return Yn[this.siteIndex]}get nextSite(){return Yn[(this.siteIndex+1)%Yn.length]}setting(n){return this.values.get(n)}get boardKey(){return`${this.site.key}|${this.view.preset}|${this.view.order}`}mark(n,r){return`${n.key}:${r}`}origPath(n,r,t){return ur(mr(n),"orig",`${r}.${t}`)}tileOf(n,r,t){let e=$t(r)??r;return{id:r.id,width:e.width,height:e.height,reduced:e!==r,owner:Mu(r.owner)?"":r.owner,artist:r.artist,score:r.score,variants:t,origin:wu(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(this.mark(n,r.id))}}show(){let n=this.site,r=this.view,t=this.board;r.tiles=t.groups.flatMap((e)=>e.open?e.posts.map((i)=>this.tileOf(n,i,0)):[this.tileOf(n,e.posts[0],e.posts.length)]),r.checked=t.checked,r.total=t.total,r.searching=t.searching,r.note=t.note,r.focus=Math.max(0,Math.min(t.focus,r.tiles.length-1)),r.top=t.top}syncSite(){let n=this.view;n.site=this.site.name,n.siteAnsi=this.site.ansi,n.nextSite=this.nextSite.name}async run(){let{stdin:n,stdout:r}=process;n.setRawMode(!0),n.resume(),n.on("data",this.onData),r.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let t=new Promise((s)=>{this.done=s}),e=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";this.draw();let o=await t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),clearInterval(e),n.off("data",this.onData),r.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),n.setRawMode(!1),n.pause(),this.saveProbes(),this.renders.close(),di(this.scratch,{recursive:!0,force:!0}),vu(),o}write(n){process.stdout.write(n)}finish(n){this.done?.(n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(t)=>{clearTimeout(r),this.probeWait=void 0,n(t)},this.write(Zu)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=ui(this.input);r;r=ui(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),pm(this.input)){this.partial=setTimeout(this.flushKeys,Fm);return}this.flushKeys()};flushKeys=()=>{let n=Qu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=Math.ceil((Pt(this.site)-Date.now())/1000),r=n>0?n:void 0;if(r!==this.view.waiting)this.view.waiting=r,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(n){let r=this.view;if(n==="ctrl-c"){this.finish(2);return}if(r.installing!==void 0)return;if(r.editing!==void 0){this.editKey(n);return}if(r.panel!==void 0){this.panelKey(n);return}if(r.help){if(n==="?"||n==="esc")r.help=!1,this.draw();return}if(this.cols<Ir.cols||this.rows<Ir.rows){if(n==="esc")this.finish(2);return}if(n==="?"){r.help=!0,this.draw();return}if(r.mode==="try"){this.tryKey(n);return}this.gridKey(n)}gridKey(n){let r=this.view,{perRow:t,rowsVis:e}=Et(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*e,pgdn:t*e,home:-r.focus,end:r.tiles.length}[n];if(o!==void 0){this.focus(r.focus+o);return}if(n==="enter"&&r.tiles[r.focus]){r.mode="try",r.error=void 0,this.select();return}if(n==="c"){r.preset=r.preset==="cutouts"?"all":"cutouts",this.turn();return}if(n==="tab"){this.siteIndex=(this.siteIndex+1)%Yn.length,this.syncSite(),this.turn();return}if(n==="/"){r.editing="",this.draw();return}if(n===" "){this.unfold();return}if(n==="o"){this.openPage();return}if(n==="s"){r.panel=0,this.draw();return}if(n==="esc")this.finish(2)}panelKey(n){let r=this.view,t=r.panel??0,e=r.settings[t];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,t+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&e){let i=n==="left"?-1:1;if(e.multi)e.cursor=(e.cursor+i+e.choices.length)%e.choices.length;else{let o=e.choices.indexOf(e.value);e.value=e.choices[(o+i+e.choices.length)%e.choices.length]}this.draw();return}if(n===" "&&e?.multi){let i=e.value.split(" "),o=e.choices.filter((u,c)=>c===e.cursor?!i.includes(u):i.includes(u)),s=e.multi.none;if(o.length>0||s!==void 0)e.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((i,o)=>{i.value=this.setting(Yr[o]?.name??"")}),r.panel=void 0,this.draw();return}if(n==="enter"||n==="alt-c")r.panel=void 0,this.adopt()}adopt(){let n=this.view,r=Yr.map((e)=>this.setting(e.name));n.settings.forEach((e,i)=>{let o=Yr[i];if(o)this.values.set(o.name,e.value)});let t=Yr.filter((e,i)=>this.setting(e.name)!==r[i]);if(t.length===0){this.draw();return}this.save(t),n.rating=At(this.setting("TTHEME_FIND_RATING")),n.block=Ct(this.setting("TTHEME_FIND_BLOCK")),n.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",n.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",n.order=this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){let r=ur(this.home,"ttheme","config.zsh");try{let t=Vr(r)?dc(r,"utf8"):"",e=n.reduce((i,o)=>Lt(i,o.name,this.setting(o.name)),t);Ei(r,e)}catch(t){this.view.error=t instanceof Error?t.message:String(t)}}editKey(n){let r=this.view,t=r.editing??"";if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){if(r.editing=void 0,t.trim()){this.commit(t.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.draw()}async commit(n){let r=bu(n,this.site);if(r){await this.jump(r.site,r.id);return}this.view.tag=n,this.boards.clear(),await this.search()}async jump(n,r){let t=++this.gen;this.siteIndex=Yn.indexOf(n),this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let e=$i(`${n.key}|post:${r}`,!0);this.board=e,this.boards.set(e.key,e),this.show(),this.draw();try{let i=await ti(n,r,this.signal);if(t!==this.gen)return;if(e.searching=!1,!i)e.error=`${n.name} has no post ${r}`,this.view.error=e.error;else this.posts.set(this.mark(n,i.id),i),e.groups=[{posts:[i],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push({site:n,post:i}),this.thumbs(),this.view.mode="try";if(this.show(),i)this.select();this.draw()}catch(i){this.fail(t,i)}}async turn(){this.current=void 0,this.view.shown=void 0;let n=this.boards.get(this.boardKey);if(!n){await this.search();return}this.gen++,this.board=n,this.view.error=n.error,this.show(),this.draw(),await this.pump()}unfold(){let n=this.view,r=0;for(let t of this.board.groups){let e=t.open?t.posts.length:1;if(n.focus<r+e){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=r;for(let i of t.posts)if(!this.thumbPath.has(this.mark(this.site,i.id)))this.thumbQueue.push({site:this.site,post:i});this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=e}}openPage(){let n=this.view.tiles[this.view.focus];if(!n)return;let r=process.platform==="darwin"?"open":"xdg-open";try{mc(r,[this.site.pageUrl(n.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(n){let r=this.view;if(n==="left"||n==="right"){this.direction=n==="left"?-1:1,this.focus(r.focus+this.direction);return}if(n==="o"){this.openPage();return}if(n==="x"){this.swap();return}if(n==="enter"){this.install();return}if(n==="esc")this.fetch?.abort(),clearTimeout(this.settle),r.fetching=void 0,r.mode="grid",r.error=void 0,this.draw()}focus(n){let r=this.view;if(r.tiles.length===0)return;let t=Math.max(0,Math.min(r.tiles.length-1,n));if(t===r.focus)return;if(r.focus=t,this.board.focus=t,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:t}=Et(this.cols,this.rows),e=Math.floor(n.focus/r);if(e<n.top)n.top=e;if(e>n.top+t-1)n.top=e-t+1;this.board.top=n.top}query(n){let r=this.view,t=[r.tag,n.rate(this.view.rating),r.preset==="cutouts"?n.cutouts:"",r.order==="score"?n.best:""].filter(Boolean),e=[],i=[];for(let o of t)if(ri([...e,o].join(" "))<=n.tagBudget)e.push(o);else i.push(o);return this.board.note=i.length>0?`${n.name} takes ${n.tagBudget} tags — ${i.join(" ")} left out`:void 0,e.join(" ")}async search(){let n=++this.gen,r=this.site,t=$i(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0,this.show(),this.draw();let e=this.query(r);this.tally(n,r,t,e);try{let i=await this.mateOwners(r);if(n!==this.gen)return;let o=ri(e)+1<=r.tagBudget;t.sources=[...o?[...i.keys()].map((s)=>({tags:`${e} user:${s}`,page:0,done:!1})):[],{tags:e,page:0,done:!1}],this.show(),this.draw(),await this.pump()}catch(i){this.fail(n,i)}}async tally(n,r,t,e){try{let i=await Nu(r,e,this.signal);if(n===this.gen)t.total=i,this.show(),this.draw()}catch{}}fail(n,r){if(n!==this.gen||this.signal.aborted)return;this.board.error=lc(this.site,r),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}wants(){let{perRow:n,rowsVis:r}=Et(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+vm)*n}async nextPage(n,r,t){let e=r.sources.find((o)=>!o.done);if(!e)return;let i=await pu(n,e.tags,e.page,this.signal);if(t!==this.gen)return;e.page++,e.done=i.length<mt;for(let o of i)if(!r.seen.has(o.id))r.seen.add(o.id),r.queue.push(o)}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=this.site,e=[],i;try{r.searching=!0;while(n===this.gen){while(e.length<gc&&r.queue.length>0&&this.wants()){let u=r.queue.shift();e.push({post:u,passed:this.passes(t,u)})}if(!i&&r.queue.length<gc&&r.sources.some((u)=>!u.done)&&this.wants()){let u=this.nextPage(t,r,n).then(()=>{if(i===u)i=void 0});u.catch(()=>{}),i=u}let o=e.shift();if(!o){if(!i)break;await i;continue}let s=await o.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(t,o.post);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(o){this.fail(n,o)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}async passes(n,r){let t=$t(r);if(!ku(n,r,this.view.rating)||Eu(r,this.view.block).length>0||!t)return!1;if(this.view.preset==="all")return["png","jpg","jpeg"].includes(t.ext);if(r.ext!=="png")return!1;return n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=ai(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let t=this.probes(n),e=t[r.id];if(e!==void 0)return e;try{let i=(await Hu(n,r.file,this.signal))?.alpha===!0;return t[r.id]=i,this.unsaved.add(n.key),i}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Yn.find((t)=>t.key===n);if(r)bi(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n,r){this.posts.set(this.mark(n,r.id),r);let t=this.view.sets==="fold"?this.board.groups.at(-1):void 0,e=t?.posts[0],i=r.owner||r.artist;if(t&&e&&i&&(e.owner||e.artist)===i&&e.width===r.width&&e.height===r.height){if(t.posts.push(r),t.open)this.thumbQueue.push({site:n,post:r}),this.thumbs();return}this.board.groups.push({posts:[r],open:!1}),this.thumbQueue.push({site:n,post:r}),this.thumbs()}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=hu(this.home),e=ai(n,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let h=t.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&h?.site===n.key?[{name:c.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let h=e[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await ti(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)e[c.id]=c.owner,s.set(c.name,c.owner);bi(n,"owners.json",e);let u=Fu(s);return this.owners.set(n.key,u),u}async cached(n,r,t,e){if(Vr(r))return am(r).size;let i=this.inflight.get(r);if(i)return i;let o=(async()=>{let s=await Su(n,t,this.signal,e);return wi(fc(r),{recursive:!0}),Ei(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<Em&&this.thumbQueue.length>0){let{site:n,post:r}=this.thumbQueue.shift();this.thumbing++,this.thumb(n,r).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n,r){let t=Ln.cols*this.cell.w,e=Ln.rows*this.cell.h,i=ur(mr(n),"tile",`${r.id}-${t}x${e}.png`);if(!Vr(i)){let o=ur(mr(n),"thumb",`${r.id}.${Zr(r.preview)}`);await this.cached(n,o,r.preview),await this.renders.run({job:"thumb",from:o,to:i,width:t,height:e})}this.thumbPath.set(this.mark(n,r.id),i),this.show(),this.draw()}select(){let n=this.view,r=n.tiles[n.focus];if(this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,!r)return;if(this.current?.id===r.id){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),Mm),this.draw()}async load(n){let r=this.view,t=this.posts.get(this.mark(this.site,n.id)),e=t&&$t(t);if(!e)return;let i=this.site,o=new AbortController;this.fetch=o;try{let s=this.origPath(i,n.id,e.ext);if(!Vr(s))r.fetching={id:n.id,got:0,size:0},this.draw();let u=await this.cached(i,s,e.file,(f,g)=>{if(r.fetching?.id===n.id)r.fetching={id:n.id,got:f,size:g},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,i!==this.site)return;let c={site:i,id:n.id,path:s,ext:e.ext,size:u,using:"plain",failed:!1};r.preparing=n.id,this.flush();let h=await this.render(c,"plain");if(o.signal.aborted||i!==this.site)return;if(h.clear===0&&ei()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.id,this.flush(),c.cut=await this.cutOut(i,n.id,s,o.signal),o.signal.aborted||i!==this.site)return;if(r.cutting=void 0,c.cut){r.preparing=n.id,this.flush();let f=await this.render(c,"cut").catch(()=>{return});if(o.signal.aborted||i!==this.site)return;if(f&&yu(f.clear))c.using="cut";else di(c.cut,{force:!0}),c.cut=void 0,c.failed=!0}else c.failed=!0}if(this.current=c,r.tiles[r.focus]?.id===n.id)await this.present();this.preload()}catch(s){if(!o.signal.aborted&&!this.signal.aborted)r.error=lc(i,s)}finally{if(r.fetching?.id===n.id)r.fetching=void 0;if(r.preparing===n.id)r.preparing=void 0;if(r.cutting===n.id)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,e){let i=ur(mr(n),"cut",`${r}.png`);if(Vr(i))return i;try{return wi(fc(i),{recursive:!0}),await Ou(t,i,e),i}catch{di(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.id)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;let r=this.site;for(let t of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=km)return;let e=n.tiles[t],i=e&&this.posts.get(this.mark(r,e.id)),o=i&&$t(i);if(!o)continue;let s=this.origPath(r,i.id,o.ext);this.prefetching++,this.cached(r,s,o.file).then(()=>this.render({site:r,id:i.id,path:s,ext:o.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let t=this.cols*this.cell.w,e=this.rows*this.cell.h,i=Math.min(t,Im),o=Math.max(1,Math.round(e*i/t)),s=ur(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${o}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&Vr(s))return{clear:c,path:s};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:s}}async present(){let n=this.current;if(!n)return;let r=n.using,{clear:t,path:e}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.id,clear:t,bytes:n.size,path:e,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.id,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.id)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.id!==r.id||n.preparing!==void 0||n.shown?.id!==r.id)return;n.installing=r.id,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`}});let e=ai(t.site,"owners.json");e[t.id]=this.posts.get(this.mark(t.site,t.id))?.owner??"",bi(t.site,"owners.json",e),Xr(this.home),process.stderr.write(`background · ${this.entry.name} ← ${t.site.name} ${t.id}
70
- `),this.finish(0)}catch(e){n.installing=void 0,n.error=e instanceof Error?e.message:String(e),this.draw()}}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Au(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((e,i)=>{r+=`\x1B[${i+1};1H\x1B[K${e}`});let t=new Set;for(let e of n.images){if(t.add(e.id),this.sent.get(e.id)!==e.path)r+=Uu(e),this.sent.set(e.id,e.path),this.placed.delete(e.id);let i=`${e.row};${e.col};${e.cols};${e.rows};${e.z}`;if(this.placed.get(e.id)!==i)r+=qu(e),this.placed.set(e.id,i)}for(let e of this.sent.keys())if(!t.has(e))r+=Wu(e),this.sent.delete(e),this.placed.delete(e);this.write(`${r}\x1B[?2026l`)}}function Nm(){if(process.versions.bun)return!0;let[n=0,r=0]=process.versions.node.split(".").map(Number);return n>22||n===22&&r>=21}async function Hm(){if(!Nm())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
71
- `),1;let n=await hc(),r=mc(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${n.port}`,TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((e)=>r.on("exit",(i)=>e(i??1)));return n.close(),t}async function ac(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Hm();let r=_n(),t=Qn(r),e=Bt(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");return new $c(r,t,e,e.booru??"").run()}function bc(n,r){let t=_n();if(Bt(Qn(t).palettes,n),r==="next"||r==="prev"){let{key:e,at:i,of:o}=su(t,n,r==="next"?1:-1);return Xr(t),process.stderr.write(`background · ${n} ${i}/${o} ${e}
72
- `),0}if(r==="drop"){let{key:e,left:i}=uu(t,n);return Xr(t),process.stderr.write(`background · ${n} removed ${e??"the picture"} · ${i} left
73
- `),0}if(r==="tuned")return Xr(t),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{chmodSync as Sd,copyFileSync as jd,existsSync as hr,mkdirSync as Xi,readdirSync as Gd,readFileSync as Nt,rmSync as bh,writeFileSync as wh}from"node:fs";import{homedir as Jd}from"node:os";import{dirname as pt,join as wn}from"node:path";import{styleText as Hi}from"node:util";import{stdout as Oc,stdin as Vm}from"node:process";import Ym from"node:readline";var wc=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let t=0;n.lastIndex=0;while(n.test(r))t+=1;return r.length-t}})(),Ec=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},kc=(n)=>{return n===8987||n===9001||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n>=131072&&n<=196605||n>=196608&&n<=262141};var Sm=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jm=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Mc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Gm=/\t{1,1000}/y,Fc=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Jm=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Km=/\p{M}+/gu,Rm={limit:1/0,ellipsis:""},Ic=(n,r={},t={})=>{let e=r.limit??1/0,i=r.ellipsis??"",o=r?.ellipsisWidth??(i?Ic(i,Rm,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,$=[[Jm,g],[Sm,0],[jm,u],[Gm,c],[Fc,h],[Mc,l]],a=0,w=0,F=n.length,v=0,j=!1,M=F,p=Math.max(0,e-o),b=0,K=0,E=0,J=0;n:while(!0){if(K>b||w>=F&&w>a){let S=n.slice(b,K)||n.slice(a,w);v=0;for(let O of S.replaceAll(Km,"")){let R=O.codePointAt(0)||0;if(Ec(R))J=2;else if(kc(R))J=l;else J=g;if(E+J>p)M=Math.min(M,Math.max(b,a)+v);if(E+J>e){j=!0;break n}v+=O.length,E+=J}b=K=0}if(w>=F)break n;for(let S=0,O=$.length;S<O;S++){let[R,A]=$[S];if(R.lastIndex=w,R.test(n)){if(v=R===Mc?wc(n.slice(w,R.lastIndex)):R===Fc?1:R.lastIndex-w,J=v*A,E+J>p)M=Math.min(M,w+Math.floor((p-E)/A));if(E+J>e){j=!0;break n}E+=J,b=a,K=w,w=a=R.lastIndex;continue n}}w+=1}return{width:j?p:E,index:j?M:F,truncated:j,ellipsed:j&&e>=o}},vc=Ic;var ym={limit:1/0,ellipsis:"",ellipsisWidth:0},Om=(n,r={})=>{return vc(n,ym,r).width},Rn=Om;var te="\x1B",jc="›",Lm=39,Fi="\x07",Gc="[",Qm="]",Jc="m",Ii=`${Qm}8;;`,pc=new RegExp(`(?:\\${Gc}(?<code>\\d+)m|\\${Ii}(?<uri>.*)${Fi})`,"y"),Nc=(n)=>{if(n>=30&&n<=37)return 39;if(n>=90&&n<=97)return 39;if(n>=40&&n<=47)return 49;if(n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0;return},Hc=(n)=>`${te}${Gc}${n}${Jc}`,Sc=(n)=>`${te}${Ii}${n}${Fi}`,Mi=(n,r,t)=>{let e=r[Symbol.iterator](),i=!1,o=!1,s=n.at(-1),u=s===void 0?0:Rn(s),c=e.next(),h=e.next(),f=0;while(!c.done){let g=c.value,l=Rn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===te||g===jc)i=!0,o=r.startsWith(Ii,f+1);if(i){if(o){if(g===Fi)i=!1,o=!1}else if(g===Jc)i=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=e.next(),f+=g.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},Zm=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Rn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},Um=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let e="",i,o,s=n.split(" "),u=[""],c=0;for(let g=0;g<s.length;g++){let l=s[g];if(t.trim!==!1){let a=u.at(-1)??"",w=a.trimStart();if(a.length!==w.length)u[u.length-1]=w,c=Rn(w)}if(g!==0){if(c>=r&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let $=Rn(l);if(t.hard&&$>r){let a=r-c,w=1+Math.floor(($-a-1)/r);if(Math.floor(($-1)/r)<w)u.push("");Mi(u,l,r),c=Rn(u.at(-1)??"");continue}if(c+$>r&&c&&$){if(t.wordWrap===!1&&c<r){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u.push(""),c=0}if(c+$>r&&t.wordWrap===!1){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=$}if(t.trim!==!1)u=u.map((g)=>Zm(g));let h=u.join(`
74
- `),f=!1;for(let g=0;g<h.length;g++){let l=h[g];if(e+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===te||l===jc){pc.lastIndex=g+1;let a=pc.exec(h)?.groups;if(a?.code!==void 0){let w=Number.parseFloat(a.code);i=w===Lm?void 0:w}else if(a?.uri!==void 0)o=a.uri.length===0?void 0:a.uri}if(h[g+1]===`
75
- `){if(o)e+=Sc("");let $=i?Nc(i):void 0;if(i&&$)e+=Hc($)}else if(l===`
76
- `){if(i&&Nc(i))e+=Hc(i);if(o)e+=Sc(o)}}return e},qm=/\r?\n/;function dr(n,r,t){return String(n).normalize().split(qm).map((e)=>Um(e,r,t)).join(`
77
- `)}var Zn=Jt(pi(),1);function cr(n,r,t){if(!t.some((s)=>!s.disabled))return n;let e=n+r,i=Math.max(t.length-1,0),o=e<0?i:e>i?0:e;return t[o]?.disabled?cr(o,r<0?-1:1,t):o}function ee(n,r,t,e){let i=e.split(`
68
+ `);return}mm(n,s[1],Number(s[2]),r.subarray(o+4))};n.on("data",t),n.on("error",()=>n.destroy())}function hc(){let n=fm(dm);return new Promise((r,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{r({port:n.address().port,close:()=>{n.close(),n.unref()}})})})}var Pr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:At,multi:{read:Ct}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Fr,multi:{read:Tt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...ei()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function wm(n,r){if(n.multi)return n.multi.read(r).join(" ")||n.multi.none;return n.choices.find((t)=>t===r)??n.choices[0]}var gc=12,Em=12,km=2,Mm=150,Fm=30,Im=1280,vm=2;function $i(n,r){return{key:n,groups:[],sources:[],queue:[],seen:new Set,checked:0,total:0,focus:0,top:0,searching:r}}function ki(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return ki(n.errors[0]);if(n.cause)return ki(n.cause);let r=n.code;if(typeof r==="string")return r;let t=(n.message||n.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function lc(n,r){return`${n.name}: ${ki(r)}`}function Nm(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function ai(n,r){try{return JSON.parse(dc(cr($r(n),r),"utf8"))}catch{return{}}}function bi(n,r,t){wi($r(n),{recursive:!0}),Ei(cr($r(n),r),`${JSON.stringify(t)}
69
+ `)}class $c{view;tone;session=new AbortController;cell={w:0,h:0};cols=process.stdout.columns||80;rows=process.stdout.rows||24;gen=0;pumping=0;boards=new Map;board;posts=new Map;thumbPath=new Map;siteIndex=0;values=new Map(Pr.map((n)=>[n.name,wm(n,process.env[n.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new li;sent=new Map;placed=new Map;current;fetch;settle;partial;input="";probeWait;done;dirty=!1;scratch=$m(cr(bm(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,e){this.home=n,this.catalog=r,this.entry=t,this.tone=As(t,t.signatureSlots),this.view={palette:t.name,tag:e,site:this.site.name,siteAnsi:this.site.ansi,nextSite:this.nextSite.name,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",rating:Ct(this.setting("TTHEME_FIND_RATING")),block:Tt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Pr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:t.cursor,selection:t.selection,ansi:t.ansi},tiles:[],checked:0,total:0,searching:e!=="",focus:0,top:0,mode:"grid",help:!1,editing:e===""?"":void 0},this.board=$i(this.boardKey,e!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return Yn[this.siteIndex]}get nextSite(){return Yn[(this.siteIndex+1)%Yn.length]}setting(n){return this.values.get(n)}get boardKey(){return`${this.site.key}|${this.view.preset}|${this.view.order}`}mark(n,r){return`${n.key}:${r}`}origPath(n,r,t){return cr($r(n),"orig",`${r}.${t}`)}tileOf(n,r,t){let e=$t(r)??r;return{id:r.id,width:e.width,height:e.height,reduced:e!==r,owner:Mu(r.owner)?"":r.owner,artist:r.artist,score:r.score,variants:t,origin:wu(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(this.mark(n,r.id))}}show(){let n=this.site,r=this.view,t=this.board;r.tiles=t.groups.flatMap((e)=>e.open?e.posts.map((i)=>this.tileOf(n,i,0)):[this.tileOf(n,e.posts[0],e.posts.length)]),r.checked=t.checked,r.total=t.total,r.searching=t.searching,r.note=t.note,r.focus=Math.max(0,Math.min(t.focus,r.tiles.length-1)),r.top=t.top}syncSite(){let n=this.view;n.site=this.site.name,n.siteAnsi=this.site.ansi,n.nextSite=this.nextSite.name}async run(){let{stdin:n,stdout:r}=process;n.setRawMode(!0),n.resume(),n.on("data",this.onData),r.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let t=new Promise((s)=>{this.done=s}),e=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";this.draw();let o=await t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),clearInterval(e),n.off("data",this.onData),r.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),n.setRawMode(!1),n.pause(),this.saveProbes(),this.renders.close(),di(this.scratch,{recursive:!0,force:!0}),vu(),o}write(n){process.stdout.write(n)}finish(n){this.done?.(n)}probe(){return new Promise((n)=>{let r=setTimeout(()=>{this.probeWait=void 0,n(null)},1000);this.probeWait=(t)=>{clearTimeout(r),this.probeWait=void 0,n(t)},this.write(Zu)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=ui(this.input);r;r=ui(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),Nm(this.input)){this.partial=setTimeout(this.flushKeys,Fm);return}this.flushKeys()};flushKeys=()=>{let n=Qu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=Math.ceil((zt(this.site)-Date.now())/1000),r=n>0?n:void 0;if(r!==this.view.waiting)this.view.waiting=r,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(n){let r=this.view;if(n==="ctrl-c"){this.finish(2);return}if(r.installing!==void 0)return;if(r.editing!==void 0){this.editKey(n);return}if(r.panel!==void 0){this.panelKey(n);return}if(r.help){if(n==="?"||n==="esc")r.help=!1,this.draw();return}if(this.cols<vr.cols||this.rows<vr.rows){if(n==="esc")this.finish(2);return}if(n==="?"){r.help=!0,this.draw();return}if(r.mode==="try"){this.tryKey(n);return}this.gridKey(n)}gridKey(n){let r=this.view,{perRow:t,rowsVis:e}=Et(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*e,pgdn:t*e,home:-r.focus,end:r.tiles.length}[n];if(o!==void 0){this.focus(r.focus+o);return}if(n==="enter"&&r.tiles[r.focus]){r.mode="try",r.error=void 0,this.select();return}if(n==="c"){r.preset=r.preset==="cutouts"?"all":"cutouts",this.turn();return}if(n==="tab"){this.siteIndex=(this.siteIndex+1)%Yn.length,this.syncSite(),this.turn();return}if(n==="/"){r.editing="",this.draw();return}if(n===" "){this.unfold();return}if(n==="o"){this.openPage();return}if(n==="s"){r.panel=0,this.draw();return}if(n==="esc")this.finish(2)}panelKey(n){let r=this.view,t=r.panel??0,e=r.settings[t];if(n==="up"||n==="down"){r.panel=Math.max(0,Math.min(r.settings.length-1,t+(n==="up"?-1:1))),this.draw();return}if((n==="left"||n==="right")&&e){let i=n==="left"?-1:1;if(e.multi)e.cursor=(e.cursor+i+e.choices.length)%e.choices.length;else{let o=e.choices.indexOf(e.value);e.value=e.choices[(o+i+e.choices.length)%e.choices.length]}this.draw();return}if(n===" "&&e?.multi){let i=e.value.split(" "),o=e.choices.filter((u,c)=>c===e.cursor?!i.includes(u):i.includes(u)),s=e.multi.none;if(o.length>0||s!==void 0)e.value=o.length>0?o.join(" "):s,this.draw();return}if(n==="esc"){r.settings.forEach((i,o)=>{i.value=this.setting(Pr[o]?.name??"")}),r.panel=void 0,this.draw();return}if(n==="enter"||n==="alt-c")r.panel=void 0,this.adopt()}adopt(){let n=this.view,r=Pr.map((e)=>this.setting(e.name));n.settings.forEach((e,i)=>{let o=Pr[i];if(o)this.values.set(o.name,e.value)});let t=Pr.filter((e,i)=>this.setting(e.name)!==r[i]);if(t.length===0){this.draw();return}this.save(t),n.rating=Ct(this.setting("TTHEME_FIND_RATING")),n.block=Tt(this.setting("TTHEME_FIND_BLOCK")),n.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",n.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",n.order=this.setting("TTHEME_FIND_ORDER")==="score"?"score":"newest",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){let r=cr(this.home,"ttheme","config.zsh");try{let t=Yr(r)?dc(r,"utf8"):"",e=n.reduce((i,o)=>Qt(i,o.name,this.setting(o.name)),t);Ei(r,e)}catch(t){this.view.error=t instanceof Error?t.message:String(t)}}editKey(n){let r=this.view,t=r.editing??"";if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){if(r.editing=void 0,t.trim()){this.commit(t.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.draw()}async commit(n){let r=bu(n,this.site);if(r){await this.jump(r.site,r.id);return}this.view.tag=n,this.boards.clear(),await this.search()}async jump(n,r){let t=++this.gen;this.siteIndex=Yn.indexOf(n),this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let e=$i(`${n.key}|post:${r}`,!0);this.board=e,this.boards.set(e.key,e),this.show(),this.draw();try{let i=await ti(n,r,this.signal);if(t!==this.gen)return;if(e.searching=!1,!i)e.error=`${n.name} has no post ${r}`,this.view.error=e.error;else this.posts.set(this.mark(n,i.id),i),e.groups=[{posts:[i],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push({site:n,post:i}),this.thumbs(),this.view.mode="try";if(this.show(),i)this.select();this.draw()}catch(i){this.fail(t,i)}}async turn(){this.current=void 0,this.view.shown=void 0;let n=this.boards.get(this.boardKey);if(!n){await this.search();return}this.gen++,this.board=n,this.view.error=n.error,this.show(),this.draw(),await this.pump()}unfold(){let n=this.view,r=0;for(let t of this.board.groups){let e=t.open?t.posts.length:1;if(n.focus<r+e){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=r;for(let i of t.posts)if(!this.thumbPath.has(this.mark(this.site,i.id)))this.thumbQueue.push({site:this.site,post:i});this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=e}}openPage(){let n=this.view.tiles[this.view.focus];if(!n)return;let r=process.platform==="darwin"?"open":"xdg-open";try{mc(r,[this.site.pageUrl(n.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(n){let r=this.view;if(n==="left"||n==="right"){this.direction=n==="left"?-1:1,this.focus(r.focus+this.direction);return}if(n==="o"){this.openPage();return}if(n==="x"){this.swap();return}if(n==="enter"){this.install();return}if(n==="esc")this.fetch?.abort(),clearTimeout(this.settle),r.fetching=void 0,r.mode="grid",r.error=void 0,this.draw()}focus(n){let r=this.view;if(r.tiles.length===0)return;let t=Math.max(0,Math.min(r.tiles.length-1,n));if(t===r.focus)return;if(r.focus=t,this.board.focus=t,this.scroll(),this.pump(),r.mode==="try")this.select();this.draw()}scroll(){let n=this.view,{perRow:r,rowsVis:t}=Et(this.cols,this.rows),e=Math.floor(n.focus/r);if(e<n.top)n.top=e;if(e>n.top+t-1)n.top=e-t+1;this.board.top=n.top}query(n){let r=this.view,t=[r.tag,n.rate(this.view.rating),r.preset==="cutouts"?n.cutouts:"",r.order==="score"?n.best:""].filter(Boolean),e=[],i=[];for(let o of t)if(ri([...e,o].join(" "))<=n.tagBudget)e.push(o);else i.push(o);return this.board.note=i.length>0?`${n.name} takes ${n.tagBudget} tags — ${i.join(" ")} left out`:void 0,e.join(" ")}async search(){let n=++this.gen,r=this.site,t=$i(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0,this.show(),this.draw();let e=this.query(r);this.tally(n,r,t,e);try{let i=await this.mateOwners(r);if(n!==this.gen)return;let o=ri(e)+1<=r.tagBudget;t.sources=[...o?[...i.keys()].map((s)=>({tags:`${e} user:${s}`,page:0,done:!1})):[],{tags:e,page:0,done:!1}],this.show(),this.draw(),await this.pump()}catch(i){this.fail(n,i)}}async tally(n,r,t,e){try{let i=await pu(r,e,this.signal);if(n===this.gen)t.total=i,this.show(),this.draw()}catch{}}fail(n,r){if(n!==this.gen||this.signal.aborted)return;this.board.error=lc(this.site,r),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}wants(){let{perRow:n,rowsVis:r}=Et(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+vm)*n}async nextPage(n,r,t){let e=r.sources.find((o)=>!o.done);if(!e)return;let i=await Nu(n,e.tags,e.page,this.signal);if(t!==this.gen)return;e.page++,e.done=i.length<mt;for(let o of i)if(!r.seen.has(o.id))r.seen.add(o.id),r.queue.push(o)}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=this.site,e=[],i;try{r.searching=!0;while(n===this.gen){while(e.length<gc&&r.queue.length>0&&this.wants()){let u=r.queue.shift();e.push({post:u,passed:this.passes(t,u)})}if(!i&&r.queue.length<gc&&r.sources.some((u)=>!u.done)&&this.wants()){let u=this.nextPage(t,r,n).then(()=>{if(i===u)i=void 0});u.catch(()=>{}),i=u}let o=e.shift();if(!o){if(!i)break;await i;continue}let s=await o.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(t,o.post);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(o){this.fail(n,o)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}async passes(n,r){let t=$t(r);if(!ku(n,r,this.view.rating)||Eu(r,this.view.block).length>0||!t)return!1;if(this.view.preset==="all")return["png","jpg","jpeg"].includes(t.ext);if(r.ext!=="png")return!1;return n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=ai(n,"probes.json"),this.probed.set(n.key,r);return r}async transparent(n,r){let t=this.probes(n),e=t[r.id];if(e!==void 0)return e;try{let i=(await Hu(n,r.file,this.signal))?.alpha===!0;return t[r.id]=i,this.unsaved.add(n.key),i}catch{return!1}}saveProbes(){for(let n of this.unsaved){let r=Yn.find((t)=>t.key===n);if(r)bi(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n,r){this.posts.set(this.mark(n,r.id),r);let t=this.view.sets==="fold"?this.board.groups.at(-1):void 0,e=t?.posts[0],i=r.owner||r.artist;if(t&&e&&i&&(e.owner||e.artist)===i&&e.width===r.width&&e.height===r.height){if(t.posts.push(r),t.open)this.thumbQueue.push({site:n,post:r}),this.thumbs();return}this.board.groups.push({posts:[r],open:!1}),this.thumbQueue.push({site:n,post:r}),this.thumbs()}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=hu(this.home),e=ai(n,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let h=t.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&h?.site===n.key?[{name:c.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let h=e[c.id];if(h!==void 0)return{...c,owner:h};try{return{...c,owner:(await ti(n,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)e[c.id]=c.owner,s.set(c.name,c.owner);bi(n,"owners.json",e);let u=Fu(s);return this.owners.set(n.key,u),u}async cached(n,r,t,e){if(Yr(r))return am(r).size;let i=this.inflight.get(r);if(i)return i;let o=(async()=>{let s=await Su(n,t,this.signal,e);return wi(fc(r),{recursive:!0}),Ei(r,s),s.length})();this.inflight.set(r,o);try{return await o}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<Em&&this.thumbQueue.length>0){let{site:n,post:r}=this.thumbQueue.shift();this.thumbing++,this.thumb(n,r).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n,r){let t=Ln.cols*this.cell.w,e=Ln.rows*this.cell.h,i=cr($r(n),"tile",`${r.id}-${t}x${e}.png`);if(!Yr(i)){let o=cr($r(n),"thumb",`${r.id}.${Ur(r.preview)}`);await this.cached(n,o,r.preview),await this.renders.run({job:"thumb",from:o,to:i,width:t,height:e})}this.thumbPath.set(this.mark(n,r.id),i),this.show(),this.draw()}select(){let n=this.view,r=n.tiles[n.focus];if(this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,!r)return;if(this.current?.id===r.id){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),Mm),this.draw()}async load(n){let r=this.view,t=this.posts.get(this.mark(this.site,n.id)),e=t&&$t(t);if(!e)return;let i=this.site,o=new AbortController;this.fetch=o;try{let s=this.origPath(i,n.id,e.ext);if(!Yr(s))r.fetching={id:n.id,got:0,size:0},this.draw();let u=await this.cached(i,s,e.file,(f,g)=>{if(r.fetching?.id===n.id)r.fetching={id:n.id,got:f,size:g},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,i!==this.site)return;let c={site:i,id:n.id,path:s,ext:e.ext,size:u,using:"plain",failed:!1};r.preparing=n.id,this.flush();let h=await this.render(c,"plain");if(o.signal.aborted||i!==this.site)return;if(h.clear===0&&ei()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.id,this.flush(),c.cut=await this.cutOut(i,n.id,s,o.signal),o.signal.aborted||i!==this.site)return;if(r.cutting=void 0,c.cut){r.preparing=n.id,this.flush();let f=await this.render(c,"cut").catch(()=>{return});if(o.signal.aborted||i!==this.site)return;if(f&&yu(f.clear))c.using="cut";else di(c.cut,{force:!0}),c.cut=void 0,c.failed=!0}else c.failed=!0}if(this.current=c,r.tiles[r.focus]?.id===n.id)await this.present();this.preload()}catch(s){if(!o.signal.aborted&&!this.signal.aborted)r.error=lc(i,s)}finally{if(r.fetching?.id===n.id)r.fetching=void 0;if(r.preparing===n.id)r.preparing=void 0;if(r.cutting===n.id)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,e){let i=cr($r(n),"cut",`${r}.png`);if(Yr(i))return i;try{return wi(fc(i),{recursive:!0}),await Ou(t,i,e),i}catch{di(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.id)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;let r=this.site;for(let t of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=km)return;let e=n.tiles[t],i=e&&this.posts.get(this.mark(r,e.id)),o=i&&$t(i);if(!o)continue;let s=this.origPath(r,i.id,o.ext);this.prefetching++,this.cached(r,s,o.file).then(()=>this.render({site:r,id:i.id,path:s,ext:o.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(n,r){let t=this.cols*this.cell.w,e=this.rows*this.cell.h,i=Math.min(t,Im),o=Math.max(1,Math.round(e*i/t)),s=cr(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${o}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&Yr(s))return{clear:c,path:s};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:s}}async present(){let n=this.current;if(!n)return;let r=n.using,{clear:t,path:e}=await this.render(n,r);if(this.current!==n||n.using!==r)return;this.view.shown={id:n.id,clear:t,bytes:n.size,path:e,cut:n.cut?r==="cut"?"on":"off":n.failed?"failed":"none"}}reveal(){let n=this.view;n.preparing=this.current?.id,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.id)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.id!==r.id||n.preparing!==void 0||n.shown?.id!==r.id)return;n.installing=r.id,n.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:t.using==="cut"?t.cut:t.path,source:t.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:t.site.key,id:t.id,ext:t.ext,from:`${t.site.name} ${t.id} ${t.site.pageUrl(t.id)}`}});let e=ai(t.site,"owners.json");e[t.id]=this.posts.get(this.mark(t.site,t.id))?.owner??"",bi(t.site,"owners.json",e),Vr(this.home),process.stderr.write(`background · ${this.entry.name} ← ${t.site.name} ${t.id}
70
+ `),this.finish(0)}catch(e){n.installing=void 0,n.error=e instanceof Error?e.message:String(e),this.draw()}}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=Au(this.view,this.cols,this.rows),r="\x1B[?2026h";n.lines.forEach((e,i)=>{r+=`\x1B[${i+1};1H\x1B[K${e}`});let t=new Set;for(let e of n.images){if(t.add(e.id),this.sent.get(e.id)!==e.path)r+=Uu(e),this.sent.set(e.id,e.path),this.placed.delete(e.id);let i=`${e.row};${e.col};${e.cols};${e.rows};${e.z}`;if(this.placed.get(e.id)!==i)r+=qu(e),this.placed.set(e.id,i)}for(let e of this.sent.keys())if(!t.has(e))r+=Wu(e),this.sent.delete(e),this.placed.delete(e);this.write(`${r}\x1B[?2026l`)}}function pm(){if(process.versions.bun)return!0;let[n=0,r=0]=process.versions.node.split(".").map(Number);return n>22||n===22&&r>=21}async function Hm(){if(!pm())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
71
+ `),1;let n=await hc(),r=mc(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${n.port}`,TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((e)=>r.on("exit",(i)=>e(i??1)));return n.close(),t}async function ac(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Hm();let r=_n(),t=Qn(r),e=xt(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");return new $c(r,t,e,e.booru??"").run()}function bc(n,r){let t=_n();if(xt(Qn(t).palettes,n),r==="next"||r==="prev"){let{key:e,at:i,of:o}=su(t,n,r==="next"?1:-1);return Vr(t),process.stderr.write(`background · ${n} ${i}/${o} ${e}
72
+ `),0}if(r==="drop"){let{key:e,left:i}=uu(t,n);return Vr(t),process.stderr.write(`background · ${n} removed ${e??"the picture"} · ${i} left
73
+ `),0}if(r==="tuned")return Vr(t),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{chmodSync as Sd,copyFileSync as jd,existsSync as fr,mkdirSync as Xi,readdirSync as Gd,readFileSync as pt,rmSync as bh,writeFileSync as wh}from"node:fs";import{homedir as Jd}from"node:os";import{dirname as Nt,join as wn}from"node:path";import{styleText as Hi}from"node:util";import{stdout as Oc,stdin as Vm}from"node:process";import Ym from"node:readline";var wc=(()=>{let n=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(r)=>{let t=0;n.lastIndex=0;while(n.test(r))t+=1;return r.length-t}})(),Ec=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},kc=(n)=>{return n===8987||n===9001||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n>=131072&&n<=196605||n>=196608&&n<=262141};var Sm=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jm=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Mc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Gm=/\t{1,1000}/y,Fc=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Jm=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Km=/\p{M}+/gu,Rm={limit:1/0,ellipsis:""},Ic=(n,r={},t={})=>{let e=r.limit??1/0,i=r.ellipsis??"",o=r?.ellipsisWidth??(i?Ic(i,Rm,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,$=[[Jm,g],[Sm,0],[jm,u],[Gm,c],[Fc,h],[Mc,l]],a=0,w=0,F=n.length,v=0,j=!1,M=F,N=Math.max(0,e-o),b=0,K=0,E=0,J=0;n:while(!0){if(K>b||w>=F&&w>a){let S=n.slice(b,K)||n.slice(a,w);v=0;for(let O of S.replaceAll(Km,"")){let R=O.codePointAt(0)||0;if(Ec(R))J=2;else if(kc(R))J=l;else J=g;if(E+J>N)M=Math.min(M,Math.max(b,a)+v);if(E+J>e){j=!0;break n}v+=O.length,E+=J}b=K=0}if(w>=F)break n;for(let S=0,O=$.length;S<O;S++){let[R,A]=$[S];if(R.lastIndex=w,R.test(n)){if(v=R===Mc?wc(n.slice(w,R.lastIndex)):R===Fc?1:R.lastIndex-w,J=v*A,E+J>N)M=Math.min(M,w+Math.floor((N-E)/A));if(E+J>e){j=!0;break n}E+=J,b=a,K=w,w=a=R.lastIndex;continue n}}w+=1}return{width:j?N:E,index:j?M:F,truncated:j,ellipsed:j&&e>=o}},vc=Ic;var ym={limit:1/0,ellipsis:"",ellipsisWidth:0},Om=(n,r={})=>{return vc(n,ym,r).width},Rn=Om;var ee="\x1B",jc="›",Lm=39,Fi="\x07",Gc="[",Qm="]",Jc="m",Ii=`${Qm}8;;`,Nc=new RegExp(`(?:\\${Gc}(?<code>\\d+)m|\\${Ii}(?<uri>.*)${Fi})`,"y"),pc=(n)=>{if(n>=30&&n<=37)return 39;if(n>=90&&n<=97)return 39;if(n>=40&&n<=47)return 49;if(n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0;return},Hc=(n)=>`${ee}${Gc}${n}${Jc}`,Sc=(n)=>`${ee}${Ii}${n}${Fi}`,Mi=(n,r,t)=>{let e=r[Symbol.iterator](),i=!1,o=!1,s=n.at(-1),u=s===void 0?0:Rn(s),c=e.next(),h=e.next(),f=0;while(!c.done){let g=c.value,l=Rn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===ee||g===jc)i=!0,o=r.startsWith(Ii,f+1);if(i){if(o){if(g===Fi)i=!1,o=!1}else if(g===Jc)i=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=e.next(),f+=g.length}if(s=n.at(-1),!u&&s!==void 0&&s.length&&n.length>1)n[n.length-2]+=n.pop()},Zm=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Rn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},Um=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let e="",i,o,s=n.split(" "),u=[""],c=0;for(let g=0;g<s.length;g++){let l=s[g];if(t.trim!==!1){let a=u.at(-1)??"",w=a.trimStart();if(a.length!==w.length)u[u.length-1]=w,c=Rn(w)}if(g!==0){if(c>=r&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let $=Rn(l);if(t.hard&&$>r){let a=r-c,w=1+Math.floor(($-a-1)/r);if(Math.floor(($-1)/r)<w)u.push("");Mi(u,l,r),c=Rn(u.at(-1)??"");continue}if(c+$>r&&c&&$){if(t.wordWrap===!1&&c<r){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u.push(""),c=0}if(c+$>r&&t.wordWrap===!1){Mi(u,l,r),c=Rn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=$}if(t.trim!==!1)u=u.map((g)=>Zm(g));let h=u.join(`
74
+ `),f=!1;for(let g=0;g<h.length;g++){let l=h[g];if(e+=l,!f){if(f=l>="\uD800"&&l<="\uDBFF",f)continue}else f=!1;if(l===ee||l===jc){Nc.lastIndex=g+1;let a=Nc.exec(h)?.groups;if(a?.code!==void 0){let w=Number.parseFloat(a.code);i=w===Lm?void 0:w}else if(a?.uri!==void 0)o=a.uri.length===0?void 0:a.uri}if(h[g+1]===`
75
+ `){if(o)e+=Sc("");let $=i?pc(i):void 0;if(i&&$)e+=Hc($)}else if(l===`
76
+ `){if(i&&pc(i))e+=Hc(i);if(o)e+=Sc(o)}}return e},qm=/\r?\n/;function ar(n,r,t){return String(n).normalize().split(qm).map((e)=>Um(e,r,t)).join(`
77
+ `)}var Zn=Jt(Ni(),1);function hr(n,r,t){if(!t.some((s)=>!s.disabled))return n;let e=n+r,i=Math.max(t.length-1,0),o=e<0?i:e>i?0:e;return t[o]?.disabled?hr(o,r<0?-1:1,t):o}function ie(n,r,t,e){let i=e.split(`
78
78
  `),o=0,s=n;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+t)),s=Math.min(s,i[o].length)+r;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var Pm=["up","down","left","right","space","enter","cancel"],zm=["January","February","March","April","May","June","July","August","September","October","November","December"],yn={actions:new Set(Pm),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...zm],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(n,r)=>`There are only ${n} days in ${r}`,afterMin:(n)=>`Date must be on or after ${n.toISOString().slice(0,10)}`,beforeMax:(n)=>`Date must be on or before ${n.toISOString().slice(0,10)}`}}};function Lc(n,r){if(typeof n=="string")return yn.aliases.get(n)===r;for(let t of n)if(t!==void 0&&Lc(t,r))return!0;return!1}function Am(n,r){if(n===r)return;let t=n.split(`
79
79
  `),e=r.split(`
80
- `),i=Math.max(t.length,e.length),o=[];for(let s=0;s<i;s++)t[s]!==e[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:e.length,numLines:i}}var ja=globalThis.process.platform.startsWith("win"),Si=Symbol("clack:cancel");function Pr(n){return n===Si}function ie(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var se=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Gi=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function $r(n,r,t,e=t,i=t,o){let s=se(n??Oc);return dr(r,s-t.length,{hard:!0,trim:!1}).split(`
80
+ `),i=Math.max(t.length,e.length),o=[];for(let s=0;s<i;s++)t[s]!==e[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:e.length,numLines:i}}var ja=globalThis.process.platform.startsWith("win"),Si=Symbol("clack:cancel");function zr(n){return n===Si}function oe(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var ue=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Gi=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function br(n,r,t,e=t,i=t,o){let s=ue(n??Oc);return ar(r,s-t.length,{hard:!0,trim:!1}).split(`
81
81
  `).map((u,c,h)=>{let f=o?o(u,c):u;return c===0?`${e}${f}`:c===h.length-1?`${i}${f}`:`${t}${f}`}).join(`
82
- `)}function Qc(n,r){if("~standard"in n){let t=n["~standard"].validate(r);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return n(r)}class tr{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(n,r=!0){let{input:t=Vm,output:e=Oc,render:i,signal:o,...s}=n;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=t,this.output=e}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let t=this._subscribers.get(n)??[];t.push(r),this._subscribers.set(n,t)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let t=this._subscribers.get(n)??[],e=[];for(let i of t)i.cb(...r),i.once&&e.push(()=>t.splice(t.indexOf(i),1));for(let i of e)i()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(Si);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Ym.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),ie(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),ie(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),ie(this.input,!1),n(Si)})})}_isActionKey(n,r){return n==="\t"}_shouldSubmit(n,r){return!0}_setValue(n){this.value=n,this.emit("value",this.value)}_setUserInput(n,r){this.userInput=n??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(n,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(n,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&yn.aliases.has(r.name)&&this.emit("cursor",yn.aliases.get(r.name)),yn.actions.has(r.name)&&this.emit("cursor",r.name)),n&&(n.toLowerCase()==="y"||n.toLowerCase()==="n")&&this.emit("confirm",n.toLowerCase()==="y"),this.emit("key",n,r),r?.name==="return"&&this._shouldSubmit(n,r)){if(this.opts.validate){let t=Qc(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Lc([n,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
83
- `),ie(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=dr(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
84
- `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=dr(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(Zn.cursor.hide);else{let r=Am(this._prevFrame,n),t=Gi(this.output);if(this.restoreCursor(),r){let e=Math.max(0,r.numLinesAfter-t),i=Math.max(0,r.numLinesBefore-t),o=r.lines.find((s)=>s>=e);if(o===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(Zn.cursor.move(0,o-i)),this.output.write(Zn.erase.lines(1));let s=n.split(`
82
+ `)}function Qc(n,r){if("~standard"in n){let t=n["~standard"].validate(r);if(t instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return t.issues?.at(0)?.message}return n(r)}class tr{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(n,r=!0){let{input:t=Vm,output:e=Oc,render:i,signal:o,...s}=n;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=t,this.output=e}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let t=this._subscribers.get(n)??[];t.push(r),this._subscribers.set(n,t)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let t=this._subscribers.get(n)??[],e=[];for(let i of t)i.cb(...r),i.once&&e.push(()=>t.splice(t.indexOf(i),1));for(let i of e)i()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(Si);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Ym.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),oe(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),oe(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(Zn.cursor.show),this.output.off("resize",this.render),oe(this.input,!1),n(Si)})})}_isActionKey(n,r){return n==="\t"}_shouldSubmit(n,r){return!0}_setValue(n){this.value=n,this.emit("value",this.value)}_setUserInput(n,r){this.userInput=n??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(n,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(n,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&yn.aliases.has(r.name)&&this.emit("cursor",yn.aliases.get(r.name)),yn.actions.has(r.name)&&this.emit("cursor",r.name)),n&&(n.toLowerCase()==="y"||n.toLowerCase()==="n")&&this.emit("confirm",n.toLowerCase()==="y"),this.emit("key",n,r),r?.name==="return"&&this._shouldSubmit(n,r)){if(this.opts.validate){let t=Qc(this.opts.validate,this.value);t&&(this.error=t instanceof Error?t.message:t,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Lc([n,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
83
+ `),oe(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=ar(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
84
+ `).length-1;this.output.write(Zn.cursor.move(-999,n*-1))}render(){let n=ar(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(Zn.cursor.hide);else{let r=Am(this._prevFrame,n),t=Gi(this.output);if(this.restoreCursor(),r){let e=Math.max(0,r.numLinesAfter-t),i=Math.max(0,r.numLinesBefore-t),o=r.lines.find((s)=>s>=e);if(o===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(Zn.cursor.move(0,o-i)),this.output.write(Zn.erase.lines(1));let s=n.split(`
85
85
  `);this.output.write(s[o]),this._prevFrame=n,this.output.write(Zn.cursor.move(0,s.length-o-1));return}else if(r.lines.length>1){if(e<i)o=e;else{let u=o-i;u>0&&this.output.write(Zn.cursor.move(0,u))}this.output.write(Zn.erase.down());let s=n.split(`
86
86
  `).slice(o);this.output.write(s.join(`
87
- `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function Cm(n,r){if(n===void 0||r.length===0)return 0;let t=r.findIndex((e)=>e.value===n);return t!==-1?t:0}function Tm(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function _m(n,r){if(r)return n?r:r[0]}var Bm=class extends tr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Hi(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),e=this.userInput.slice(this.cursor+1);return`${r}${Hi("inverse",t)}${e}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??Tm;let e;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?e=r.initialValue:e=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(e=[this.options[0]?.value]),e)for(let i of e){let o=t.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#r=o)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,o)=>this.#t(i,o)),this.on("userInput",(i)=>this.#e(i))}_isActionKey(r,t){return r==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&r!==void 0&&r!==""}#t(r,t){let e=t.name==="up",i=t.name==="down",o=t.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,h=u!==void 0&&u!==""&&c.some((f)=>!f.disabled&&(this.#n?this.#n(u,f):!0));if(t.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}e||i?(this.#r=cr(this.#r,e?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=_m(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(r){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(r)?this.selectedValues=this.selectedValues.filter((t)=>t!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#e(r){if(r!==this.#i){this.#i=r;let t=this.options;r&&this.#n?this.filteredOptions=t.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...t];let e=Cm(this.focusedValue,this.filteredOptions);this.#r=cr(e,0,this.filteredOptions);let i=this.filteredOptions[this.#r];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Ji extends tr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(n){super(n,!1),this.value=!!n.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(r)=>{this.output.write(Zn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var xm={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Rc(n){return[...n].map((r)=>xm[r])}function Dm(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],e="/";for(let i of r)i.type==="literal"?e=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&t.push({type:i.type,len:i.type==="year"?4:2});return{segments:t,separator:e}}function Ni(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function oe(n){return{year:Ni(n.year),month:Ni(n.month),day:Ni(n.day)}}function ji(n,r){return new Date(n||2001,r||1,0).getDate()}function Zc(n){let{year:r,month:t,day:e}=oe(n);if(!r||r<0||r>9999||!t||t<1||t>12||!e||e<1)return;let i=new Date(Date.UTC(r,t-1,e));if(!(i.getUTCFullYear()!==r||i.getUTCMonth()!==t-1||i.getUTCDate()!==e))return{year:r,month:t,day:e}}function yc(n){let r=Zc(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function nd(n,r,t,e){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:o?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:o&&r.year===o.year?o.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:o&&r.year===o.year&&r.month===o.month?o.day:ji(r.year,r.month)}}class Uc extends tr{#r;#i;#n;#o;#u;#t={segmentIndex:0,positionInSegment:0};#e=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#t}}get segmentValues(){return{...this.#n}}get segments(){return this.#r}get separator(){return this.#i}get formattedValue(){return this.#g(this.#n)}#g(n){return this.#r.map((r)=>n[r.type]).join(this.#i)}#c(){this._setUserInput(this.#g(this.#n)),this._setValue(yc(this.#n)??void 0)}constructor(n){let r=n.format?{segments:Rc(n.format),separator:n.separator??"/"}:Dm(n.locale),t=n.separator??r.separator,e=n.format?Rc(n.format):r.segments,i=n.initialValue??n.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=e.map((u)=>o[u.type]).join(t);super({...n,initialUserInput:s},!1),this.#r=e,this.#i=t,this.#n=o,this.#o=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#d(u)),this.on("key",(u,c)=>this.#$(u,c)),this.on("finalize",()=>this.#a(n))}#h(){let n=Math.max(0,Math.min(this.#t.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#t.positionInSegment=Math.max(0,Math.min(this.#t.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#t.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#t.positionInSegment=0,this.#e=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:t}=r,e=this.#n[t.type],i=!e||e.replace(/_/g,"")==="",o=Number.parseInt((e||"0").replace(/_/g,"0"),10)||0,s=nd(t.type,oe(this.#n),this.#o,this.#u),u;i?u=n===1?s.min:s.max:u=Math.max(Math.min(s.max,o+n),s.min),this.#n={...this.#n,[t.type]:u.toString().padStart(t.len,"0")},this.#e=!0,this.#s=null,this.#c()}#d(n){if(n)switch(n){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#$(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let t=this.#h();if(!t)return;if(!this.#n[t.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[t.segment.type]="_".repeat(t.segment.len),this.#e=!0,this.#t.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let t=this.#h();if(!t)return;let e=r.shift?-1:1,i=t.index+e;i>=0&&i<this.#r.length&&(this.#t.segmentIndex=i,this.#t.positionInSegment=0,this.#e=!0);return}if(n&&/^[0-9]$/.test(n)){let t=this.#h();if(!t)return;let{segment:e}=t,i=!this.#n[e.type].replace(/_/g,"");if(this.#e&&this.#s!==null&&!i){let l=this.#s+n,$={...this.#n,[e.type]:l},a=this.#m($,e);if(a){this.inlineError=a,this.#s=null,this.#e=!1;return}this.inlineError="",this.#n[e.type]=l,this.#s=null,this.#e=!1,this.#c(),t.index<this.#r.length-1&&(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0);return}this.#e&&!i&&(this.#n[e.type]="_".repeat(e.len),this.#t.positionInSegment=0),this.#e=!1,this.#s=null;let o=this.#n[e.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#t.positionInSegment,e.len-1);if(u<0||u>=e.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(e.type==="month"||e.type==="day")){let l=Number.parseInt(n,10);c=`0${n}`,h=l<=(e.type==="month"?1:2)}if(e.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(e.len,"_")),!c.includes("_")){let l={...this.#n,[e.type]:c},$=this.#m(l,e);if($){this.inlineError=$;return}}this.inlineError="",this.#n[e.type]=c;let f=c.includes("_")?void 0:Zc(this.#n);if(f){let{year:l,month:$}=f,a=ji(l,$);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,$))).padStart(2,"0"),day:String(Math.max(1,Math.min(a,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#e=!0,this.#s=n):g>=0?this.#t.positionInSegment=g:s>=0&&t.index<this.#r.length-1?(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0):this.#t.positionInSegment=Math.min(u+1,e.len-1)}}#m(n,r){let{month:t,day:e}=oe(n);if(r.type==="month"&&(t<0||t>12))return yn.date.messages.invalidMonth;if(r.type==="day"&&(e<0||e>31))return yn.date.messages.invalidDay(31,"any month")}#a(n){let{year:r,month:t,day:e}=oe(this.#n);if(r&&t&&e){let i=ji(r,t);this.#n={...this.#n,day:String(Math.min(e,i)).padStart(2,"0")}}this.value=yc(this.#n)??n.defaultValue??void 0}}var rd=class extends tr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((t)=>t.group===r)}isGroupSelected(r){let t=this.getGroupItems(r),e=this.value;return e===void 0?!1:t.every((i)=>e.includes(i.value))}toggleValue(){let r=this.options[this.cursor];if(r!==void 0)if(this.value===void 0&&(this.value=[]),r.group===!0){let t=r.value,e=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>e.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...e.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(r.value);this.value=t?this.value.filter((e)=>e!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:t}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([e,i])=>[{value:e,group:!0,label:e},...i.map((o)=>({...o,group:e}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:e})=>e===r.cursorAt),this.#r?0:1),this.on("cursor",(e)=>{switch(e){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},td=new Set(["up","down","left","right"]);class qc extends tr{#r=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let n=this.userInput;if(this.cursor>=n.length)return`${n}█`;let r=n.slice(0,this.cursor),t=n.slice(this.cursor,this.cursor+1),e=n.slice(this.cursor+1);return t===`
87
+ `)),this._prevFrame=n;return}}this.output.write(Zn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function Cm(n,r){if(n===void 0||r.length===0)return 0;let t=r.findIndex((e)=>e.value===n);return t!==-1?t:0}function Tm(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function _m(n,r){if(r)return n?r:r[0]}var Bm=class extends tr{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#o;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Hi(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let r=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),e=this.userInput.slice(this.cursor+1);return`${r}${Hi("inverse",t)}${e}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(r){super(r),this.#o=r.options,this.#u=r.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=r.multiple===!0,this.#n=typeof r.options=="function"?r.filter:r.filter??Tm;let e;if(r.initialValue&&Array.isArray(r.initialValue)?this.multiple?e=r.initialValue:e=r.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(e=[this.options[0]?.value]),e)for(let i of e){let o=t.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#r=o)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,o)=>this.#t(i,o)),this.on("userInput",(i)=>this.#e(i))}_isActionKey(r,t){return r==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&r!==void 0&&r!==""}#t(r,t){let e=t.name==="up",i=t.name==="down",o=t.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,h=u!==void 0&&u!==""&&c.some((f)=>!f.disabled&&(this.#n?this.#n(u,f):!0));if(t.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}e||i?(this.#r=hr(this.#r,e?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=_m(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(t.name==="tab"||this.isNavigating&&t.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(r){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(r)?this.selectedValues=this.selectedValues.filter((t)=>t!==r):this.selectedValues=[...this.selectedValues,r]:this.selectedValues=[r])}#e(r){if(r!==this.#i){this.#i=r;let t=this.options;r&&this.#n?this.filteredOptions=t.filter((o)=>this.#n?.(r,o)):this.filteredOptions=[...t];let e=Cm(this.focusedValue,this.filteredOptions);this.#r=hr(e,0,this.filteredOptions);let i=this.filteredOptions[this.#r];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Ji extends tr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(n){super(n,!1),this.value=!!n.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(r)=>{this.output.write(Zn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var xm={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Rc(n){return[...n].map((r)=>xm[r])}function Dm(n){let r=new Intl.DateTimeFormat(n,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],e="/";for(let i of r)i.type==="literal"?e=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&t.push({type:i.type,len:i.type==="year"?4:2});return{segments:t,separator:e}}function pi(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function se(n){return{year:pi(n.year),month:pi(n.month),day:pi(n.day)}}function ji(n,r){return new Date(n||2001,r||1,0).getDate()}function Zc(n){let{year:r,month:t,day:e}=se(n);if(!r||r<0||r>9999||!t||t<1||t>12||!e||e<1)return;let i=new Date(Date.UTC(r,t-1,e));if(!(i.getUTCFullYear()!==r||i.getUTCMonth()!==t-1||i.getUTCDate()!==e))return{year:r,month:t,day:e}}function yc(n){let r=Zc(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function nd(n,r,t,e){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:o?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:o&&r.year===o.year?o.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:o&&r.year===o.year&&r.month===o.month?o.day:ji(r.year,r.month)}}class Uc extends tr{#r;#i;#n;#o;#u;#t={segmentIndex:0,positionInSegment:0};#e=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#t}}get segmentValues(){return{...this.#n}}get segments(){return this.#r}get separator(){return this.#i}get formattedValue(){return this.#g(this.#n)}#g(n){return this.#r.map((r)=>n[r.type]).join(this.#i)}#c(){this._setUserInput(this.#g(this.#n)),this._setValue(yc(this.#n)??void 0)}constructor(n){let r=n.format?{segments:Rc(n.format),separator:n.separator??"/"}:Dm(n.locale),t=n.separator??r.separator,e=n.format?Rc(n.format):r.segments,i=n.initialValue??n.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=e.map((u)=>o[u.type]).join(t);super({...n,initialUserInput:s},!1),this.#r=e,this.#i=t,this.#n=o,this.#o=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#d(u)),this.on("key",(u,c)=>this.#$(u,c)),this.on("finalize",()=>this.#a(n))}#h(){let n=Math.max(0,Math.min(this.#t.segmentIndex,this.#r.length-1)),r=this.#r[n];if(r)return this.#t.positionInSegment=Math.max(0,Math.min(this.#t.positionInSegment,r.len-1)),{segment:r,index:n}}#f(n){this.inlineError="",this.#s=null;let r=this.#h();r&&(this.#t.segmentIndex=Math.max(0,Math.min(this.#r.length-1,r.index+n)),this.#t.positionInSegment=0,this.#e=!0)}#l(n){let r=this.#h();if(!r)return;let{segment:t}=r,e=this.#n[t.type],i=!e||e.replace(/_/g,"")==="",o=Number.parseInt((e||"0").replace(/_/g,"0"),10)||0,s=nd(t.type,se(this.#n),this.#o,this.#u),u;i?u=n===1?s.min:s.max:u=Math.max(Math.min(s.max,o+n),s.min),this.#n={...this.#n,[t.type]:u.toString().padStart(t.len,"0")},this.#e=!0,this.#s=null,this.#c()}#d(n){if(n)switch(n){case"right":return this.#f(1);case"left":return this.#f(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#$(n,r){if(r?.name==="backspace"||r?.sequence===""||r?.sequence==="\b"||n===""||n==="\b"){this.inlineError="";let t=this.#h();if(!t)return;if(!this.#n[t.segment.type].replace(/_/g,"")){this.#f(-1);return}this.#n[t.segment.type]="_".repeat(t.segment.len),this.#e=!0,this.#t.positionInSegment=0,this.#c();return}if(r?.name==="tab"){this.inlineError="";let t=this.#h();if(!t)return;let e=r.shift?-1:1,i=t.index+e;i>=0&&i<this.#r.length&&(this.#t.segmentIndex=i,this.#t.positionInSegment=0,this.#e=!0);return}if(n&&/^[0-9]$/.test(n)){let t=this.#h();if(!t)return;let{segment:e}=t,i=!this.#n[e.type].replace(/_/g,"");if(this.#e&&this.#s!==null&&!i){let l=this.#s+n,$={...this.#n,[e.type]:l},a=this.#m($,e);if(a){this.inlineError=a,this.#s=null,this.#e=!1;return}this.inlineError="",this.#n[e.type]=l,this.#s=null,this.#e=!1,this.#c(),t.index<this.#r.length-1&&(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0);return}this.#e&&!i&&(this.#n[e.type]="_".repeat(e.len),this.#t.positionInSegment=0),this.#e=!1,this.#s=null;let o=this.#n[e.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#t.positionInSegment,e.len-1);if(u<0||u>=e.len)return;let c=o.slice(0,u)+n+o.slice(u+1),h=!1;if(u===0&&o==="__"&&(e.type==="month"||e.type==="day")){let l=Number.parseInt(n,10);c=`0${n}`,h=l<=(e.type==="month"?1:2)}if(e.type==="year"&&(c=(o.replace(/_/g,"")+n).padStart(e.len,"_")),!c.includes("_")){let l={...this.#n,[e.type]:c},$=this.#m(l,e);if($){this.inlineError=$;return}}this.inlineError="",this.#n[e.type]=c;let f=c.includes("_")?void 0:Zc(this.#n);if(f){let{year:l,month:$}=f,a=ji(l,$);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,$))).padStart(2,"0"),day:String(Math.max(1,Math.min(a,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#e=!0,this.#s=n):g>=0?this.#t.positionInSegment=g:s>=0&&t.index<this.#r.length-1?(this.#t.segmentIndex=t.index+1,this.#t.positionInSegment=0,this.#e=!0):this.#t.positionInSegment=Math.min(u+1,e.len-1)}}#m(n,r){let{month:t,day:e}=se(n);if(r.type==="month"&&(t<0||t>12))return yn.date.messages.invalidMonth;if(r.type==="day"&&(e<0||e>31))return yn.date.messages.invalidDay(31,"any month")}#a(n){let{year:r,month:t,day:e}=se(this.#n);if(r&&t&&e){let i=ji(r,t);this.#n={...this.#n,day:String(Math.min(e,i)).padStart(2,"0")}}this.value=yc(this.#n)??n.defaultValue??void 0}}var rd=class extends tr{options;cursor=0;#r;getGroupItems(r){return this.options.filter((t)=>t.group===r)}isGroupSelected(r){let t=this.getGroupItems(r),e=this.value;return e===void 0?!1:t.every((i)=>e.includes(i.value))}toggleValue(){let r=this.options[this.cursor];if(r!==void 0)if(this.value===void 0&&(this.value=[]),r.group===!0){let t=r.value,e=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>e.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...e.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(r.value);this.value=t?this.value.filter((e)=>e!==r.value):[...this.value,r.value]}}constructor(r){super(r,!1);let{options:t}=r;this.#r=r.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([e,i])=>[{value:e,group:!0,label:e},...i.map((o)=>({...o,group:e}))]),this.value=[...r.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:e})=>e===r.cursorAt),this.#r?0:1),this.on("cursor",(e)=>{switch(e){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#r&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},td=new Set(["up","down","left","right"]);class qc extends tr{#r=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let n=this.userInput;if(this.cursor>=n.length)return`${n}█`;let r=n.slice(0,this.cursor),t=n.slice(this.cursor,this.cursor+1),e=n.slice(this.cursor+1);return t===`
88
88
  `?`${r}█
89
- ${e}`:`${r}${Hi("inverse",t)}${e}`}get cursor(){return this._cursor}#n(n){if(this.userInput.length===0){this._setUserInput(n);return}this._setUserInput(this.userInput.slice(0,this.cursor)+n+this.userInput.slice(this.cursor))}#o(n){let r=this.value??"";switch(n){case"up":this._cursor=ee(this._cursor,0,-1,r);return;case"down":this._cursor=ee(this._cursor,0,1,r);return;case"left":this._cursor=ee(this._cursor,-1,0,r);return;case"right":this._cursor=ee(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
89
+ ${e}`:`${r}${Hi("inverse",t)}${e}`}get cursor(){return this._cursor}#n(n){if(this.userInput.length===0){this._setUserInput(n);return}this._setUserInput(this.userInput.slice(0,this.cursor)+n+this.userInput.slice(this.cursor))}#o(n){let r=this.value??"";switch(n){case"up":this._cursor=ie(this._cursor,0,-1,r);return;case"down":this._cursor=ie(this._cursor,0,1,r);return;case"left":this._cursor=ie(this._cursor,-1,0,r);return;case"right":this._cursor=ie(this._cursor,1,0,r);return}}_shouldSubmit(n,r){if(this.#i)return this.focused==="submit"?!0:(this.#n(`
90
90
  `),this._cursor++,!1);let t=this.#r;return this.#r=!0,t&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
91
91
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#n(`
92
- `),this._cursor++,!1)}constructor(n){let r=n.initialUserInput??n.initialValue;super({...n,initialUserInput:r},!1),r!==void 0&&(this._cursor=r.length),this.#i=n.showSubmit??!1,this.on("key",(t,e)=>{if(e?.name&&td.has(e.name)){this.#r=!1,this.#o(e.name);return}if(t==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(e?.name!=="return"){if(this.#r=!1,e?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(e?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#n(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class Ki extends tr{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((n)=>n.disabled!==!0)}toggleAll(){let n=this._enabledOptions,r=this.value!==void 0&&this.value.length===n.length;this.value=r?[]:n.map((t)=>t.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((t)=>!n.includes(t.value));this.value=r.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let n=this.value.includes(this._value);this.value=n?this.value.filter((r)=>r!==this._value):[...this.value,this._value]}constructor(n){super(n,!1),this.options=n.options,this.value=[...n.initialValues??[]];let r=Math.max(this.options.findIndex(({value:t})=>t===n.cursorAt),0);this.cursor=this.options[r]?.disabled?cr(r,1,this.options):r,this.on("key",(t,e)=>{e.name==="a"&&this.toggleAll(),e.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=cr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=cr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Wc=class extends tr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let r=this._selectedValue;this.value=r===void 0?void 0:r.value}constructor(r){super(r,!1),this.options=r.options;let t=this.options.findIndex(({value:i})=>i===r.initialValue),e=t===-1?0:t;this.cursor=this.options[e]?.disabled?cr(e,1,this.options):e,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=cr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=cr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as k,stripVTControlCharacters as Za}from"node:util";import zn from"node:process";var zc=Jt(pi(),1);function ed(){if(zn.platform!=="win32")return zn.env.TERM!=="linux";return Boolean(zn.env.CI)||Boolean(zn.env.WT_SESSION)||Boolean(zn.env.TERMINUS_SUBLIME)||zn.env.ConEmuTask==="{cmd::Cmder}"||zn.env.TERM_PROGRAM==="Terminus-Sublime"||zn.env.TERM_PROGRAM==="vscode"||zn.env.TERM==="xterm-256color"||zn.env.TERM==="alacritty"||zn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var id=ed();var ln=(n,r)=>id?n:r,od=ln("◆","*"),sd=ln("■","x"),ud=ln("▲","x"),Ac=ln("◇","o"),cd=ln("┌","T"),cn=ln("│","|"),pr=ln("└","—"),Xa=ln("┐","T"),Va=ln("┘","—"),Ri=ln("●",">"),ce=ln("○"," "),hd=ln("◻","[•]"),Xc=ln("◼","[+]"),Vc=ln("◻","[ ]"),Ya=ln("▪","•"),Yc=ln("─","-"),fd=ln("╮","+"),gd=ln("├","+"),ld=ln("╯","+"),md=ln("╰","+"),Pa=ln("╭","+"),za=ln("●","•"),Aa=ln("◆","*"),Ca=ln("▲","!"),Ta=ln("■","x"),Oi=(n)=>{switch(n){case"initial":case"active":return k("cyan",od);case"cancel":return k("red",sd);case"error":return k("yellow",ud);case"submit":return k("green",Ac)}},Cc=(n)=>{switch(n){case"initial":case"active":return k("cyan",cn);case"cancel":return k("red",cn);case"error":return k("yellow",cn);case"submit":return k("green",cn)}};function Tc(n,r){let t=[`${r?`${k("cyan",cn)} `:""}${n.join(" • ")}`];return r&&t.push(k("cyan",pr)),t}var Pc=(n,r,t,e,i,o=!1)=>{let s=r,u=0;if(o)for(let c=e-1;c>=t;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}else for(let c=t;c<e;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}return{lineCount:s,removals:u}},yi=({cursor:n,options:r,style:t,output:e=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=se(e)-o,c=Gi(e),h=k("dim","..."),f=Math.max(c-s,0),g=Math.max(Math.min(i,f),5),l=0;n>=g-3&&(l=Math.max(Math.min(n-g+3,r.length-g),0));let $=g<r.length&&l>0,a=g<r.length&&l+g<r.length,w=Math.min(l+g,r.length),F=[],v=0;$&&v++,a&&v++;let j=l+($?1:0),M=w-(a?1:0);for(let b=j;b<M;b++){let K=r[b],E=K?t(K,b===n):"",J=dr(E,u,{hard:!0,trim:!1}).split(`
93
- `);F.push(J),v+=J.length}if(v>f){let b=0,K=0,E=v,J=n-j,S=f,O=()=>Pc(F,E,0,J,S),R=()=>Pc(F,E,J+1,F.length,S,!0);$?({lineCount:E,removals:b}=O(),E>S&&(a||(S-=1),{lineCount:E,removals:K}=R())):(a||(S-=1),{lineCount:E,removals:K}=R(),E>S&&(S-=1,{lineCount:E,removals:b}=O())),b>0&&($=!0,F.splice(0,b)),K>0&&(a=!0,F.splice(F.length-K,K))}let p=[];$&&p.push(h);for(let b of F)for(let K of b)p.push(K);return a&&p.push(h),p};var _c=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new Ji({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=e?`${k("gray",cn)} `:"",s=$r(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
92
+ `),this._cursor++,!1)}constructor(n){let r=n.initialUserInput??n.initialValue;super({...n,initialUserInput:r},!1),r!==void 0&&(this._cursor=r.length),this.#i=n.showSubmit??!1,this.on("key",(t,e)=>{if(e?.name&&td.has(e.name)){this.#r=!1,this.#o(e.name);return}if(t==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(e?.name!=="return"){if(this.#r=!1,e?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(e?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#n(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}class Ki extends tr{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((n)=>n.disabled!==!0)}toggleAll(){let n=this._enabledOptions,r=this.value!==void 0&&this.value.length===n.length;this.value=r?[]:n.map((t)=>t.value)}toggleInvert(){let n=this.value;if(!n)return;let r=this._enabledOptions.filter((t)=>!n.includes(t.value));this.value=r.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let n=this.value.includes(this._value);this.value=n?this.value.filter((r)=>r!==this._value):[...this.value,this._value]}constructor(n){super(n,!1),this.options=n.options,this.value=[...n.initialValues??[]];let r=Math.max(this.options.findIndex(({value:t})=>t===n.cursorAt),0);this.cursor=this.options[r]?.disabled?hr(r,1,this.options):r,this.on("key",(t,e)=>{e.name==="a"&&this.toggleAll(),e.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=hr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=hr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Wc=class extends tr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let r=this._selectedValue;this.value=r===void 0?void 0:r.value}constructor(r){super(r,!1),this.options=r.options;let t=this.options.findIndex(({value:i})=>i===r.initialValue),e=t===-1?0:t;this.cursor=this.options[e]?.disabled?hr(e,1,this.options):e,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=hr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=hr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as k,stripVTControlCharacters as Za}from"node:util";import zn from"node:process";var zc=Jt(Ni(),1);function ed(){if(zn.platform!=="win32")return zn.env.TERM!=="linux";return Boolean(zn.env.CI)||Boolean(zn.env.WT_SESSION)||Boolean(zn.env.TERMINUS_SUBLIME)||zn.env.ConEmuTask==="{cmd::Cmder}"||zn.env.TERM_PROGRAM==="Terminus-Sublime"||zn.env.TERM_PROGRAM==="vscode"||zn.env.TERM==="xterm-256color"||zn.env.TERM==="alacritty"||zn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var id=ed();var ln=(n,r)=>id?n:r,od=ln("◆","*"),sd=ln("■","x"),ud=ln("▲","x"),Ac=ln("◇","o"),cd=ln("┌","T"),cn=ln("│","|"),pr=ln("└","—"),Xa=ln("┐","T"),Va=ln("┘","—"),Ri=ln("●",">"),he=ln("○"," "),hd=ln("◻","[•]"),Xc=ln("◼","[+]"),Vc=ln("◻","[ ]"),Ya=ln("▪","•"),Yc=ln("─","-"),fd=ln("╮","+"),gd=ln("├","+"),ld=ln("╯","+"),md=ln("╰","+"),Pa=ln("╭","+"),za=ln("●","•"),Aa=ln("◆","*"),Ca=ln("▲","!"),Ta=ln("■","x"),Oi=(n)=>{switch(n){case"initial":case"active":return k("cyan",od);case"cancel":return k("red",sd);case"error":return k("yellow",ud);case"submit":return k("green",Ac)}},Cc=(n)=>{switch(n){case"initial":case"active":return k("cyan",cn);case"cancel":return k("red",cn);case"error":return k("yellow",cn);case"submit":return k("green",cn)}};function Tc(n,r){let t=[`${r?`${k("cyan",cn)} `:""}${n.join(" • ")}`];return r&&t.push(k("cyan",pr)),t}var Pc=(n,r,t,e,i,o=!1)=>{let s=r,u=0;if(o)for(let c=e-1;c>=t;c--){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}else for(let c=t;c<e;c++){let h=n[c];if(h&&(s-=h.length),u++,s<=i)break}return{lineCount:s,removals:u}},yi=({cursor:n,options:r,style:t,output:e=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=ue(e)-o,c=Gi(e),h=k("dim","..."),f=Math.max(c-s,0),g=Math.max(Math.min(i,f),5),l=0;n>=g-3&&(l=Math.max(Math.min(n-g+3,r.length-g),0));let $=g<r.length&&l>0,a=g<r.length&&l+g<r.length,w=Math.min(l+g,r.length),F=[],v=0;$&&v++,a&&v++;let j=l+($?1:0),M=w-(a?1:0);for(let b=j;b<M;b++){let K=r[b],E=K?t(K,b===n):"",J=ar(E,u,{hard:!0,trim:!1}).split(`
93
+ `);F.push(J),v+=J.length}if(v>f){let b=0,K=0,E=v,J=n-j,S=f,O=()=>Pc(F,E,0,J,S),R=()=>Pc(F,E,J+1,F.length,S,!0);$?({lineCount:E,removals:b}=O(),E>S&&(a||(S-=1),{lineCount:E,removals:K}=R())):(a||(S-=1),{lineCount:E,removals:K}=R(),E>S&&(S-=1,{lineCount:E,removals:b}=O())),b>0&&($=!0,F.splice(0,b)),K>0&&(a=!0,F.splice(F.length-K,K))}let N=[];$&&N.push(h);for(let b of F)for(let K of b)N.push(K);return a&&N.push(h),N};var _c=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new Ji({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=e?`${k("gray",cn)} `:"",s=br(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
94
94
  `:""}${s}
95
95
  `,c=this.value?r:t;switch(this.state){case"submit":{let h=e?`${k("gray",cn)} `:"";return`${u}${h}${k("dim",c)}`}case"cancel":{let h=e?`${k("gray",cn)} `:"";return`${u}${h}${k(["strikethrough","dim"],c)}${e?`
96
- ${k("gray",cn)}`:""}`}default:{let h=e?`${k("cyan",cn)} `:"",f=e?k("cyan",pr):"";return`${u}${h}${this.value?`${k("green",Ri)} ${r}`:`${k("dim",ce)} ${k("dim",r)}`}${n.vertical?e?`
96
+ ${k("gray",cn)}`:""}`}default:{let h=e?`${k("cyan",cn)} `:"",f=e?k("cyan",pr):"";return`${u}${h}${this.value?`${k("green",Ri)} ${r}`:`${k("dim",he)} ${k("dim",r)}`}${n.vertical?e?`
97
97
  ${k("cyan",cn)} `:`
98
- `:` ${k("dim","/")} `}${this.value?`${k("dim",ce)} ${k("dim",t)}`:`${k("green",Ri)} ${t}`}
98
+ `:` ${k("dim","/")} `}${this.value?`${k("dim",he)} ${k("dim",t)}`:`${k("green",Ri)} ${t}`}
99
99
  ${f}
100
100
  `}}}}).prompt()};var dd=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Space:")} select`,`${k("dim","Enter:")} confirm`],vt=(n,r)=>n.split(`
101
101
  `).map((t)=>r(t)).join(`
102
102
  `),Bc=(n)=>{let r=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${k("gray",Vc)} ${vt(s,(u)=>k(["strikethrough","gray"],u))}${i.hint?` ${k("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${k("cyan",hd)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${k("green",Xc)} ${vt(s,(u)=>k("dim",u))}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${vt(s,(u)=>k(["strikethrough","dim"],u))}`:o==="active-selected"?`${k("green",Xc)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${vt(s,(u)=>k("dim",u))}`:`${k("dim",Vc)} ${vt(s,(u)=>k("dim",u))}`},t=n.required??!0,e=n.showInstructions??!0;return new Ki({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValues:n.initialValues,required:t,cursorAt:n.cursorAt,validate(i){if(t&&(i===void 0||i.length===0))return`Please select at least one option.
103
- ${k("reset",k("dim",`Press ${k(["gray","bgWhite","inverse"]," space ")} to select, ${k("gray",k("bgWhite",k("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??yn.withGuide,o=$r(n.output,n.message,i?`${Cc(this.state)} `:"",`${Oi(this.state)} `),s=`${i?`${k("gray",cn)}
103
+ ${k("reset",k("dim",`Press ${k(["gray","bgWhite","inverse"]," space ")} to select, ${k("gray",k("bgWhite",k("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??yn.withGuide,o=br(n.output,n.message,i?`${Cc(this.state)} `:"",`${Oi(this.state)} `),s=`${i?`${k("gray",cn)}
104
104
  `:""}${o}
105
- `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let g=u.includes(h.value);return f&&g?r(h,"active-selected"):g?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"submitted")).join(k("dim",", "))||k("dim","none"),f=$r(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(k("dim",", "));if(h.trim()==="")return`${s}${k("gray",cn)}`;let f=$r(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}${i?`
105
+ `,u=this.value??[],c=(h,f)=>{if(h.disabled)return r(h,"disabled");let g=u.includes(h.value);return f&&g?r(h,"active-selected"):g?r(h,"selected"):r(h,f?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"submitted")).join(k("dim",", "))||k("dim","none"),f=br(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(k("dim",", "));if(h.trim()==="")return`${s}${k("gray",cn)}`;let f=br(n.output,h,i?`${k("gray",cn)} `:"");return`${s}${f}${i?`
106
106
  ${k("gray",cn)}`:""}`}case"error":{let h=i?`${k("yellow",cn)} `:"",f=this.error.split(`
107
107
  `).map(($,a)=>a===0?`${i?`${k("yellow",pr)} `:""}${k("yellow",$)}`:` ${$}`).join(`
108
108
  `),g=s.split(`
@@ -115,43 +115,43 @@ ${f}
115
115
  `),$=g.length+1;return`${s}${h}${yi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+$,style:c}).join(`
116
116
  ${h}`)}
117
117
  ${l}
118
- `}}}}).prompt()};var he=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",pr)} `:"";t.write(`${e}${k("red",n)}
118
+ `}}}}).prompt()};var fe=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",pr)} `:"";t.write(`${e}${k("red",n)}
119
119
 
120
120
  `)},xc=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",cd)} `:"";t.write(`${e}${n}
121
121
  `)},Dc=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??yn.withGuide?`${k("gray",cn)}
122
122
  ${k("gray",pr)} `:"";t.write(`${e}${n}
123
123
 
124
- `)};var $d=(n)=>n,ad=(n,r,t)=>{let e={hard:!0,trim:!1},i=dr(n,r,e).split(`
125
- `),o=i.reduce((c,h)=>Math.max(Rn(h),c),0),s=i.map(t).reduce((c,h)=>Math.max(Rn(h),c),0),u=r-(s-o);return dr(n,u,e)},fe=(n="",r="",t)=>{let e=t?.output??zn.stdout,i=t?.withGuide??yn.withGuide,o=t?.format??$d,s=["",...ad(n,se(e)-6,o).split(`
124
+ `)};var $d=(n)=>n,ad=(n,r,t)=>{let e={hard:!0,trim:!1},i=ar(n,r,e).split(`
125
+ `),o=i.reduce((c,h)=>Math.max(Rn(h),c),0),s=i.map(t).reduce((c,h)=>Math.max(Rn(h),c),0),u=r-(s-o);return ar(n,u,e)},ge=(n="",r="",t)=>{let e=t?.output??zn.stdout,i=t?.withGuide??yn.withGuide,o=t?.format??$d,s=["",...ad(n,ue(e)-6,o).split(`
126
126
  `).map(o),""],u=Rn(r),c=Math.max(s.reduce((l,$)=>{let a=Rn($);return a>l?a:l},0),u)+2,h=s.map((l)=>`${k("gray",cn)} ${l}${" ".repeat(c-Rn(l))}${k("gray",cn)}`).join(`
127
127
  `),f=i?`${k("gray",cn)}
128
128
  `:"",g=i?gd:md;e.write(`${f}${k("green",Ac)} ${k("reset",r)} ${k("gray",Yc.repeat(Math.max(c-u-1,1))+fd)}
129
129
  ${h}
130
130
  ${k("gray",g+Yc.repeat(c+2)+ld)}
131
- `)};var _a={light:ln("─","-"),heavy:ln("━","="),block:ln("█","#")};var bd=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Enter:")} confirm`],ue=(n,r)=>n.includes(`
131
+ `)};var _a={light:ln("─","-"),heavy:ln("━","="),block:ln("█","#")};var bd=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Enter:")} confirm`],ce=(n,r)=>n.includes(`
132
132
  `)?n.split(`
133
133
  `).map((t)=>r(t)).join(`
134
- `):r(n),nh=(n)=>{let r=(e,i)=>{if(e===void 0)return"";let o=e.label??String(e.value);switch(i){case"disabled":return`${k("gray",ce)} ${ue(o,(s)=>k("gray",s))}${e.hint?` ${k("dim",`(${e.hint??"disabled"})`)}`:""}`;case"selected":return`${ue(o,(s)=>k("dim",s))}`;case"active":return`${k("green",Ri)} ${o}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`;case"cancelled":return`${ue(o,(s)=>k(["strikethrough","dim"],s))}`;default:return`${k("dim",ce)} ${ue(o,(s)=>k("dim",s))}`}},t=n.showInstructions??!0;return new Wc({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=`${Cc(this.state)} `,s=$r(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
134
+ `):r(n),nh=(n)=>{let r=(e,i)=>{if(e===void 0)return"";let o=e.label??String(e.value);switch(i){case"disabled":return`${k("gray",he)} ${ce(o,(s)=>k("gray",s))}${e.hint?` ${k("dim",`(${e.hint??"disabled"})`)}`:""}`;case"selected":return`${ce(o,(s)=>k("dim",s))}`;case"active":return`${k("green",Ri)} ${o}${e.hint?` ${k("dim",`(${e.hint})`)}`:""}`;case"cancelled":return`${ce(o,(s)=>k(["strikethrough","dim"],s))}`;default:return`${k("dim",he)} ${ce(o,(s)=>k("dim",s))}`}},t=n.showInstructions??!0;return new Wc({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let e=n.withGuide??yn.withGuide,i=`${Oi(this.state)} `,o=`${Cc(this.state)} `,s=br(n.output,n.message,o,i),u=`${e?`${k("gray",cn)}
135
135
  `:""}${s}
136
- `;switch(this.state){case"submit":{let c=e?`${k("gray",cn)} `:"",h=$r(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=e?`${k("gray",cn)} `:"",h=$r(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${e?`
136
+ `;switch(this.state){case"submit":{let c=e?`${k("gray",cn)} `:"",h=br(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=e?`${k("gray",cn)} `:"",h=br(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${e?`
137
137
  ${k("gray",cn)}`:""}`}default:{let c=e?`${k("cyan",cn)} `:"",h=u.split(`
138
138
  `).length,f=t?Tc(bd,e):e?[k("cyan",pr)]:[],g=f.join(`
139
139
  `),l=f.length+1;return`${u}${c}${yi({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+l,style:($,a)=>r($,$.disabled?"disabled":a?"active":"inactive")}).join(`
140
140
  ${c}`)}
141
141
  ${g}
142
- `}}}}).prompt()};var Ba=`${k("gray",cn)} `;import{existsSync as Nd}from"node:fs";import{openSync as wd,writeSync as Ed}from"node:fs";import{ReadStream as kd}from"node:tty";var th=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function ge(n){let r=n.ansi.map((t,e)=>`;${e};${t}`).join("");return[`\x1B]11;${n.background}\x1B\\`,`\x1B]10;${n.foreground}\x1B\\`,`\x1B]12;${n.cursor}\x1B\\`,`\x1B]17;${n.selection}\x1B\\`,`\x1B]4${r}\x1B\\`].join("")}function eh(n){let r=new Map;for(let t of n.split("\x1B")){let e=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=e??[];if(i&&o)r.set(i,o)}return r}function ih(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function oh(){let n,r;try{n=wd("/dev/tty","r+"),r=new kd(n),r.setRawMode(!0)}catch{return new Map}try{Ed(n,th.map((e)=>`\x1B]${e};?\x1B\\`).join(""));let t="";return await new Promise((e)=>{let i=setTimeout(e,120);r.on("data",(o)=>{if(t+=o.toString(),eh(t).size>=th.length)clearTimeout(i),e()})}),eh(t)}finally{r.setRawMode(!1),r.destroy()}}function zr(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function sh(n,r){return`\x1B[48;2;${zr(r)}m ${n} \x1B[0m`}function Li(n,r){return`\x1B[48;2;${zr(n)};38;2;${zr(r)}m ● \x1B[0m`}function uh(n){return`\x1B[38;2;${zr(n)}m`}function Qi(n,r){return`\x1B[48;2;${zr(r)}m${n.map((t)=>`\x1B[38;2;${zr(t)}m▄`).join("")} \x1B[0m`}function le(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((e)=>e.toLowerCase().includes(t))}function hh(n,r,t){let e=t.trim(),i=[],o=new Set;for(let s of n){if(s.default||o.has(s.group))continue;o.add(s.group);let u=n.filter((f)=>!f.default&&f.group===s.group),c=e?u.filter((f)=>le(f,e)):u;if(e&&c.length===0)continue;let h=e.length>0||r.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function Md(n,r){let t=r.trim(),e=new Set(n.filter((i)=>!i.default&&(t===""||le(i,t))).map((i)=>i.group));return hh(n,new Set,"").filter((i)=>i.kind==="group"&&e.has(i.name))}function Fd(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",Ar="\x1B[2m",Id="\x1B[1m",ch="\x1B[1;7m",vd="\x1B[36m",pd="\x1B[33m";function fh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Zi extends tr{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(n){super({render:()=>this.draw(),input:n.input,output:n.output,validate:n.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=n.entries,this.scope=n.scope??"palette",this.picked=new Set(n.installed??[]),this.named=n.entries.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.maxItems=n.maxItems??12,this.color=n.color??!0,this.fx=n.fx??"typewriter",this.onFocus=n.onFocus,this.rollExample();let r=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);r.unref?.(),this.once("finalize",()=>{clearInterval(r),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,e)=>{if(e?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(n){return n==="\t"||n===" "}members(n){let r=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((t)=>t.group===n&&(r===""||le(t,r)))}everyone(n){return n.flatMap((r)=>r.kind==="group"?this.members(r.name):[])}pick(n){let r=n?.kind==="palette"?[n.entry.name]:n?.kind==="group"?this.members(n.name).map((e)=>e.name):n?.kind==="all"?this.everyone(this.rows).map((e)=>e.name):[];if(r.length===0)return;let t=r.some((e)=>!this.picked.has(e));for(let e of r)if(t)this.picked.add(e);else this.picked.delete(e)}pickedIn(n){return this.members(n).filter((r)=>this.picked.has(r.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((n)=>this.members(n).every((r)=>this.picked.has(r.name))).length}rollExample(){let n=this.named[Math.floor(Math.random()*this.named.length)],r=this.series[Math.floor(Math.random()*this.series.length)];if(!n||!r){this.example="";return}let t=`${n.name} | ${r}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let n=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,n)}▏`;let r=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(e)=>!/[a-z0-9]/i.test(e):(e)=>e===" ";return[...this.example].map((e,i)=>i+(i*7+this.fxSeed)%3<n||t(e)?e:r[Math.floor(Math.random()*r.length)]??e).join("")}sync(){let n=this.rows[this.cursor],r=n?.kind==="palette"?n.entry:n?.kind==="group"&&this.scope==="series"?n.lead:void 0;if(r&&r.name!==this.lastFocused)this.lastFocused=r.name,this.onFocus?.(r)}rebuild(n){let r=this.rows[this.cursor],t=this.scope==="series"?Md(this.entries,this.userInput):hh(this.entries,this.expanded,this.userInput),e=t.length>0?Fd(t)+1:0;if(this.rows=t.length>0?[{kind:"all",count:this.allCount(t)},...t]:[],n==="first")this.cursor=e;else if(n==="keep"){let i=r?.kind==="palette"?r.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?e:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(n){return this.scope==="series"?n.length:this.everyone(n).length}move(n){let r=this.cursor+n;if(r>=0&&r<this.rows.length)this.cursor=r;this.sync()}toggle(n){if(this.expanded.has(n))this.expanded.delete(n);else this.expanded.add(n);this.rebuild("clamp")}fold(n){if(this.userInput||this.scope==="series")return;let r=this.rows[this.cursor];if(r?.kind==="group"){if(n!==r.expanded)this.toggle(r.name)}else if(r?.kind==="palette"&&!n&&!r.entry.default){let t=r.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((e)=>e.kind==="group"&&e.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let t=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${t}${o}select all ${this.color?`${Ar}${s}${Bn}`:s}`}if(n.kind==="group"&&this.scope==="series"){let o=this.pickedIn(n.name)===n.count?"● ":"○ ",s=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${t}${o}${s} ${u}`;let c=n.lead;return`${t}${o}${s} ${Li(c.background,c.cursor)}${Qi(c.ansi.slice(1,7),c.background)} ${Ar}${u}${Bn}`}if(n.kind==="group"){let o=n.expanded?"▾":"▸",s=this.rows[this.cursor],u=s?.kind==="palette"&&s.entry.group===n.name?s.entry:void 0,c=this.color?r?`${ch} ${n.name} ${Bn}`:u?`${ch}${uh(u.cursor)} ${n.name} ${Bn}`:` ${Id}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?sh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${Ar}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${Ar}${n.native}${Bn}`:` ${n.native}`:"";return`${o}${c}${h}${g}${l}`}let e=n.entry,i=this.picked.has(e.name)?"● ":"○ ";if(!this.color)return` ${t}${i}${e.name.padEnd(13)} ● · ${e.ansiSource}`;return` ${t}${i}${e.name.padEnd(13)} ${Li(e.background,e.cursor)}${Qi(e.ansi.slice(1,7),e.background)} ${Ar}${e.ansiSource}${Bn}`}draw(){let n=(w)=>this.color?`${Ar}${w}${Bn}`:w,r=(w)=>this.color?`${vd}${w}${Bn}`:w,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${t} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${t} · cancelled`)}`;let e=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((w)=>w.kind==="group").length:e?this.named.filter((w)=>le(w,e)).length:i,s=`${r("◆")} ${t} ${n(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${r("│")} ${this.userInput?`⌕ ${this.userInput}_`:n(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),h=c.length>0?c.map((w,F)=>`${r("│")} ${this.renderRow(w,this.top+F===this.cursor)}`):[`${r("│")} ${n(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(r("│"));let f=this.rows.length-this.top-c.length,g=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),l=this.scope==="series"?"":" · ←→ fold",$=this.scope==="series"?"continue":"install",a=this.state==="error"?`${r("└")} ${this.color?`${pd}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${$} · esc cancel`)}`;return[s,u,...h,g,a].join(`
143
- `)}}function Ui(n,r,t,e){let i=Ur(),o=Boolean(qr(t))!==Boolean(qr(e)),s=o?kt(e,i):e;if(It(n,r,s),Ft(n,s),o)Mt(s,i)}function qi(n){console.log(`
144
- ${n} palettes installed — open a new tab, or reload your terminal config`)}function gh(n){let r=_n(),t=Qn(r),e=sr(r),i=n.filter((u)=>e.palettes.includes(u)),o=n.filter((u)=>!e.palettes.includes(u));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...e,palettes:[...e.palettes,...o]};Ui(r,t,e,s);for(let u of o)console.log(` + ${u}`);qi(s.palettes.length)}function lh(n){let r=_n(),t=Qn(r),e=sr(r),i=n.filter((s)=>e.palettes.includes(s));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...e,palettes:e.palettes.filter((s)=>!i.includes(s))};Ui(r,t,e,o),gi(r,t,e.terminals,i);for(let s of i)console.log(` - ${s}`);qi(o.palettes.length)}function mh(n){let r=_n(),t=Qn(r),e=sr(r);if(!e.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...o}=e,s=Ur(),u=kt({...o,startup:n},s);It(r,t,u),Ft(r,u);let c=Mt(u,s);console.log(Hd(n,u.terminals,c&&s.running()).join(`
145
- `))}function Hd(n,r,t){let e=r.filter((o)=>o!=="iterm2"),i=e.length>0?[`default ${n} · ${e.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(t?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${n} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function dh(n){let r=_n(),t=Qn(r),e=new Set(sr(r).palettes),i=Gr(t.palettes),o=ut(n?Ru(i,n):i),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${e.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
146
- ${u} palettes — ${o.filter((c)=>e.has(c.name)).length} installed`)}async function $h(){let n=_n(),r=Nd(Tt(n))?Qn(n).palettes.length:0,t=await Ju(ju);_t(n,t);let e=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${e>0?` (+${e})`:""}`)}async function Wi(n,r,t,e=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:ut(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await oh():new Map,u=new Zi({entries:i,scope:t,installed:r,required:e,color:!process.env.NO_COLOR,fx:fh(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(ge(h)):void 0}),c=await u.prompt();if(process.stdout.write(ih(s)),Pr(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function ah(){let n=_n(),r=Qn(n),t=sr(n),e=await Wi(r,t.palettes,"palette");if(!e){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!e.includes(u)),o=e.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:e};Ui(n,r,t,s),gi(n,r,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);qi(s.palettes.length)}function Eh(n,r,t){for(let e of Gd(r))n.push({from:wn(r,e),to:wn(t,e)})}function Ih(n){return JSON.parse(Nt(wn(n,"dist","manifest.json"),"utf8"))}function kh(n,r){let t=wn(r.root,"dist"),e=wn(r.configHome,"ttheme"),i=[{from:wn(r.root,"bin","ttheme.js"),to:wn(e,"ttheme.js")},{from:wn(r.root,"shell","ttheme.zsh"),to:wn(e,"ttheme.zsh")},{from:wn(r.root,"shell","launch-tab.zsh"),to:wn(e,"launch-tab.zsh"),executable:!0},{from:wn(t,"ghostty","ttheme.conf"),to:wn(e,"ttheme.conf")}];Eh(i,wn(r.root,"shell","adapters"),wn(e,"adapters"));let o=[{file:wn(r.zdotdir,".zshrc"),block:vo(e)}],s=wn(e,"config.zsh"),u=No(hr(s)?Nt(s,"utf8"):""),c={file:s,content:n.wear?Lt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))Eh(i,wn(r.root,"ghostty","shaders"),wn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=wn(r.configHome,"alacritty","alacritty.toml");if(hr(g)&&!Nt(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}h.push("wezterm: import the palettes you install from the release archive");let f={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{}};return{home:r.home,copies:i,edits:o,settings:c,catalog:Ih(r.root),installed:f,notes:h}}function Kd(n){try{return sr(n).itermBase}catch{return}}function Mh(n,r=Ur()){for(let o of n.copies)if(Xi(pt(o.to),{recursive:!0}),bh(o.to,{force:!0}),bh(`${o.to}.zwc`,{force:!0}),jd(o.from,o.to),o.executable)Sd(o.to,493);Xi(pt(n.settings.file),{recursive:!0}),wh(n.settings.file,n.settings.content);let t=pt(pt(n.settings.file)),e=Kd(t),i=kt(e?{...n.installed,itermBase:e}:n.installed,r);_t(t,n.catalog),Ft(t,i),It(t,n.catalog,i,n.home);for(let o of n.edits){Xi(pt(o.file),{recursive:!0});let s=hr(o.file)?Nt(o.file,"utf8"):"";wh(o.file,Ot(s,o.block))}return Mt(i,r)}function Vi(n){if(Pr(n))he("nothing changed"),process.exit(1);return n}function vh(){return yt.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function Rd(n,r){return n==="iterm2"?hr(wn(r.home,"Library","Application Support","iTerm2")):hr(wn(r.configHome,n))}async function yd(n,r){return Vi(await Bc({message:"wire which terminals?",options:vh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Od(n,r){if(n==="keep")return"leave the terminal colors as they are";return n==="rotate"?`paint every new tab with the next palette, this tab with ${r} now`:`paint every tab with ${r}, this one now`}async function Ld(n){return Vi(await nh({message:"how should the terminal wear them?",options:[{value:"default",label:"default",hint:`every tab wears ${n}`},{value:"rotate",label:"rotate",hint:"every new tab wears the next palette"},{value:"keep",label:"keep",hint:"leave my terminal colors alone"}],initialValue:"default"}))}function Fh(n){let r=[...n.copies.filter((t)=>!hr(t.to)).map((t)=>t.to),...hr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!Nt(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(r.length>0)throw Error(`init left gaps:
142
+ `}}}}).prompt()};var Ba=`${k("gray",cn)} `;import{existsSync as pd}from"node:fs";import{openSync as wd,writeSync as Ed}from"node:fs";import{ReadStream as kd}from"node:tty";var th=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function le(n){let r=n.ansi.map((t,e)=>`;${e};${t}`).join("");return[`\x1B]11;${n.background}\x1B\\`,`\x1B]10;${n.foreground}\x1B\\`,`\x1B]12;${n.cursor}\x1B\\`,`\x1B]17;${n.selection}\x1B\\`,`\x1B]4${r}\x1B\\`].join("")}function eh(n){let r=new Map;for(let t of n.split("\x1B")){let e=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=e??[];if(i&&o)r.set(i,o)}return r}function ih(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function oh(){let n,r;try{n=wd("/dev/tty","r+"),r=new kd(n),r.setRawMode(!0)}catch{return new Map}try{Ed(n,th.map((e)=>`\x1B]${e};?\x1B\\`).join(""));let t="";return await new Promise((e)=>{let i=setTimeout(e,120);r.on("data",(o)=>{if(t+=o.toString(),eh(t).size>=th.length)clearTimeout(i),e()})}),eh(t)}finally{r.setRawMode(!1),r.destroy()}}function Ar(n){let r=n.replace("#","");return[r.slice(0,2),r.slice(2,4),r.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function sh(n,r){return`\x1B[48;2;${Ar(r)}m ${n} \x1B[0m`}function Li(n,r){return`\x1B[48;2;${Ar(n)};38;2;${Ar(r)}m ● \x1B[0m`}function uh(n){return`\x1B[38;2;${Ar(n)}m`}function Qi(n,r){return`\x1B[48;2;${Ar(r)}m${n.map((t)=>`\x1B[38;2;${Ar(t)}m▄`).join("")} \x1B[0m`}function me(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((e)=>e.toLowerCase().includes(t))}function hh(n,r,t){let e=t.trim(),i=[],o=new Set;for(let s of n){if(s.default||o.has(s.group))continue;o.add(s.group);let u=n.filter((f)=>!f.default&&f.group===s.group),c=e?u.filter((f)=>me(f,e)):u;if(e&&c.length===0)continue;let h=e.length>0||r.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((f)=>f.lead)??s,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function Md(n,r){let t=r.trim(),e=new Set(n.filter((i)=>!i.default&&(t===""||me(i,t))).map((i)=>i.group));return hh(n,new Set,"").filter((i)=>i.kind==="group"&&e.has(i.name))}function Fd(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",Cr="\x1B[2m",Id="\x1B[1m",ch="\x1B[1;7m",vd="\x1B[36m",Nd="\x1B[33m";function fh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Zi extends tr{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(n){super({render:()=>this.draw(),input:n.input,output:n.output,validate:n.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=n.entries,this.scope=n.scope??"palette",this.picked=new Set(n.installed??[]),this.named=n.entries.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.maxItems=n.maxItems??12,this.color=n.color??!0,this.fx=n.fx??"typewriter",this.onFocus=n.onFocus,this.rollExample();let r=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);r.unref?.(),this.once("finalize",()=>{clearInterval(r),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(t)=>{if(t==="up")this.move(-1);else if(t==="down")this.move(1);else if(t==="left")this.fold(!1);else if(t==="right")this.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.rebuild("keep")}),this.on("key",(t,e)=>{if(e?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(n){return n==="\t"||n===" "}members(n){let r=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((t)=>t.group===n&&(r===""||me(t,r)))}everyone(n){return n.flatMap((r)=>r.kind==="group"?this.members(r.name):[])}pick(n){let r=n?.kind==="palette"?[n.entry.name]:n?.kind==="group"?this.members(n.name).map((e)=>e.name):n?.kind==="all"?this.everyone(this.rows).map((e)=>e.name):[];if(r.length===0)return;let t=r.some((e)=>!this.picked.has(e));for(let e of r)if(t)this.picked.add(e);else this.picked.delete(e)}pickedIn(n){return this.members(n).filter((r)=>this.picked.has(r.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((n)=>this.members(n).every((r)=>this.picked.has(r.name))).length}rollExample(){let n=this.named[Math.floor(Math.random()*this.named.length)],r=this.series[Math.floor(Math.random()*this.series.length)];if(!n||!r){this.example="";return}let t=`${n.name} | ${r}`;this.example=t.length>30?`${t.slice(0,29)}…`:t,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let n=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,n)}▏`;let r=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(e)=>!/[a-z0-9]/i.test(e):(e)=>e===" ";return[...this.example].map((e,i)=>i+(i*7+this.fxSeed)%3<n||t(e)?e:r[Math.floor(Math.random()*r.length)]??e).join("")}sync(){let n=this.rows[this.cursor],r=n?.kind==="palette"?n.entry:n?.kind==="group"&&this.scope==="series"?n.lead:void 0;if(r&&r.name!==this.lastFocused)this.lastFocused=r.name,this.onFocus?.(r)}rebuild(n){let r=this.rows[this.cursor],t=this.scope==="series"?Md(this.entries,this.userInput):hh(this.entries,this.expanded,this.userInput),e=t.length>0?Fd(t)+1:0;if(this.rows=t.length>0?[{kind:"all",count:this.allCount(t)},...t]:[],n==="first")this.cursor=e;else if(n==="keep"){let i=r?.kind==="palette"?r.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?e:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(n){return this.scope==="series"?n.length:this.everyone(n).length}move(n){let r=this.cursor+n;if(r>=0&&r<this.rows.length)this.cursor=r;this.sync()}toggle(n){if(this.expanded.has(n))this.expanded.delete(n);else this.expanded.add(n);this.rebuild("clamp")}fold(n){if(this.userInput||this.scope==="series")return;let r=this.rows[this.cursor];if(r?.kind==="group"){if(n!==r.expanded)this.toggle(r.name)}else if(r?.kind==="palette"&&!n&&!r.entry.default){let t=r.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((e)=>e.kind==="group"&&e.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(n,r){let t=r?"▶ ":" ";if(n.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${n.count})`;return`${t}${o}select all ${this.color?`${Cr}${s}${Bn}`:s}`}if(n.kind==="group"&&this.scope==="series"){let o=this.pickedIn(n.name)===n.count?"● ":"○ ",s=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${t}${o}${s} ${u}`;let c=n.lead;return`${t}${o}${s} ${Li(c.background,c.cursor)}${Qi(c.ansi.slice(1,7),c.background)} ${Cr}${u}${Bn}`}if(n.kind==="group"){let o=n.expanded?"▾":"▸",s=this.rows[this.cursor],u=s?.kind==="palette"&&s.entry.group===n.name?s.entry:void 0,c=this.color?r?`${ch} ${n.name} ${Bn}`:u?`${ch}${uh(u.cursor)} ${n.name} ${Bn}`:` ${Id}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?sh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${Cr}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${Cr}${n.native}${Bn}`:` ${n.native}`:"";return`${o}${c}${h}${g}${l}`}let e=n.entry,i=this.picked.has(e.name)?"● ":"○ ";if(!this.color)return` ${t}${i}${e.name.padEnd(13)} ● · ${e.ansiSource}`;return` ${t}${i}${e.name.padEnd(13)} ${Li(e.background,e.cursor)}${Qi(e.ansi.slice(1,7),e.background)} ${Cr}${e.ansiSource}${Bn}`}draw(){let n=(w)=>this.color?`${Cr}${w}${Bn}`:w,r=(w)=>this.color?`${vd}${w}${Bn}`:w,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${n("◇")} ${t} ${n(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${n(`◇ ${t} · cancelled`)}`;let e=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((w)=>w.kind==="group").length:e?this.named.filter((w)=>me(w,e)).length:i,s=`${r("◆")} ${t} ${n(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${r("│")} ${this.userInput?`⌕ ${this.userInput}_`:n(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let c=this.rows.slice(this.top,this.top+this.maxItems),h=c.length>0?c.map((w,F)=>`${r("│")} ${this.renderRow(w,this.top+F===this.cursor)}`):[`${r("│")} ${n(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(r("│"));let f=this.rows.length-this.top-c.length,g=f>0?`${r("│")} ${n(`↓ ${f} more`)}`:r("│"),l=this.scope==="series"?"":" · ←→ fold",$=this.scope==="series"?"continue":"install",a=this.state==="error"?`${r("└")} ${this.color?`${Nd}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${$} · esc cancel`)}`;return[s,u,...h,g,a].join(`
143
+ `)}}function Ui(n,r,t,e){let i=qr(),o=Boolean(Wr(t))!==Boolean(Wr(e)),s=o?kt(e,i):e;if(It(n,r,s),Ft(n,s),o)Mt(s,i)}function qi(n){console.log(`
144
+ ${n} palettes installed — open a new tab, or reload your terminal config`)}function gh(n){let r=_n(),t=Qn(r),e=ur(r),i=n.filter((u)=>e.palettes.includes(u)),o=n.filter((u)=>!e.palettes.includes(u));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...e,palettes:[...e.palettes,...o]};Ui(r,t,e,s);for(let u of o)console.log(` + ${u}`);qi(s.palettes.length)}function lh(n){let r=_n(),t=Qn(r),e=ur(r),i=n.filter((s)=>e.palettes.includes(s));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let o={...e,palettes:e.palettes.filter((s)=>!i.includes(s))};Ui(r,t,e,o),gi(r,t,e.terminals,i);for(let s of i)console.log(` - ${s}`);qi(o.palettes.length)}function mh(n){let r=_n(),t=Qn(r),e=ur(r);if(!e.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...o}=e,s=qr(),u=kt({...o,startup:n},s);It(r,t,u),Ft(r,u);let c=Mt(u,s);console.log(Hd(n,u.terminals,c&&s.running()).join(`
145
+ `))}function Hd(n,r,t){let e=r.filter((o)=>o!=="iterm2"),i=e.length>0?[`default ${n} · ${e.join(", ")} open new tabs with it once their config reloads`]:[];if(r.includes("iterm2"))i.push(t?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${n} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function dh(n){let r=_n(),t=Qn(r),e=new Set(ur(r).palettes),i=Jr(t.palettes),o=ut(n?Ru(i,n):i),s=Math.max(...o.map((c)=>c.name.length),0);for(let c of o)console.log(` ${e.has(c.name)?"●":"○"} ${c.name.padEnd(s)} ${c.group}`);let u=n?`${o.length} of ${i.length}`:`${i.length}`;console.log(`
146
+ ${u} palettes — ${o.filter((c)=>e.has(c.name)).length} installed`)}async function $h(){let n=_n(),r=pd(_t(n))?Qn(n).palettes.length:0,t=await Ju(ju);Bt(n,t);let e=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${e>0?` (+${e})`:""}`)}async function Wi(n,r,t,e=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:ut(n.palettes),o=process.stdout.isTTY===!0&&!process.env.NO_COLOR,s=o?await oh():new Map,u=new Zi({entries:i,scope:t,installed:r,required:e,color:!process.env.NO_COLOR,fx:fh(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(le(h)):void 0}),c=await u.prompt();if(process.stdout.write(ih(s)),zr(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function ah(){let n=_n(),r=Qn(n),t=ur(n),e=await Wi(r,t.palettes,"palette");if(!e){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!e.includes(u)),o=e.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:e};Ui(n,r,t,s),gi(n,r,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);qi(s.palettes.length)}function Eh(n,r,t){for(let e of Gd(r))n.push({from:wn(r,e),to:wn(t,e)})}function Ih(n){return JSON.parse(pt(wn(n,"dist","manifest.json"),"utf8"))}function kh(n,r){let t=wn(r.root,"dist"),e=wn(r.configHome,"ttheme"),i=[{from:wn(r.root,"bin","ttheme.js"),to:wn(e,"ttheme.js")},{from:wn(r.root,"shell","ttheme.zsh"),to:wn(e,"ttheme.zsh")},{from:wn(r.root,"shell","launch-tab.zsh"),to:wn(e,"launch-tab.zsh"),executable:!0},{from:wn(t,"ghostty","ttheme.conf"),to:wn(e,"ttheme.conf")}];Eh(i,wn(r.root,"shell","adapters"),wn(e,"adapters"));let o=[{file:wn(r.zdotdir,".zshrc"),block:vo(e)}],s=wn(e,"config.zsh"),u=po(fr(s)?pt(s,"utf8"):""),c={file:s,content:n.wear?Qt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))Eh(i,wn(r.root,"ghostty","shaders"),wn(r.configHome,"ghostty","shaders"));if(n.terminals.includes("alacritty")){let g=wn(r.configHome,"alacritty","alacritty.toml");if(fr(g)&&!pt(g,"utf8").includes("# ttheme begin"))h.push("alacritty.toml already exists — ttheme left it alone; add its themes/ import yourself")}h.push("wezterm: import the palettes you install from the release archive");let f={terminals:n.terminals,palettes:n.palettes,...n.wear==="keep"?{keepTheme:!0}:{}};return{home:r.home,copies:i,edits:o,settings:c,catalog:Ih(r.root),installed:f,notes:h}}function Kd(n){try{return ur(n).itermBase}catch{return}}function Mh(n,r=qr()){for(let o of n.copies)if(Xi(Nt(o.to),{recursive:!0}),bh(o.to,{force:!0}),bh(`${o.to}.zwc`,{force:!0}),jd(o.from,o.to),o.executable)Sd(o.to,493);Xi(Nt(n.settings.file),{recursive:!0}),wh(n.settings.file,n.settings.content);let t=Nt(Nt(n.settings.file)),e=Kd(t),i=kt(e?{...n.installed,itermBase:e}:n.installed,r);Bt(t,n.catalog),Ft(t,i),It(t,n.catalog,i,n.home);for(let o of n.edits){Xi(Nt(o.file),{recursive:!0});let s=fr(o.file)?pt(o.file,"utf8"):"";wh(o.file,Lt(s,o.block))}return Mt(i,r)}function Vi(n){if(zr(n))fe("nothing changed"),process.exit(1);return n}function vh(){return Ot.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function Rd(n,r){return n==="iterm2"?fr(wn(r.home,"Library","Application Support","iTerm2")):fr(wn(r.configHome,n))}async function yd(n,r){return Vi(await Bc({message:"wire which terminals?",options:vh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Od(n,r){if(n==="keep")return"leave the terminal colors as they are";return n==="rotate"?`paint every new tab with the next palette, this tab with ${r} now`:`paint every tab with ${r}, this one now`}async function Ld(n){return Vi(await nh({message:"how should the terminal wear them?",options:[{value:"default",label:"default",hint:`every tab wears ${n}`},{value:"rotate",label:"rotate",hint:"every new tab wears the next palette"},{value:"keep",label:"keep",hint:"leave my terminal colors alone"}],initialValue:"default"}))}function Fh(n){let r=[...n.copies.filter((t)=>!fr(t.to)).map((t)=>t.to),...fr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!pt(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(r.length>0)throw Error(`init left gaps:
147
147
  ${r.join(`
148
- `)}`)}function ph(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function Qd(n,r){let t=n.palettes.find((i)=>i.name===Wr(r)),e=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!e)return!1;return process.stdout.write(ge(t)),!0}function Zd(n,r,t){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${t?" — this tab wears it already":""}`,n==="rotate"?"new tabs rotate through the palettes — change with `ttheme config`":`new tabs all wear ${r} — change with \`ttheme config\``]}function Ud(n,r,t,e,i){let o=ph(n.catalog,r.palettes);fe([`${o.join(", ")} (${r.palettes.length})`,...Zd(t,Wr(n.installed),e)].join(`
149
- `),`installed ${r.palettes.length} palettes`);let s=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))s.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))s.push("new kitty window picks up its config");if(r.terminals.includes("iterm2"))s.push(...qd(t==="default"?Wr(n.installed):void 0,i));fe([...s,...n.notes].join(`
148
+ `)}`)}function Nh(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function Qd(n,r){let t=n.palettes.find((i)=>i.name===Xr(r)),e=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!e)return!1;return process.stdout.write(le(t)),!0}function Zd(n,r,t){if(n==="keep")return["terminal colors left alone — paint a tab with `ttheme <palette>`"," `ttheme default <palette>` sets the terminal default"];return[`default ${r}${t?" — this tab wears it already":""}`,n==="rotate"?"new tabs rotate through the palettes — change with `ttheme config`":`new tabs all wear ${r} — change with \`ttheme config\``]}function Ud(n,r,t,e,i){let o=Nh(n.catalog,r.palettes);ge([`${o.join(", ")} (${r.palettes.length})`,...Zd(t,Xr(n.installed),e)].join(`
149
+ `),`installed ${r.palettes.length} palettes`);let s=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))s.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))s.push("new kitty window picks up its config");if(r.terminals.includes("iterm2"))s.push(...qd(t==="default"?Xr(n.installed):void 0,i));ge([...s,...n.notes].join(`
150
150
  `),"next"),Dc("done")}function qd(n,r){let t=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(n)t.push(r?`restart iterm2 new tabs open on "ttheme · default", which wears ${n}`:`iterm2 default "ttheme · default" wears ${n} and follows \`ttheme default\``);return t}function Wd(n,r){let t=[`placed ${n.copies.length} files`,`settings in ${n.settings.file} — edit later with \`ttheme config\``,...n.edits.map((e)=>`wired ${e.file}`)];if(r.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(r.terminals.includes("kitty"))t.push("open a new kitty window to pick up its config");if(r.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...n.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
151
- `))}async function Nh(n={}){let r=wn(import.meta.dirname,"..");if(!hr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!hr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Zt()}let t=Jd(),e=process.env.XDG_CONFIG_HOME??wn(t,".config"),i=process.env.ZDOTDIR??t,o={root:r,home:t,configHome:e,zdotdir:i},s=Fo(process.env),u=vh().filter((v)=>v===s||Rd(v,o));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(u.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty or iterm2");let v={terminals:u,palettes:[]},j=kh(v,o);Mh(j),Fh(j),Wd(j,v);return}xc("ttheme init");let h=await yd(s,u),f=await Wi(Ih(r),[],"series",!0);if(!f)he("nothing changed"),process.exit(1);let g=Wr({terminals:h,palettes:f}),l=await Ld(g),$={terminals:h,palettes:f,wear:l},a=kh($,o);if(fe([`install ${f.length} palettes — ${ph(a.catalog,f).join(", ")}`,`copy ${a.copies.length} files under ${e}`,`write ${a.settings.file}`,...a.edits.map((v)=>`edit ${v.file}`),Od(l,g),...h.includes("iterm2")&&l!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
152
- `),`wiring ${h.join(", ")}`),!Vi(await _c({message:"apply these changes?"})))he("nothing changed"),process.exit(1);let w=Ur(),F=Mh(a,w);Fh(a),Ud(a,$,l,l!=="keep"&&Qd(a.catalog,a.installed),F&&w.running())}var Gh=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ko,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Zt({only:r})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(n,{yes:r})=>Nh({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>ah()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>dh(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>gh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>lh(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>mh(n)},{name:"find",args:["<palette>"],about:"pick a safebooru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>ac(n)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([n,r])=>bc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>$h()}];class Nr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function Hh(n){let r=Gh.find((t)=>t.name===n);if(!r)throw new Nr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Vd(n,r){let t={help:{type:"boolean",short:"h"}};for(let[e,{type:i,multiple:o}]of Object.entries(n.flags??{}))t[e]={type:i,multiple:o===!0};try{return Xd({args:r,options:t,allowPositionals:!0})}catch(e){let[i=""]=(e instanceof Error?e.message:String(e)).split(". ");throw new Nr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function Yd(n){let[r,...t]=n;if(r===void 0)return{kind:"help",code:1};if(r==="-h"||r==="--help")return{kind:"help",code:0};if(r==="-V"||r==="--version")return{kind:"version"};if(r==="help")return t[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:Hh(t[0]),code:0};let e=Hh(r),i=Vd(e,t);if(i.values.help)return{kind:"help",verb:e,code:0};for(let[f,{choices:g}]of Object.entries(e.flags??{}))for(let l of[i.values[f]??[]].flat())if(g&&!g.includes(String(l)))throw new Nr(`--${f} takes ${g.join(", ")} — not ${l}`,e);let o=i.positionals,s=e.args.filter((f)=>f.startsWith("<")).length,u=e.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:e.args.length;if(o.length<s)throw new Nr(`missing ${e.args[o.length]}`,e);if(o.length>u)throw new Nr(`too many arguments: ${o.slice(u).join(" ")}`,e);let{help:c,...h}=i.values;return{kind:"run",verb:e,args:o,flags:h}}function Sh(n){let r=Object.entries(n.flags??{}).map(([t,{value:e}])=>`[--${t}${e?` ${e}`:""}]`);return[n.name,...r,...n.args].join(" ")}function jh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,e])=>` ${t.padEnd(r)} ${e}`)}function Yi(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:e,about:i}])=>[`--${t}${e?` ${e}`:""}`,i]);return[`Usage: ttheme ${Sh(n)}`,"",n.about,...r.length>0?["","Options:",...jh(r)]:[]].join(`
151
+ `))}async function ph(n={}){let r=wn(import.meta.dirname,"..");if(!fr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!fr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Ut()}let t=Jd(),e=process.env.XDG_CONFIG_HOME??wn(t,".config"),i=process.env.ZDOTDIR??t,o={root:r,home:t,configHome:e,zdotdir:i},s=Fo(process.env),u=vh().filter((v)=>v===s||Rd(v,o));if(!(!n.yes&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0)){if(u.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty or iterm2");let v={terminals:u,palettes:[]},j=kh(v,o);Mh(j),Fh(j),Wd(j,v);return}xc("ttheme init");let h=await yd(s,u),f=await Wi(Ih(r),[],"series",!0);if(!f)fe("nothing changed"),process.exit(1);let g=Xr({terminals:h,palettes:f}),l=await Ld(g),$={terminals:h,palettes:f,wear:l},a=kh($,o);if(ge([`install ${f.length} palettes — ${Nh(a.catalog,f).join(", ")}`,`copy ${a.copies.length} files under ${e}`,`write ${a.settings.file}`,...a.edits.map((v)=>`edit ${v.file}`),Od(l,g),...h.includes("iterm2")&&l!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
152
+ `),`wiring ${h.join(", ")}`),!Vi(await _c({message:"apply these changes?"})))fe("nothing changed"),process.exit(1);let w=qr(),F=Mh(a,w);Fh(a),Ud(a,$,l,l!=="keep"&&Qd(a.catalog,a.installed),F&&w.running())}var Gh=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ko,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Ut({only:r})},{name:"init",args:[],about:"install the palettes and wire your terminal configs",flags:{yes:{type:"boolean",about:"accept every default without prompting"}},run:(n,{yes:r})=>ph({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>ah()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>dh(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>gh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>lh(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>mh(n)},{name:"find",args:["<palette>"],about:"pick a safebooru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>ac(n)},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",hidden:!0,run:([n,r])=>bc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>$h()}];class Hr extends Error{verb;constructor(n,r){super(n);this.verb=r}}function Hh(n){let r=Gh.find((t)=>t.name===n);if(!r)throw new Hr(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Vd(n,r){let t={help:{type:"boolean",short:"h"}};for(let[e,{type:i,multiple:o}]of Object.entries(n.flags??{}))t[e]={type:i,multiple:o===!0};try{return Xd({args:r,options:t,allowPositionals:!0})}catch(e){let[i=""]=(e instanceof Error?e.message:String(e)).split(". ");throw new Hr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function Yd(n){let[r,...t]=n;if(r===void 0)return{kind:"help",code:1};if(r==="-h"||r==="--help")return{kind:"help",code:0};if(r==="-V"||r==="--version")return{kind:"version"};if(r==="help")return t[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:Hh(t[0]),code:0};let e=Hh(r),i=Vd(e,t);if(i.values.help)return{kind:"help",verb:e,code:0};for(let[f,{choices:g}]of Object.entries(e.flags??{}))for(let l of[i.values[f]??[]].flat())if(g&&!g.includes(String(l)))throw new Hr(`--${f} takes ${g.join(", ")} — not ${l}`,e);let o=i.positionals,s=e.args.filter((f)=>f.startsWith("<")).length,u=e.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:e.args.length;if(o.length<s)throw new Hr(`missing ${e.args[o.length]}`,e);if(o.length>u)throw new Hr(`too many arguments: ${o.slice(u).join(" ")}`,e);let{help:c,...h}=i.values;return{kind:"run",verb:e,args:o,flags:h}}function Sh(n){let r=Object.entries(n.flags??{}).map(([t,{value:e}])=>`[--${t}${e?` ${e}`:""}]`);return[n.name,...r,...n.args].join(" ")}function jh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,e])=>` ${t.padEnd(r)} ${e}`)}function Yi(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:e,about:i}])=>[`--${t}${e?` ${e}`:""}`,i]);return[`Usage: ttheme ${Sh(n)}`,"",n.about,...r.length>0?["","Options:",...jh(r)]:[]].join(`
153
153
  `)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...jh(Gh.filter((r)=>!r.hidden).map((r)=>[Sh(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
154
- `)}async function Jh(n){try{let r=Yd(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Yi(r.verb));else console.error(Yi(r.verb));return r.code}let t=await r.verb.run(r.args,r.flags);return typeof t==="number"?t:0}catch(r){if(r instanceof Nr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
154
+ `)}async function Jh(n){try{let r=Yd(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Yi(r.verb));else console.error(Yi(r.verb));return r.code}let t=await r.verb.run(r.args,r.flags);return typeof t==="number"?t:0}catch(r){if(r instanceof Hr)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
155
155
 
156
156
  ${Yi(r.verb)}`),1;return console.error(`
157
157
  ${r instanceof Error?r.message:String(r)}`),1}}if(Pd)process.exitCode=await Jh(process.argv.slice(2));