@kecan0406/ttheme 1.0.2 → 1.0.4
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/README.md +42 -26
- package/bin/ttheme.js +102 -102
- package/dist/manifest.json +1416 -147
- package/package.json +1 -1
- package/shell/adapters/_bg.zsh +5 -1
- package/shell/ttheme.zsh +11 -4
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,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
|
|
2
|
+
import{createRequire as ff}from"node:module";var tf=Object.create;var{getPrototypeOf:ef,defineProperty:cs,getOwnPropertyNames:sf}=Object;var of=Object.prototype.hasOwnProperty;function uf(n){return this[n]}var cf,hf,Kt=(n,r,t)=>{var e=n!=null&&typeof n==="object";if(e){var i=r?cf??=new WeakMap:hf??=new WeakMap,s=i.get(n);if(s)return s}t=n!=null?tf(ef(n)):{};let o=r||!n||!n.__esModule?cs(t,"default",{value:n,enumerable:!0}):t;for(let u of sf(n))if(!of.call(o,u))cs(o,u,{get:uf.bind(n,u),enumerable:!0});if(e)i.set(n,o);return o};var bn=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var Gn=ff(import.meta.url);var Es=bn((Tm,Zt)=>{var Ms=Ms||function(n){return Buffer.from(n).toString("base64")};function bf(n){var r=this,t=Math.round,e=Math.floor,i=Array(64),s=Array(64),o=Array(64),u=Array(64),c,h,f,g,l=Array(65535),a=Array(65535),m=Array(64),b=Array(64),E=[],F=0,H=7,p=Array(64),I=Array(64),w=Array(64),O=Array(256),k=Array(2048),G,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],K=[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],z=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],P=[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],Nn=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],Z=[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],Mn=[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 an(d){var J=[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((J[q]*d+50)/100);if(Q<1)Q=1;else if(Q>255)Q=255;i[S[q]]=Q}var V=[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 Y=0;Y<64;Y++){var en=e((V[Y]*d+50)/100);if(en<1)en=1;else if(en>255)en=255;s[S[Y]]=en}var sn=[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 v=0;v<8;v++)o[In]=1/(i[S[In]]*sn[$n]*sn[v]*8),u[In]=1/(s[S[In]]*sn[$n]*sn[v]*8),In++}function x(d,J){var q=0,Q=0,V=[];for(var Y=1;Y<=16;Y++){for(var en=1;en<=d[Y];en++)V[J[Q]]=[],V[J[Q]][0]=q,V[J[Q]][1]=Y,Q++,q++;q*=2}return V}function yn(){c=x(K,R),h=x(Nn,Z),f=x(z,P),g=x(B,Mn)}function on(){var d=1,J=2;for(var q=1;q<=15;q++){for(var Q=d;Q<J;Q++)a[32767+Q]=q,l[32767+Q]=[],l[32767+Q][1]=q,l[32767+Q][0]=Q;for(var V=-(J-1);V<=-d;V++)a[32767+V]=q,l[32767+V]=[],l[32767+V][1]=q,l[32767+V][0]=J-1+V;d<<=1,J<<=1}}function nn(){for(var d=0;d<256;d++)k[d]=19595*d,k[d+256>>0]=38470*d,k[d+512>>0]=7471*d+32768,k[d+768>>0]=-11059*d,k[d+1024>>0]=-21709*d,k[d+1280>>0]=32768*d+8421375,k[d+1536>>0]=-27439*d,k[d+1792>>0]=-5329*d}function T(d){var J=d[0],q=d[1]-1;while(q>=0){if(J&1<<q)F|=1<<H;if(q--,H--,H<0){if(F==255)$(255),$(0);else $(F);H=7,F=0}}}function $(d){E.push(d)}function L(d){$(d>>8&255),$(d&255)}function fn(d,J){var q,Q,V,Y,en,sn,In,$n,v=0,j,X=8,En=64;for(j=0;j<X;++j){q=d[v],Q=d[v+1],V=d[v+2],Y=d[v+3],en=d[v+4],sn=d[v+5],In=d[v+6],$n=d[v+7];var A=q+$n,D=q-$n,ln=Q+In,U=Q-In,un=V+sn,jn=V-sn,kn=Y+en,Wn=Y-en,xn=A+kn,vr=A-kn,Rr=ln+un,Jr=ln-un;d[v]=xn+Rr,d[v+4]=xn-Rr;var Dr=(Jr+vr)*0.707106781;d[v+2]=vr+Dr,d[v+6]=vr-Dr,xn=Wn+jn,Rr=jn+U,Jr=U+D;var nt=(xn-Jr)*0.382683433,Gt=0.5411961*xn+nt,rt=1.306562965*Jr+nt,tt=Rr*0.707106781,et=D+tt,it=D-tt;d[v+5]=it+Gt,d[v+3]=it-Gt,d[v+1]=et+rt,d[v+7]=et-rt,v+=8}v=0;for(j=0;j<X;++j){q=d[v],Q=d[v+8],V=d[v+16],Y=d[v+24],en=d[v+32],sn=d[v+40],In=d[v+48],$n=d[v+56];var Ci=q+$n,Me=q-$n,_i=Q+In,Bi=Q-In,xi=V+sn,Di=V-sn,ns=Y+en,rf=Y-en,st=Ci+ns,Ee=Ci-ns,Ot=_i+xi,Rt=_i-xi;d[v]=st+Ot,d[v+32]=st-Ot;var rs=(Rt+Ee)*0.707106781;d[v+16]=Ee+rs,d[v+48]=Ee-rs,st=rf+Di,Ot=Di+Bi,Rt=Bi+Me;var ts=(st-Rt)*0.382683433,es=0.5411961*st+ts,is=1.306562965*Rt+ts,ss=Ot*0.707106781,os=Me+ss,us=Me-ss;d[v+40]=us+es,d[v+24]=us-es,d[v+8]=os+is,d[v+56]=os-is,v++}var Jt;for(j=0;j<En;++j)Jt=d[j]*J[j],m[j]=Jt>0?Jt+0.5|0:Jt-0.5|0;return m}function gn(){L(65504),L(16),$(74),$(70),$(73),$(70),$(0),$(1),$(1),$(0),L(1),L(1),$(0),$(0)}function rn(d){if(!d)return;if(L(65505),d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102)L(d.length+2);else L(d.length+5+2),$(69),$(120),$(105),$(102),$(0);for(var J=0;J<d.length;J++)$(d[J])}function tn(d,J){L(65472),L(17),$(8),L(J),L(d),$(3),$(1),$(17),$(0),$(2),$(17),$(1),$(3),$(17),$(1)}function C(){L(65499),L(132),$(0);for(var d=0;d<64;d++)$(i[d]);$(1);for(var J=0;J<64;J++)$(s[J])}function y(){L(65476),L(418),$(0);for(var d=0;d<16;d++)$(K[d+1]);for(var J=0;J<=11;J++)$(R[J]);$(16);for(var q=0;q<16;q++)$(z[q+1]);for(var Q=0;Q<=161;Q++)$(P[Q]);$(1);for(var V=0;V<16;V++)$(Nn[V+1]);for(var Y=0;Y<=11;Y++)$(Z[Y]);$(17);for(var en=0;en<16;en++)$(B[en+1]);for(var sn=0;sn<=161;sn++)$(Mn[sn])}function N(d){if(typeof d>"u"||d.constructor!==Array)return;d.forEach((J)=>{if(typeof J!=="string")return;L(65534);var q=J.length;L(q+2);var Q;for(Q=0;Q<q;Q++)$(J.charCodeAt(Q))})}function mn(){L(65498),L(12),$(3),$(1),$(0),$(2),$(17),$(3),$(17),$(0),$(63),$(0)}function W(d,J,q,Q,V){var Y=V[0],en=V[240],sn,In=16,$n=63,v=64,j=fn(d,J);for(var X=0;X<v;++X)b[S[X]]=j[X];var En=b[0]-q;if(q=b[0],En==0)T(Q[0]);else sn=32767+En,T(Q[a[sn]]),T(l[sn]);var A=63;for(;A>0&&b[A]==0;A--);if(A==0)return T(Y),q;var D=1,ln;while(D<=A){var U=D;for(;b[D]==0&&D<=A;++D);var un=D-U;if(un>=In){ln=un>>4;for(var jn=1;jn<=ln;++jn)T(en);un=un&15}sn=32767+b[D],T(V[(un<<4)+a[sn]]),T(l[sn]),D++}if(A!=$n)T(Y);return q}function _(){var d=String.fromCharCode;for(var J=0;J<256;J++)O[J]=d(J)}this.encode=function(d,J){var q=new Date().getTime();if(J)Un(J);E=[],F=0,H=7,L(65496),gn(),N(d.comments),rn(d.exifBuffer),C(),tn(d.width,d.height),y(),mn();var Q=0,V=0,Y=0;F=0,H=7,this.encode.displayName="_encode_";var{data:en,width:sn,height:In}=d,$n=sn*4,v=sn*3,j,X=0,En,A,D,ln,U,un,jn,kn;while(X<In){j=0;while(j<$n){ln=$n*X+j,U=ln,un=-1,jn=0;for(kn=0;kn<64;kn++){if(jn=kn>>3,un=(kn&7)*4,U=ln+jn*$n+un,X+jn>=In)U-=$n*(X+1+jn-In);if(j+un>=$n)U-=j+un-$n+4;En=en[U++],A=en[U++],D=en[U++],p[kn]=(k[En]+k[A+256>>0]+k[D+512>>0]>>16)-128,I[kn]=(k[En+768>>0]+k[A+1024>>0]+k[D+1280>>0]>>16)-128,w[kn]=(k[En+1280>>0]+k[A+1536>>0]+k[D+1792>>0]>>16)-128}Q=W(p,o,Q,c,f),V=W(I,u,V,h,g),Y=W(w,u,Y,h,g),j+=32}X+=8}if(H>=0){var Wn=[];Wn[1]=H+1,Wn[0]=(1<<H+1)-1,T(Wn)}if(L(65497),typeof Zt>"u")return new Uint8Array(E);return Buffer.from(E);var xn,vr};function Un(d){if(d<=0)d=1;if(d>100)d=100;if(G==d)return;var J=0;if(d<50)J=Math.floor(5000/d);else J=Math.floor(200-d*2);an(J),G=d}function zn(){var d=new Date().getTime();if(!n)n=50;_(),yn(),on(),nn(),Un(n);var J=new Date().getTime()-d}zn()}if(typeof Zt<"u")Zt.exports=ps;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=ps;function ps(n,r){if(typeof r>"u")r=50;var t=new bf(r),e=t.encode(n,r);return{data:e,width:n.width,height:n.height}}});var Fs=bn((Cm,ye)=>{var Ne=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,s=2276,o=1567,u=3784,c=5793,h=2896;function f(){}function g(H,p){var I=0,w=[],O,k,G=16;while(G>0&&!H[G-1])G--;w.push({children:[],index:0});var S=w[0],K;for(O=0;O<G;O++){for(k=0;k<H[O];k++){S=w.pop(),S.children[S.index]=p[I];while(S.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");S=w.pop()}S.index++,w.push(S);while(w.length<=O)w.push(K={children:[],index:0}),S.children[S.index]=K.children,S=K;I++}if(O+1<G)w.push(K={children:[],index:0}),S.children[S.index]=K.children,S=K}return w[0].children}function l(H,p,I,w,O,k,G,S,K,R){var{precision:z,samplesPerLine:P,scanLines:Nn,mcusPerLine:Z,progressive:B,maxH:Mn,maxV:an}=I,x=p,yn=0,on=0;function nn(){if(on>0)return on--,yn>>on&1;if(yn=H[p++],yn==255){var v=H[p++];if(v)throw Error("unexpected marker: "+(yn<<8|v).toString(16))}return on=7,yn>>>7}function T(v){var j=v,X;while((X=nn())!==null){if(j=j[X],typeof j==="number")return j;if(typeof j!=="object")throw Error("invalid huffman sequence")}return null}function $(v){var j=0;while(v>0){var X=nn();if(X===null)return;j=j<<1|X,v--}return j}function L(v){var j=$(v);if(j>=1<<v-1)return j;return j+(-1<<v)+1}function fn(v,j){var X=T(v.huffmanTableDC),En=X===0?0:L(X);j[0]=v.pred+=En;var A=1;while(A<64){var D=T(v.huffmanTableAC),ln=D&15,U=D>>4;if(ln===0){if(U<15)break;A+=16;continue}A+=U;var un=r[A];j[un]=L(ln),A++}}function gn(v,j){var X=T(v.huffmanTableDC),En=X===0?0:L(X)<<K;j[0]=v.pred+=En}function rn(v,j){j[0]|=nn()<<K}var tn=0;function C(v,j){if(tn>0){tn--;return}var X=k,En=G;while(X<=En){var A=T(v.huffmanTableAC),D=A&15,ln=A>>4;if(D===0){if(ln<15){tn=$(ln)+(1<<ln)-1;break}X+=16;continue}X+=ln;var U=r[X];j[U]=L(D)*(1<<K),X++}}var y=0,N;function mn(v,j){var X=k,En=G,A=0;while(X<=En){var D=r[X],ln=j[D]<0?-1:1;switch(y){case 0:var U=T(v.huffmanTableAC),un=U&15,A=U>>4;if(un===0)if(A<15)tn=$(A)+(1<<A),y=4;else A=16,y=1;else{if(un!==1)throw Error("invalid ACn encoding");N=L(un),y=A?2:3}continue;case 1:case 2:if(j[D])j[D]+=(nn()<<K)*ln;else if(A--,A===0)y=y==2?3:0;break;case 3:if(j[D])j[D]+=(nn()<<K)*ln;else j[D]=N<<K,y=0;break;case 4:if(j[D])j[D]+=(nn()<<K)*ln;break}X++}if(y===4){if(tn--,tn===0)y=0}}function W(v,j,X,En,A){var D=X/Z|0,ln=X%Z,U=D*v.v+En,un=ln*v.h+A;if(v.blocks[U]===void 0&&R.tolerantDecoding)return;j(v,v.blocks[U][un])}function _(v,j,X){var En=X/v.blocksPerLine|0,A=X%v.blocksPerLine;if(v.blocks[En]===void 0&&R.tolerantDecoding)return;j(v,v.blocks[En][A])}var Un=w.length,zn,d,J,q,Q,V;if(B)if(k===0)V=S===0?gn:rn;else V=S===0?C:mn;else V=fn;var Y=0,en,sn;if(Un==1)sn=w[0].blocksPerLine*w[0].blocksPerColumn;else sn=Z*I.mcusPerColumn;if(!O)O=sn;var In,$n;while(Y<sn){for(d=0;d<Un;d++)w[d].pred=0;if(tn=0,Un==1){zn=w[0];for(Q=0;Q<O;Q++)_(zn,V,Y),Y++}else for(Q=0;Q<O;Q++){for(d=0;d<Un;d++){zn=w[d],In=zn.h,$n=zn.v;for(J=0;J<$n;J++)for(q=0;q<In;q++)W(zn,V,Y,J,q)}if(Y++,Y===sn)break}if(Y===sn)do{if(H[p]===255){if(H[p+1]!==0)break}p+=1}while(p<H.length-2);if(on=0,en=H[p]<<8|H[p+1],en<65280)throw Error("marker was not found");if(en>=65488&&en<=65495)p+=2;else break}return p-x}function a(H,p){var I=[],w=p.blocksPerLine,O=p.blocksPerColumn,k=w<<3,G=new Int32Array(64),S=new Uint8Array(64);function K(x,yn,on){var nn=p.quantizationTable,T,$,L,fn,gn,rn,tn,C,y,N=on,mn;for(mn=0;mn<64;mn++)N[mn]=x[mn]*nn[mn];for(mn=0;mn<8;++mn){var W=8*mn;if(N[1+W]==0&&N[2+W]==0&&N[3+W]==0&&N[4+W]==0&&N[5+W]==0&&N[6+W]==0&&N[7+W]==0){y=c*N[0+W]+512>>10,N[0+W]=y,N[1+W]=y,N[2+W]=y,N[3+W]=y,N[4+W]=y,N[5+W]=y,N[6+W]=y,N[7+W]=y;continue}T=c*N[0+W]+128>>8,$=c*N[4+W]+128>>8,L=N[2+W],fn=N[6+W],gn=h*(N[1+W]-N[7+W])+128>>8,C=h*(N[1+W]+N[7+W])+128>>8,rn=N[3+W]<<4,tn=N[5+W]<<4,y=T-$+1>>1,T=T+$+1>>1,$=y,y=L*u+fn*o+128>>8,L=L*o-fn*u+128>>8,fn=y,y=gn-tn+1>>1,gn=gn+tn+1>>1,tn=y,y=C+rn+1>>1,rn=C-rn+1>>1,C=y,y=T-fn+1>>1,T=T+fn+1>>1,fn=y,y=$-L+1>>1,$=$+L+1>>1,L=y,y=gn*s+C*i+2048>>12,gn=gn*i-C*s+2048>>12,C=y,y=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=y,N[0+W]=T+C,N[7+W]=T-C,N[1+W]=$+tn,N[6+W]=$-tn,N[2+W]=L+rn,N[5+W]=L-rn,N[3+W]=fn+gn,N[4+W]=fn-gn}for(mn=0;mn<8;++mn){var _=mn;if(N[8+_]==0&&N[16+_]==0&&N[24+_]==0&&N[32+_]==0&&N[40+_]==0&&N[48+_]==0&&N[56+_]==0){y=c*on[mn+0]+8192>>14,N[0+_]=y,N[8+_]=y,N[16+_]=y,N[24+_]=y,N[32+_]=y,N[40+_]=y,N[48+_]=y,N[56+_]=y;continue}T=c*N[0+_]+2048>>12,$=c*N[32+_]+2048>>12,L=N[16+_],fn=N[48+_],gn=h*(N[8+_]-N[56+_])+2048>>12,C=h*(N[8+_]+N[56+_])+2048>>12,rn=N[24+_],tn=N[40+_],y=T-$+1>>1,T=T+$+1>>1,$=y,y=L*u+fn*o+2048>>12,L=L*o-fn*u+2048>>12,fn=y,y=gn-tn+1>>1,gn=gn+tn+1>>1,tn=y,y=C+rn+1>>1,rn=C-rn+1>>1,C=y,y=T-fn+1>>1,T=T+fn+1>>1,fn=y,y=$-L+1>>1,$=$+L+1>>1,L=y,y=gn*s+C*i+2048>>12,gn=gn*i-C*s+2048>>12,C=y,y=rn*e+tn*t+2048>>12,rn=rn*t-tn*e+2048>>12,tn=y,N[0+_]=T+C,N[56+_]=T-C,N[8+_]=$+tn,N[48+_]=$-tn,N[16+_]=L+rn,N[40+_]=L-rn,N[24+_]=fn+gn,N[32+_]=fn-gn}for(mn=0;mn<64;++mn){var Un=128+(N[mn]+8>>4);yn[mn]=Un<0?0:Un>255?255:Un}}F(k*O*8);var R,z;for(var P=0;P<O;P++){var Nn=P<<3;for(R=0;R<8;R++)I.push(new Uint8Array(k));for(var Z=0;Z<w;Z++){K(p.blocks[P][Z],S,G);var B=0,Mn=Z<<3;for(z=0;z<8;z++){var an=I[Nn+z];for(R=0;R<8;R++)an[Mn+R]=S[B++]}}}return I}function m(H){return H<0?0:H>255?255:H}f.prototype={load:function(p){var I=new XMLHttpRequest;I.open("GET",p,!0),I.responseType="arraybuffer",I.onload=function(){var w=new Uint8Array(I.response||I.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),I.send(null)},parse:function(p){var I=this.opts.maxResolutionInMP*1000*1000,w=0,O=p.length;function k(){var U=p[w]<<8|p[w+1];return w+=2,U}function G(){var U=k(),un=p.subarray(w,w+U-2);return w+=un.length,un}function S(U){var un=1,jn=1,kn,Wn;for(Wn in U.components)if(U.components.hasOwnProperty(Wn)){if(kn=U.components[Wn],un<kn.h)un=kn.h;if(jn<kn.v)jn=kn.v}var xn=Math.ceil(U.samplesPerLine/8/un),vr=Math.ceil(U.scanLines/8/jn);for(Wn in U.components)if(U.components.hasOwnProperty(Wn)){kn=U.components[Wn];var Rr=Math.ceil(Math.ceil(U.samplesPerLine/8)*kn.h/un),Jr=Math.ceil(Math.ceil(U.scanLines/8)*kn.v/jn),Dr=xn*kn.h,nt=vr*kn.v,Gt=nt*Dr,rt=[];F(Gt*256);for(var tt=0;tt<nt;tt++){var et=[];for(var it=0;it<Dr;it++)et.push(new Int32Array(64));rt.push(et)}kn.blocksPerLine=Rr,kn.blocksPerColumn=Jr,kn.blocks=rt}U.maxH=un,U.maxV=jn,U.mcusPerLine=xn,U.mcusPerColumn=vr}var K=null,R=null,z=null,P,Nn,Z=[],B=[],Mn=[],an=[],x=k(),yn=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=k();while(x!=65497){var on,nn,T;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 $=G();if(x===65534){var L=String.fromCharCode.apply(null,$);this.comments.push(L)}if(x===65504){if($[0]===74&&$[1]===70&&$[2]===73&&$[3]===70&&$[4]===0)K={version:{major:$[5],minor:$[6]},densityUnits:$[7],xDensity:$[8]<<8|$[9],yDensity:$[10]<<8|$[11],thumbWidth:$[12],thumbHeight:$[13],thumbData:$.subarray(14,14+3*$[12]*$[13])}}if(x===65505){if($[0]===69&&$[1]===120&&$[2]===105&&$[3]===102&&$[4]===0)this.exifBuffer=$.subarray(5,$.length)}if(x===65518){if($[0]===65&&$[1]===100&&$[2]===111&&$[3]===98&&$[4]===101&&$[5]===0)R={version:$[6],flags0:$[7]<<8|$[8],flags1:$[9]<<8|$[10],transformCode:$[11]}}break;case 65499:var fn=k(),gn=fn+w-2;while(w<gn){var rn=p[w++];F(256);var tn=new Int32Array(64);if(rn>>4===0)for(nn=0;nn<64;nn++){var C=r[nn];tn[C]=p[w++]}else if(rn>>4===1)for(nn=0;nn<64;nn++){var C=r[nn];tn[C]=k()}else throw Error("DQT: invalid table spec");Z[rn&15]=tn}break;case 65472:case 65473:case 65474:k(),P={},P.extended=x===65473,P.progressive=x===65474,P.precision=p[w++],P.scanLines=k(),P.samplesPerLine=k(),P.components={},P.componentsOrder=[];var y=P.scanLines*P.samplesPerLine;if(y>I){var N=Math.ceil((y-I)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${N}MP`)}var mn=p[w++],W,_=0,Un=0;for(on=0;on<mn;on++){W=p[w];var zn=p[w+1]>>4,d=p[w+1]&15,J=p[w+2];if(zn<=0||d<=0)throw Error("Invalid sampling factor, expected values above 0");P.componentsOrder.push(W),P.components[W]={h:zn,v:d,quantizationIdx:J},w+=3}S(P),B.push(P);break;case 65476:var q=k();for(on=2;on<q;){var Q=p[w++],V=new Uint8Array(16),Y=0;for(nn=0;nn<16;nn++,w++)Y+=V[nn]=p[w];F(16+Y);var en=new Uint8Array(Y);for(nn=0;nn<Y;nn++,w++)en[nn]=p[w];on+=17+Y,(Q>>4===0?an:Mn)[Q&15]=g(V,en)}break;case 65501:k(),Nn=k();break;case 65500:k(),k();break;case 65498:var sn=k(),In=p[w++],$n=[],v;for(on=0;on<In;on++){v=P.components[p[w++]];var j=p[w++];v.huffmanTableDC=an[j>>4],v.huffmanTableAC=Mn[j&15],$n.push(v)}var X=p[w++],En=p[w++],A=p[w++],D=l(p,w,P,$n,Nn,X,En,A>>4,A&15,this.opts);w+=D;break;case 65535:if(p[w]!==255)w--;break;default:if(p[w-3]==255&&p[w-2]>=192&&p[w-2]<=254){w-=3;break}else if(x===224||x==225){if(yn!==-1)throw Error(`first unknown JPEG marker at offset ${yn.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(w-1).toString(16)}`);yn=w-1;let U=k();if(p[w+U-2]===255){w+=U-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=k()}if(B.length!=1)throw Error("only single frame JPEGs supported");for(var on=0;on<B.length;on++){var ln=B[on].components;for(var nn in ln)ln[nn].quantizationTable=Z[ln[nn].quantizationIdx],delete ln[nn].quantizationIdx}this.width=P.samplesPerLine,this.height=P.scanLines,this.jfif=K,this.adobe=R,this.components=[];for(var on=0;on<P.componentsOrder.length;on++){var v=P.components[P.componentsOrder[on]];this.components.push({lines:a(P,v),scaleX:v.h/P.maxH,scaleY:v.v/P.maxV})}},getData:function(p,I){var w=this.width/p,O=this.height/I,k,G,S,K,R,z,P,Nn,Z,B,Mn=0,an,x,yn,on,nn,T,$,L,fn,gn,rn,tn=p*I*this.components.length;F(tn);var C=new Uint8Array(tn);switch(this.components.length){case 1:k=this.components[0];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O];for(Z=0;Z<p;Z++)an=R[0|Z*k.scaleX*w],C[Mn++]=an}break;case 2:k=this.components[0],G=this.components[1];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O];for(Z=0;Z<p;Z++)an=R[0|Z*k.scaleX*w],C[Mn++]=an,an=z[0|Z*G.scaleX*w],C[Mn++]=an}break;case 3:if(rn=!0,this.adobe&&this.adobe.transformCode)rn=!0;else if(typeof this.opts.colorTransform<"u")rn=!!this.opts.colorTransform;k=this.components[0],G=this.components[1],S=this.components[2];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O],P=S.lines[0|B*S.scaleY*O];for(Z=0;Z<p;Z++){if(!rn)L=R[0|Z*k.scaleX*w],fn=z[0|Z*G.scaleX*w],gn=P[0|Z*S.scaleX*w];else an=R[0|Z*k.scaleX*w],x=z[0|Z*G.scaleX*w],yn=P[0|Z*S.scaleX*w],L=m(an+1.402*(yn-128)),fn=m(an-0.3441363*(x-128)-0.71413636*(yn-128)),gn=m(an+1.772*(x-128));C[Mn++]=L,C[Mn++]=fn,C[Mn++]=gn}}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;k=this.components[0],G=this.components[1],S=this.components[2],K=this.components[3];for(B=0;B<I;B++){R=k.lines[0|B*k.scaleY*O],z=G.lines[0|B*G.scaleY*O],P=S.lines[0|B*S.scaleY*O],Nn=K.lines[0|B*K.scaleY*O];for(Z=0;Z<p;Z++){if(!rn)nn=R[0|Z*k.scaleX*w],T=z[0|Z*G.scaleX*w],$=P[0|Z*S.scaleX*w],on=Nn[0|Z*K.scaleX*w];else an=R[0|Z*k.scaleX*w],x=z[0|Z*G.scaleX*w],yn=P[0|Z*S.scaleX*w],on=Nn[0|Z*K.scaleX*w],nn=255-m(an+1.402*(yn-128)),T=255-m(an-0.3441363*(x-128)-0.71413636*(yn-128)),$=255-m(an+1.772*(x-128));C[Mn++]=255-nn,C[Mn++]=255-T,C[Mn++]=255-$,C[Mn++]=255-on}}break;default:throw Error("Unsupported color mode")}return C},copyToImageData:function(p,I){var{width:w,height:O,data:k}=p,G=this.getData(w,O),S=0,K=0,R,z,P,Nn,Z,B,Mn,an,x;switch(this.components.length){case 1:for(z=0;z<O;z++)for(R=0;R<w;R++)if(P=G[S++],k[K++]=P,k[K++]=P,k[K++]=P,I)k[K++]=255;break;case 3:for(z=0;z<O;z++)for(R=0;R<w;R++)if(Mn=G[S++],an=G[S++],x=G[S++],k[K++]=Mn,k[K++]=an,k[K++]=x,I)k[K++]=255;break;case 4:for(z=0;z<O;z++)for(R=0;R<w;R++)if(Z=G[S++],B=G[S++],P=G[S++],Nn=G[S++],Mn=255-m(Z*(1-Nn/255)+Nn),an=255-m(B*(1-Nn/255)+Nn),x=255-m(P*(1-Nn/255)+Nn),k[K++]=Mn,k[K++]=an,k[K++]=x,I)k[K++]=255;break;default:throw Error("Unsupported color mode")}}};var b=0,E=0;function F(H=0){var p=b+H;if(p>E){var I=Math.ceil((p-E)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${I}MB`)}b=p}return f.resetMaxMemoryUsage=function(H){b=0,E=H},f.getBytesAllocated=function(){return b},f.requestMemoryAllocation=F,f}();if(typeof ye<"u")ye.exports=vs;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=vs;function vs(n,r={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},e={...t,...r},i=new Uint8Array(n),s=new Ne;s.opts=e,Ne.resetMaxMemoryUsage(e.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=e.formatAsRGBA?4:3,u=s.width*s.height*o;try{Ne.requestMemoryAllocation(u);var c={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:e.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(s.comments.length>0)c.comments=s.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 s.copyToImageData(c,e.formatAsRGBA),c}});var Ns=bn((_m,Is)=>{var wf=Es(),kf=Fs();Is.exports={encode:wf,decode:kf}});var Se=bn((Bm,Ss)=>{var pf=Gn("util"),ys=Gn("stream"),Tn=Ss.exports=function(){ys.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};pf.inherits(Tn,ys);Tn.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))};Tn.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};Tn.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()};Tn.prototype.destroySoon=Tn.prototype.end;Tn.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Tn.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Tn.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)};Tn.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++],s=Math.min(i.length,n.length-r);if(i.copy(e,r,0,s),r+=s,s!==i.length)this._buffers[--t]=i.slice(s)}if(t>0)this._buffers.splice(0,t);this._buffered-=n.length,n.func.call(this,e)};Tn.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 He=bn((Mf)=>{var $r=[{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]}];Mf.getImagePasses=function(n,r){let t=[],e=n%8,i=r%8,s=(n-e)/8,o=(r-i)/8;for(let u=0;u<$r.length;u++){let c=$r[u],h=s*c.x.length,f=o*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};Mf.getInterlaceIterator=function(n){return function(r,t,e){let i=r%$r[e].x.length,s=(r-i)/$r[e].x.length*8+$r[e].x[i],o=t%$r[e].y.length,u=(t-o)/$r[e].y.length*8+$r[e].y[o];return s*4+u*n*4}}});var je=bn((Dm,Hs)=>{Hs.exports=function(r,t,e){let i=r+t-e,s=Math.abs(i-r),o=Math.abs(i-t),u=Math.abs(i-e);if(s<=o&&s<=u)return r;if(o<=u)return t;return e}});var Ge=bn((n0,Gs)=>{var Ff=He(),If=je();function js(n,r,t){let e=n*r;if(t!==8)e=Math.ceil(e/(8/t));return e}var Lr=Gs.exports=function(n,r){let{width:t,height:e,interlace:i,bpp:s,depth:o}=n;if(this.read=r.read,this.write=r.write,this.complete=r.complete,this._imageIndex=0,this._images=[],i){let u=Ff.getImagePasses(t,e);for(let c=0;c<u.length;c++)this._images.push({byteWidth:js(u[c].width,s,o),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:js(t,s,o),height:e,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};Lr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Lr.prototype._unFilterType1=function(n,r,t){let e=this._xComparison,i=e-1;for(let s=0;s<t;s++){let o=n[1+s],u=s>i?r[s-e]:0;r[s]=o+u}};Lr.prototype._unFilterType2=function(n,r,t){let e=this._lastLine;for(let i=0;i<t;i++){let s=n[1+i],o=e?e[i]:0;r[i]=s+o}};Lr.prototype._unFilterType3=function(n,r,t){let e=this._xComparison,i=e-1,s=this._lastLine;for(let o=0;o<t;o++){let u=n[1+o],c=s?s[o]:0,h=o>i?r[o-e]:0,f=Math.floor((h+c)/2);r[o]=u+f}};Lr.prototype._unFilterType4=function(n,r,t){let e=this._xComparison,i=e-1,s=this._lastLine;for(let o=0;o<t;o++){let u=n[1+o],c=s?s[o]:0,h=o>i?r[o-e]:0,f=o>i&&s?s[o-e]:0,g=If(h,c,f);r[o]=u+g}};Lr.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 Js=bn((r0,Rs)=>{var Nf=Gn("util"),Os=Se(),yf=Ge(),Sf=Rs.exports=function(n){Os.call(this);let r=[],t=this;this._filter=new yf(n,{read:this.read.bind(this),write:function(e){r.push(e)},complete:function(){t.emit("complete",Buffer.concat(r))}}),this._filter.start()};Nf.inherits(Sf,Os)});var Qr=bn((t0,Ks)=>{Ks.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 Je=bn((e0,Ls)=>{var Oe=[];(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;Oe[n]=r}})();var Re=Ls.exports=function(){this._crc=-1};Re.prototype.write=function(n){for(let r=0;r<n.length;r++)this._crc=Oe[(this._crc^n[r])&255]^this._crc>>>8;return!0};Re.prototype.crc32=function(){return this._crc^-1};Re.crc32=function(n){let r=-1;for(let t=0;t<n.length;t++)r=Oe[(r^n[t])&255]^r>>>8;return r^-1}});var Ke=bn((i0,Qs)=>{var Sn=Qr(),Hf=Je(),Hn=Qs.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[Sn.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Sn.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Sn.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Sn.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Sn.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Sn.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(){}};Hn.prototype.start=function(){this.read(Sn.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Hn.prototype._parseSignature=function(n){let r=Sn.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))};Hn.prototype._parseChunkBegin=function(n){let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e="";for(let s=4;s<8;s++)e+=String.fromCharCode(n[s]);let i=Boolean(n[4]&32);if(!this._hasIHDR&&t!==Sn.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Hf,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))};Hn.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Hn.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Hn.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))};Hn.prototype._handleIHDR=function(n){this.read(n,this._parseIHDR.bind(this))};Hn.prototype._parseIHDR=function(n){this._crc.write(n);let r=n.readUInt32BE(0),t=n.readUInt32BE(4),e=n[8],i=n[9],s=n[10],o=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 Sn.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(s!==0){this.error(Error("Unsupported compression method"));return}if(o!==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=Sn.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:r,height:t,depth:e,interlace:Boolean(u),palette:Boolean(i&Sn.COLORTYPE_PALETTE),color:Boolean(i&Sn.COLORTYPE_COLOR),alpha:Boolean(i&Sn.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Hn.prototype._handlePLTE=function(n){this.read(n,this._parsePLTE.bind(this))};Hn.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()};Hn.prototype._handleTRNS=function(n){this.simpleTransparency(),this.read(n,this._parseTRNS.bind(this))};Hn.prototype._parseTRNS=function(n){if(this._crc.write(n),this._colorType===Sn.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===Sn.COLORTYPE_GRAYSCALE)this.transColor([n.readUInt16BE(0)]);if(this._colorType===Sn.COLORTYPE_COLOR)this.transColor([n.readUInt16BE(0),n.readUInt16BE(2),n.readUInt16BE(4)]);this._handleChunkEnd()};Hn.prototype._handleGAMA=function(n){this.read(n,this._parseGAMA.bind(this))};Hn.prototype._parseGAMA=function(n){this._crc.write(n),this.gamma(n.readUInt32BE(0)/Sn.GAMMA_DIVISION),this._handleChunkEnd()};Hn.prototype._handleIDAT=function(n){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-n,this._parseIDAT.bind(this,n))};Hn.prototype._parseIDAT=function(n,r){if(this._crc.write(r),this._colorType===Sn.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()};Hn.prototype._handleIEND=function(n){this.read(n,this._parseIEND.bind(this))};Hn.prototype._parseIEND=function(n){if(this._crc.write(n),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Le=bn((Kf)=>{var Ps=He(),jf=[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]}],Gf=[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 Of(n,r){let t=[],e=0;function i(){if(e===n.length)throw Error("Ran out of data");let s=n[e];e++;let o,u,c,h,f,g,l,a;switch(r){default:throw Error("unrecognised depth");case 16:l=n[e],e++,t.push((s<<8)+l);break;case 4:l=s&15,a=s>>4,t.push(a,l);break;case 2:f=s&3,g=s>>2&3,l=s>>4&3,a=s>>6&3,t.push(a,l,g,f);break;case 1:o=s&1,u=s>>1&1,c=s>>2&1,h=s>>3&1,f=s>>4&1,g=s>>5&1,l=s>>6&1,a=s>>7&1,t.push(a,l,g,f,h,c,u,o);break}}return{get:function(s){while(t.length<s)i();let o=t.slice(0,s);return t=t.slice(s),o},resetAfterLine:function(){t.length=0},end:function(){if(e!==n.length)throw Error("extra data found")}}}function Rf(n,r,t,e,i,s){let{width:o,height:u,index:c}=n;for(let h=0;h<u;h++)for(let f=0;f<o;f++){let g=t(f,h,c);jf[e](r,i,g,s),s+=e}return s}function Jf(n,r,t,e,i,s){let{width:o,height:u,index:c}=n;for(let h=0;h<u;h++){for(let f=0;f<o;f++){let g=i.get(e),l=t(f,h,c);Gf[e](r,g,l,s)}i.resetAfterLine()}}Kf.dataToBitMap=function(n,r){let{width:t,height:e,depth:i,bpp:s,interlace:o}=r,u;if(i!==8)u=Of(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(o)g=Ps.getImagePasses(t,e),l=Ps.getInterlaceIterator(t,e);else{let a=0;l=function(){let m=a;return a+=4,m},g=[{width:t,height:e}]}for(let a=0;a<g.length;a++)if(i===8)f=Rf(g[a],c,l,s,n,f);else Jf(g[a],c,l,s,u,h);if(i===8){if(f!==n.length)throw Error("extra data found")}else u.end();return c}});var Qe=bn((o0,Zs)=>{function Qf(n,r,t,e,i){let s=0;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=i[n[s]];if(!c)throw Error("index "+n[s]+" not in palette");for(let h=0;h<4;h++)r[s+h]=c[h];s+=4}}function Pf(n,r,t,e,i){let s=0;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===n[s])c=!0}else if(i[0]===n[s]&&i[1]===n[s+1]&&i[2]===n[s+2])c=!0;if(c)for(let h=0;h<4;h++)r[s+h]=0;s+=4}}function Zf(n,r,t,e,i){let s=255,o=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]*s/o+0.5);u+=4}}Zs.exports=function(n,r,t=!1){let{depth:e,width:i,height:s,colorType:o,transColor:u,palette:c}=r,h=n;if(o===3)Qf(n,h,i,s,c);else{if(u)Pf(n,h,i,s,u);if(e!==8&&!t){if(e===16)h=Buffer.alloc(i*s*4);Zf(n,h,i,s,e)}}return h}});var Ws=bn((u0,Us)=>{var qf=Gn("util"),Pe=Gn("zlib"),qs=Se(),Uf=Js(),Wf=Ke(),Xf=Le(),Vf=Qe(),nr=Us.exports=function(n){qs.call(this),this._parser=new Wf(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()};qf.inherits(nr,qs);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=Pe.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,Pe.Z_MIN_CHUNK);this._inflate=Pe.createInflate({chunkSize:e});let i=t,s=this.emit.bind(this,"error");this._inflate.on("error",function(u){if(!i)return;s(u)}),this._filter.on("complete",this._complete.bind(this));let o=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,o(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 Uf(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=Xf.dataToBitMap(n,this._bitmapInfo);r=Vf(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",r)}});var Vs=bn((c0,Xs)=>{var Xn=Qr();Xs.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 m=function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256}();if(e.bitDepth===8||e.bitDepth===16&&m)return n}let s=e.bitDepth!==16?n:new Uint16Array(n.buffer),o=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)o=65535,c*=2;let h=Buffer.alloc(r*t*c),f=0,g=0,l=e.bgColor||{};if(l.red===void 0)l.red=o;if(l.green===void 0)l.green=o;if(l.blue===void 0)l.blue=o;function a(){let m,b,E,F=o;switch(e.inputColorType){case Xn.COLORTYPE_COLOR_ALPHA:F=s[f+3],m=s[f],b=s[f+1],E=s[f+2];break;case Xn.COLORTYPE_COLOR:m=s[f],b=s[f+1],E=s[f+2];break;case Xn.COLORTYPE_ALPHA:F=s[f+1],m=s[f],b=m,E=m;break;case Xn.COLORTYPE_GRAYSCALE:m=s[f],b=m,E=m;break;default:throw Error("input color type:"+e.inputColorType+" is not supported at present")}if(e.inputHasAlpha){if(!i)F/=o,m=Math.min(Math.max(Math.round((1-F)*l.red+F*m),0),o),b=Math.min(Math.max(Math.round((1-F)*l.green+F*b),0),o),E=Math.min(Math.max(Math.round((1-F)*l.blue+F*E),0),o)}return{red:m,green:b,blue:E,alpha:F}}for(let m=0;m<t;m++)for(let b=0;b<r;b++){let E=a(s,f);switch(e.colorType){case Xn.COLORTYPE_COLOR_ALPHA:case Xn.COLORTYPE_COLOR:if(e.bitDepth===8){if(h[g]=E.red,h[g+1]=E.green,h[g+2]=E.blue,i)h[g+3]=E.alpha}else if(h.writeUInt16BE(E.red,g),h.writeUInt16BE(E.green,g+2),h.writeUInt16BE(E.blue,g+4),i)h.writeUInt16BE(E.alpha,g+6);break;case Xn.COLORTYPE_ALPHA:case Xn.COLORTYPE_GRAYSCALE:{let F=(E.red+E.green+E.blue)/3;if(e.bitDepth===8){if(h[g]=F,i)h[g+1]=E.alpha}else if(h.writeUInt16BE(F,g),i)h.writeUInt16BE(E.alpha,g+2);break}default:throw Error("unrecognised color Type "+e.colorType)}f+=u,g+=c}return h}});var zs=bn((h0,As)=>{var Ys=je();function Yf(n,r,t,e,i){for(let s=0;s<t;s++)e[i+s]=n[r+s]}function Af(n,r,t){let e=0,i=r+t;for(let s=r;s<i;s++)e+=Math.abs(n[s]);return e}function zf(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=n[r+o]-u;e[i+o]=c}}function Tf(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=n[r+s]-o;i+=Math.abs(u)}return i}function Cf(n,r,t,e,i){for(let s=0;s<t;s++){let o=r>0?n[r+s-t]:0,u=n[r+s]-o;e[i+s]=u}}function _f(n,r,t){let e=0,i=r+t;for(let s=r;s<i;s++){let o=r>0?n[s-t]:0,u=n[s]-o;e+=Math.abs(u)}return e}function Bf(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=r>0?n[r+o-t]:0,h=n[r+o]-(u+c>>1);e[i+o]=h}}function xf(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=r>0?n[r+s-t]:0,c=n[r+s]-(o+u>>1);i+=Math.abs(c)}return i}function Df(n,r,t,e,i,s){for(let o=0;o<t;o++){let u=o>=s?n[r+o-s]:0,c=r>0?n[r+o-t]:0,h=r>0&&o>=s?n[r+o-(t+s)]:0,f=n[r+o]-Ys(u,c,h);e[i+o]=f}}function ng(n,r,t,e){let i=0;for(let s=0;s<t;s++){let o=s>=e?n[r+s-e]:0,u=r>0?n[r+s-t]:0,c=r>0&&s>=e?n[r+s-(t+e)]:0,h=n[r+s]-Ys(o,u,c);i+=Math.abs(h)}return i}var rg={0:Yf,1:zf,2:Cf,3:Bf,4:Df},tg={0:Af,1:Tf,2:_f,3:xf,4:ng};As.exports=function(n,r,t,e,i){let s;if(!("filterType"in e)||e.filterType===-1)s=[0,1,2,3,4];else if(typeof e.filterType==="number")s=[e.filterType];else throw Error("unrecognised filter types");if(e.bitDepth===16)i*=2;let o=r*i,u=0,c=0,h=Buffer.alloc((o+1)*t),f=s[0];for(let g=0;g<t;g++){if(s.length>1){let l=1/0;for(let a=0;a<s.length;a++){let m=tg[s[a]](n,c,o,i);if(m<l)f=s[a],l=m}}h[u]=f,u++,rg[f](n,c,o,h,u,i),u+=o,c+=o}return h}});var Ze=bn((f0,Ts)=>{var Rn=Qr(),eg=Je(),ig=Vs(),sg=zs(),og=Gn("zlib"),br=Ts.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||og.createDeflate,n.bitDepth=n.bitDepth||8,n.colorType=typeof n.colorType==="number"?n.colorType:Rn.COLORTYPE_COLOR_ALPHA,n.inputColorType=typeof n.inputColorType==="number"?n.inputColorType:Rn.COLORTYPE_COLOR_ALPHA,[Rn.COLORTYPE_GRAYSCALE,Rn.COLORTYPE_COLOR,Rn.COLORTYPE_COLOR_ALPHA,Rn.COLORTYPE_ALPHA].indexOf(n.colorType)===-1)throw Error("option color type:"+n.colorType+" is not supported at present");if([Rn.COLORTYPE_GRAYSCALE,Rn.COLORTYPE_COLOR,Rn.COLORTYPE_COLOR_ALPHA,Rn.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")};br.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};br.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};br.prototype.filterData=function(n,r,t){let e=ig(n,r,t,this._options),i=Rn.COLORTYPE_TO_BPP_MAP[this._options.colorType];return sg(e,r,t,this._options,i)};br.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(eg.crc32(e.slice(4,e.length-4)),e.length-4),e};br.prototype.packGAMA=function(n){let r=Buffer.alloc(4);return r.writeUInt32BE(Math.floor(n*Rn.GAMMA_DIVISION),0),this._packChunk(Rn.TYPE_gAMA,r)};br.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(Rn.TYPE_IHDR,t)};br.prototype.packIDAT=function(n){return this._packChunk(Rn.TYPE_IDAT,n)};br.prototype.packIEND=function(){return this._packChunk(Rn.TYPE_IEND,null)}});var xs=bn((g0,Bs)=>{var ug=Gn("util"),Cs=Gn("stream"),cg=Qr(),hg=Ze(),_s=Bs.exports=function(n){Cs.call(this);let r=n||{};this._packer=new hg(r),this._deflate=this._packer.createDeflate(),this.readable=!0};ug.inherits(_s,Cs);_s.prototype.pack=function(n,r,t,e){if(this.emit("data",Buffer.from(cg.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(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var io=bn((gt,eo)=>{var Ds=Gn("assert").ok,Pr=Gn("zlib"),fg=Gn("util"),no=Gn("buffer").kMaxLength;function Fr(n){if(!(this instanceof Fr))return new Fr(n);if(n&&n.chunkSize<Pr.Z_MIN_CHUNK)n.chunkSize=Pr.Z_MIN_CHUNK;if(Pr.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 gg(n){return new Fr(n)}function ro(n,r){if(r)process.nextTick(r);if(!n._handle)return;n._handle.close(),n._handle=null}Fr.prototype._processChunk=function(n,r,t){if(typeof t==="function")return Pr.Inflate._processChunk.call(this,n,r,t);let e=this,i=n&&n.length,s=this._chunkSize-this._offset,o=this._maxLength,u=0,c=[],h=0,f;this.on("error",function(m){f=m});function g(m,b){if(e._hadError)return;let E=s-b;if(Ds(E>=0,"have should not go down"),E>0){let F=e._buffer.slice(e._offset,e._offset+E);if(e._offset+=E,F.length>o)F=F.slice(0,o);if(c.push(F),h+=F.length,o-=F.length,o===0)return!1}if(b===0||e._offset>=e._chunkSize)s=e._chunkSize,e._offset=0,e._buffer=Buffer.allocUnsafe(e._chunkSize);if(b===0)return u+=i-m,i=m,!0;return!1}Ds(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(r,n,u,i,this._buffer,this._offset,s),l=l||this._writeState;while(!this._hadError&&g(l[0],l[1]));if(this._hadError)throw f;if(h>=no)throw ro(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+no.toString(16)+" bytes");let a=Buffer.concat(c,h);return ro(this),a};fg.inherits(Fr,Pr.Inflate);function lg(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=Pr.Z_FINISH;return n._processChunk(r,t)}function to(n,r){return lg(new Fr(r),n)}eo.exports=gt=to;gt.Inflate=Fr;gt.createInflate=gg;gt.inflateSync=to});var qe=bn((l0,oo)=>{var so=oo.exports=function(n){this._buffer=n,this._reads=[]};so.prototype.read=function(n,r){this._reads.push({length:Math.abs(n),allowLess:n<0,func:r})};so.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 uo=bn((mg)=>{var dg=qe(),ag=Ge();mg.process=function(n,r){let t=[],e=new dg(n);return new ag(r,{read:e.read.bind(e),write:function(s){t.push(s)},complete:function(){}}).start(),e.process(),Buffer.concat(t)}});var go=bn((a0,fo)=>{var co=!0,ho=Gn("zlib"),bg=io();if(!ho.deflateSync)co=!1;var wg=qe(),kg=uo(),pg=Ke(),Mg=Le(),Eg=Qe();fo.exports=function(n,r){if(!co)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(I){t=I}let i;function s(I){i=I}function o(I){i.transColor=I}function u(I){i.palette=I}function c(){i.alpha=!0}let h;function f(I){h=I}let g=[];function l(I){g.push(I)}let a=new wg(n);if(new pg(r,{read:a.read.bind(a),error:e,metadata:s,gamma:f,palette:u,transColor:o,inflateData:l,simpleTransparency:c}).start(),a.process(),t)throw t;let b=Buffer.concat(g);g.length=0;let E;if(i.interlace)E=ho.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;E=bg(b,{chunkSize:w,maxLength:w})}if(b=null,!E||!E.length)throw Error("bad png - invalid inflate data response");let F=kg.process(E,i);b=null;let H=Mg.dataToBitMap(F,i);F=null;let p=Eg(H,i,r.skipRescale);return i.data=p,i.gamma=h||0,i}});var $o=bn((m0,mo)=>{var lo=!0,ao=Gn("zlib");if(!ao.deflateSync)lo=!1;var vg=Qr(),Fg=Ze();mo.exports=function(n,r){if(!lo)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let e=new Fg(r||{}),i=[];if(i.push(Buffer.from(vg.PNG_SIGNATURE)),i.push(e.packIHDR(n.width,n.height)),n.gamma)i.push(e.packGAMA(n.gamma));let s=e.filterData(n.data,n.width,n.height),o=ao.deflateSync(s,e.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(e.packIDAT(o)),i.push(e.packIEND()),Buffer.concat(i)}});var bo=bn((yg)=>{var Ig=go(),Ng=$o();yg.read=function(n,r){return Ig(n,r||{})};yg.write=function(n,r){return Ng(n,r)}});var ko=bn((Jg)=>{var jg=Gn("util"),wo=Gn("stream"),Gg=Ws(),Og=xs(),Rg=bo(),Jn=Jg.PNG=function(n){if(wo.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 Gg(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 Og(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"))};jg.inherits(Jn,wo);Jn.sync=Rg;Jn.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};Jn.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};Jn.prototype.write=function(n){return this._parser.write(n),!0};Jn.prototype.end=function(n){this._parser.end(n)};Jn.prototype._metadata=function(n){this.width=n.width,this.height=n.height,this.emit("metadata",n)};Jn.prototype._gamma=function(n){this.gamma=n};Jn.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Jn.bitblt=function(n,r,t,e,i,s,o,u){if(t|=0,e|=0,i|=0,s|=0,o|=0,u|=0,t>n.width||e>n.height||t+i>n.width||e+s>n.height)throw Error("bitblt reading outside image");if(o>r.width||u>r.height||o+i>r.width||u+s>r.height)throw Error("bitblt writing outside image");for(let c=0;c<s;c++)n.data.copy(r.data,(u+c)*r.width+o<<2,(e+c)*n.width+t<<2,(e+c)*n.width+t+i<<2)};Jn.prototype.bitblt=function(n,r,t,e,i,s,o){return Jn.bitblt(this,n,r,t,e,i,s,o),this};Jn.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 s=n.data[e+i]/255;s=Math.pow(s,0.45454545454545453/n.gamma),n.data[e+i]=Math.round(s*255)}}n.gamma=0}};Jn.prototype.adjustGamma=function(){Jn.adjustGamma(this)}});var Hi=bn((p1,rh)=>{var Si={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"},ya={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},Sa={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?Si.up():"");if(n)r+=Si.left;return r}};rh.exports={cursor:Si,scroll:ya,erase:Sa,beep:"\x07"}});import{isMainThread as Gm}from"node:worker_threads";import{parseArgs as Sm}from"node:util";var Dn={name:"@kecan0406/ttheme",version:"1.0.4",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 Ru}from"node:fs";import{basename as zl,join as Mt}from"node:path";var lf=/^#[0-9a-f]{6}$/;function hs(n){return lf.test(n)}function On(n){let r=Number.parseInt(n.slice(1),16);return[r>>16&255,r>>8&255,r&255]}function ir(n){let[r,t,e]=On(n).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*r+0.7152*t+0.0722*e}function sr(n,r){let t=ir(n),e=ir(r);return(Math.max(t,e)+0.05)/(Math.min(t,e)+0.05)}function Lt(n,r){return Math.round(sr(n,r)*100)/100}var ar=7,fs=3,ve=0.15,gs=1.6,ls=[1,2,3,4,5,6,9,10,11,12,13,14],ds=[7,15];function ot(n,r){let t=n.ansi[r];if(t===void 0)throw Error(`${n.name}: missing ANSI ${r}`);return t}function Fe(n,r,t){let e=n.background;return r.flatMap((i)=>{let s=ot(n,i);return sr(s,e)<t?[`ANSI ${i} ${s} on ${e} is ${Lt(s,e)}:1, needs ${t}:1`]:[]})}function as(n,r){return Math.min(...r.map((t)=>sr(ot(n,t),n.background)))}var Qt=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:ar,measure:({foreground:n,background:r})=>sr(n,r),check:({foreground:n,background:r})=>sr(n,r)<ar?[`foreground ${n} on ${r} is ${Lt(n,r)}:1, needs ${ar}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:fs,measure:(n)=>as(n,ls),check:(n)=>Fe(n,ls,fs)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ve,measure:(n)=>ir(ot(n,0)),check:(n)=>{let r=ot(n,0);return ir(r)>ve?[`ANSI 0 ${r} has luminance ${ir(r).toFixed(3)}, needs <= ${ve}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:ar,measure:(n)=>as(n,ds),check:(n)=>Fe(n,ds,ar)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:gs,measure:(n)=>sr(ot(n,8),n.background),check:(n)=>Fe(n,[8],gs)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:ar,measure:({foreground:n,selectionBackground:r})=>r===void 0?Number.NaN:sr(n,r),check:({foreground:n,selectionBackground:r})=>r!==void 0&&sr(n,r)<ar?[`foreground ${n} on selection ${r} is ${Lt(n,r)}:1, needs ${ar}:1`]:[]}],Qm=Qt.map((n)=>n.rule),Pt=Qt.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 ms(n){return Qt.map((r)=>Math.round(r.measure(n)*1000)/1000)}function Ie(n){return Qt.filter((r)=>!n.waive.includes(r.rule)).flatMap((r)=>r.check(n).map((t)=>({theme:n.name,rule:r.rule,detail:t})))}function $s(n){return n.flatMap(Ie)}var df=["black","red","green","yellow","blue","magenta","cyan","white"];function bs(n,r){return[n,...df.map((t,e)=>`${t} = '${r[e]}'`),""].join(`
|
|
3
|
+
`)}var ut={id:"alacritty",limits:"no shaders, no runtime color API (OSC only)",emit(n){let r=[...Kr(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}'`,"",bs("[colors.normal]",n.ansi.slice(0,8)),bs("[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
|
|
6
|
-
`);return[{path:`ghostty/themes/${n.name}`,content:r}]},emitShared(n){let[r]=n;if(!r)return[];for(let e of n)if(!
|
|
7
|
-
`)}]}};function
|
|
8
|
-
`}function
|
|
9
|
-
`)}var
|
|
10
|
-
`);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var
|
|
5
|
+
`);return[{path:`alacritty/themes/${n.name}.toml`,content:r},{path:`alacritty/config/${n.name}.toml`,content:t}]}};import{isDeepStrictEqual as af}from"node:util";var ct={id:"ghostty",emit(n){let r=[...Kr(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
|
+
`);return[{path:`ghostty/themes/${n.name}`,content:r}]},emitShared(n){let[r]=n;if(!r)return[];for(let e of n)if(!af(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 mr(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 ws(n){return{...Object.fromEntries(n.ansi.map((r,t)=>[`Ansi ${t} Color`,mr(r)])),"Background Color":mr(n.background),"Bold Color":mr(n.foreground),"Cursor Color":mr(n.cursor),"Cursor Text Color":mr(n.background),"Foreground Color":mr(n.foreground),"Selected Text Color":mr(n.foreground),"Selection Color":mr(n.selectionBackground)}}function mf(n){return n?{"Background Image Location":n.image,"Background Image Mode":n.cover?2:3,Blend:n.opacity}:{"Background Image Location":""}}function ks(n,r,t,e){let i=(o,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,...mf(r.get(o.name)),...ws(o)}),s=[...t?[i(t,"default")]:[],...n.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
|
|
8
|
+
`}function $f(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
|
+
`)}var ht={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(ws(n)).map(([t,e])=>$f(t,e)),"</dict>","</plist>",""].join(`
|
|
10
|
+
`);return[{path:`iterm2/${n.name}.itermcolors`,content:r}]}};var ft={id:"kitty",limits:"no GLSL shaders, no per-codepoint font mapping",emit(n){let r=[...Kr(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
|
|
13
|
-
`
|
|
12
|
+
`);return[{path:`kitty/themes/${n.name}.conf`,content:r},{path:`kitty/config/${n.name}.conf`,content:t}]}};import{createHash as Qg}from"node:crypto";import{mkdirSync as Go,readdirSync as Ir,readFileSync as Oo,renameSync as Ro,rmSync as qr,statSync as Pg,utimesSync as Zg,writeFileSync as Wt}from"node:fs";import{isAbsolute as qg,join as vn}from"node:path";var Eo=Kt(Ns(),1),qt=Kt(ko(),1),po=[137,80,78,71,13,10,26,10],vo=13;function Fo(n){return n.length>=po.length&&po.every((r,t)=>n[t]===r)}function Kg(n){let r=qt.PNG.sync.read(Buffer.from(n));return{width:r.width,height:r.height,data:new Uint8Array(r.data)}}function Io(n,r){if(Fo(n)){let t=Ue(n);if(t&&t.width*t.height>r)throw Error(`${t.width}×${t.height} is over ${r/1e6} megapixels`);return Kg(n)}if(n[0]===255&&n[1]===216){let t=Eo.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 Zr(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 Mo(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 Ue(n){if(n.length<33||!Fo(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=Mo(n,"IDAT");return{width:t,height:e,alpha:Mo(i===-1?n:n.subarray(0,i),"tRNS")!==-1}}function No(n,r=vo){let{width:t,height:e}=n,i=-1,s=-1;for(let o=0;o<n.height;o++)for(let u=0;u<n.width;u++)if((n.data[(o*n.width+u)*4+3]??0)>=r)t=Math.min(t,u),i=Math.max(i,u),e=Math.min(e,o),s=Math.max(s,o);return i<0?null:{x:t,y:e,w:i-t+1,h:s-e+1}}function lt(n,r={x:0,y:0,w:n.width,h:n.height}){let t=0;for(let e=r.y;e<r.y+r.h;e++)for(let i=r.x;i<r.x+r.w;i++)if((n.data[(e*n.width+i)*4+3]??0)<vo)t++;return Math.round(t*100/(r.w*r.h))}function Lg(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),s=n.data;for(let o=0;o<e;o++)for(let u=0;u<t;u++){let c=0,h=0,f=0,g=0;for(let a=0;a<r;a++)for(let m=0;m<r;m++){let b=((o*r+a)*n.width+u*r+m)*4,E=s[b+3]??0;c+=(s[b]??0)*E,h+=(s[b+1]??0)*E,f+=(s[b+2]??0)*E,g+=E}let l=(o*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 yo(n,r,t){let e=Math.min(r/n.width,t/n.height),i=Math.max(1,Math.round(n.width*e)),s=Math.max(1,Math.round(n.height*e)),o=Ut(n,{x:0,y:0,w:n.width,h:n.height},i,s),u=new Uint8Array(r*t*4),c=Math.floor((r-i)/2),h=Math.floor((t-s)/2);for(let f=0;f<s;f++)u.set(o.data.subarray(f*i*4,(f+1)*i*4),((h+f)*r+c)*4);return{width:r,height:t,data:u}}function Ut(n,r,t,e){let i=Math.max(1,Math.floor(Math.min(r.w/t,r.h/e))),s=Lg(n,i),o=s.data,u=new Uint8Array(t*e*4);for(let c=0;c<e;c++){let h=Math.min(s.height-1,Math.max(0,r.y/i+(c+0.5)*r.h/i/e-0.5)),f=Math.floor(h),g=Math.min(s.height-1,f+1),l=h-f;for(let a=0;a<t;a++){let m=Math.min(s.width-1,Math.max(0,r.x/i+(a+0.5)*r.w/i/t-0.5)),b=Math.floor(m),E=Math.min(s.width-1,b+1),F=m-b,H=(f*s.width+b)*4,p=(f*s.width+E)*4,I=(g*s.width+b)*4,w=(g*s.width+E)*4,O=(o[H+3]??0)*(1-F)*(1-l),k=(o[p+3]??0)*F*(1-l),G=(o[I+3]??0)*(1-F)*l,S=(o[w+3]??0)*F*l,K=O+k+G+S,R=(c*t+a)*4;if(K>0)for(let z=0;z<3;z++){let P=(o[H+z]??0)*O+(o[p+z]??0)*k+(o[I+z]??0)*G+(o[w+z]??0)*S;u[R+z]=Math.round(P/K)}u[R+3]=Math.round(K)}}return{width:t,height:e,data:u}}var So={width:2560,height:1550},Ug=2560,Wg=0.1,or={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Xg=ir(We("#19161e","#9b86c8",0.2)),Vg="shelf";function We(n,r,t){let e=On(n),i=On(r);return`#${e.map((s,o)=>Math.round(s+((i[o]??0)-s)*t).toString(16).padStart(2,"0")).join("")}`}function Yg(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 Ho(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 jo(n,r){let t=Yg(n,r),i=Ho((h)=>Ie({name:n.name,background:We(n.background,t,h),foreground:n.foreground,ansi:n.ansi,waive:n.waived??[]}).length===0),s=Ho((h)=>ir(We(n.background,t,h))<=Xg),o=Math.floor(Math.min(i,s)*1000)/1000,u=On(n.background),c=Math.hypot(...On(t).map((h,f)=>(h-(u[f]??0))*o));return{slot:r,color:t,cap:i,matched:s,opacity:o,reach:c}}function Xt(n,r){let t=jo(n,"cursor");if(t.opacity>=Wg)return t;return r.filter((e)=>e!=="cursor"&&e!=="background").map((e)=>jo(n,e)).reduce((e,i)=>i.reach>e.reach?i:e,t)}function Xe(n,r,t){let e=On(r),i=On(t),s=n.data;for(let o=0;o<s.length;o+=4){let u=(0.299*(s[o]??0)+0.587*(s[o+1]??0)+0.114*(s[o+2]??0))/255;for(let c=0;c<3;c++)s[o+c]=Math.round((e[c]??0)+((i[c]??0)-(e[c]??0))*u)}return n}function Ag(n,r,t){let e=On(r),i=n.data,s=new Uint8Array(i.length);for(let o=0;o<i.length;o+=4){let u=(i[o+3]??0)/255*t;for(let c=0;c<3;c++)s[o+c]=Math.round((e[c]??0)*(1-u)+(i[o+c]??0)*u);s[o+3]=255}return{width:n.width,height:n.height,data:s}}function Jo(n){return No(n)??{x:0,y:0,w:n.width,h:n.height}}function zg(n,r){if(n<=0||r<=0)return So;let t=Math.min(1,So.width/Math.max(n,r));return{width:Math.round(n*t),height:Math.round(r*t)}}function Tg(n,r){let t=Math.min(1,Ug/Math.max(r.w,r.h));return Ut(n,r,Math.round(r.w*t),Math.round(r.h*t))}function Ko(n,r,t,e){if(e<or.stands){let c=n.w*t>n.h*r?{x:n.x+(n.w-n.h*r/t)/2,y:n.y,w:n.h*r/t,h:n.h}:{x:n.x,y:n.y,w:n.w,h:n.w*t/r};return{crop:c,at:{x:0,y:0,w:r,h:t},focus:(c.y-n.y+c.h/2)/n.h}}let i=Math.max(or.tall*t,or.reach*r*n.h/n.w),s=i*n.w/n.h;if(s>or.widest*r)s=or.widest*r,i=s*n.h/n.w;let o=or.headroom*t,u=Math.min(1,(t-o)/i);return{crop:{x:n.x,y:n.y,w:n.w,h:n.h*u},at:{x:r*(1-or.margin)-s,y:o,w:s,h:i*u},focus:Math.min(1,(t/2-o)/i)}}function Lo(n,r,t,e){let i=Math.max(1,Math.round(r.at.w)),s=Math.max(1,Math.round(r.at.h)),o=Ut(n,r.crop,i,s),u=new Uint8Array(t*e*4),c=Math.round(r.at.x),h=Math.round(r.at.y);for(let f=0;f<s;f++){let g=h+f,l=Math.max(0,-c),a=Math.min(i,t-c);if(g<0||g>=e||a<=l)continue;u.set(o.data.subarray((f*i+l)*4,(f*i+a)*4),(g*t+c+l)*4)}return{width:t,height:e,data:u}}function Qo(n,r,t,e,i){let s=Jo(n),o=Lo(n,Ko(s,e,i,lt(n,s)),e,i);return Ag(Xe(o,r.background,t.color),r.background,t.opacity)}function Ur(n){return vn(n,"ttheme","backgrounds")}function Cg(n,r,t,e,i){return[...e?[`# from ${e}`]:[],...i?[`# image ${i}`]:[],`background-image = ${r}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${t}`,`config-file = ?${n}.tune.conf`,`config-file = ?${n}.off.conf`,""].join(`
|
|
13
|
+
`)}function Po(n,r,t){let e=new Map;for(let o of[`${r}.conf`,`${r}.tune.conf`,`${r}.off.conf`]){let u;try{u=Oo(vn(n,o),"utf8")}catch{if(o===`${r}.conf`)return;continue}for(let c of u.split(`
|
|
14
|
+
`)){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 s=Number(e.get("background-image-opacity")??1);return{image:i.startsWith("~/")?vn(t,i.slice(2)):qg(i)?i:vn(n,i),opacity:Number.isFinite(s)?s:1,cover:e.get("background-image-fit")==="cover"}}function _g(n,r){for(let t of Ir(n))if(Ve(t,r))qr(vn(n,t))}function Bg(n){return`${n.site}_${n.id}`}function Vt(n,r){return vn(n,Vg,r)}function Ve(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 dt(n,r){try{return/^# image (\S+)$/m.exec(Oo(vn(n,`${r}.conf`),"utf8"))?.[1]}catch{return}}function xg(n,r){try{return Ir(Vt(n,r))}catch{return[]}}function Zo(n,r){let t=dt(n,r);return[...t?[t]:[],...xg(n,r)].sort()}function qo(n,r){let t=dt(n,r);if(!t)return;let e=vn(Vt(n,r),t);qr(e,{recursive:!0,force:!0}),Go(e,{recursive:!0});for(let i of Ir(n))if(Ve(i,r))Ro(vn(n,i),vn(e,i.slice(r.length)))}function Uo(n,r,t){let e=vn(Vt(n,r),t);for(let i of Ir(e))Ro(vn(e,i),vn(n,`${r}${i}`));qr(e,{recursive:!0})}function Wo(n,r,t){try{return Ir(vn(n,"originals")).find((e)=>e.startsWith(`${r}-${t}.`))}catch{return}}function Xo(n,r,t){let e=Wo(n,r,t);if(e){let i=new Date;Zg(vn(n,"originals",e),i,i)}}function Vo(n,r,t){let e=Ur(n),i=Zo(e,r),s=dt(e,r);if(!s||i.length<2)throw Error(`${r} has no other image`);let o=(i.indexOf(s)+t+i.length)%i.length,u=i[o];return qo(e,r),Uo(e,r,u),Xo(e,r,u),{key:u,at:o+1,of:i.length}}function Yo(n,r){let t=Ur(n),e=Ir(t).filter((h)=>Ve(h,r));if(e.length===0)throw Error(`${r} has no image`);let i=Zo(t,r),s=dt(t,r),o=s&&Wo(t,r,s);if(o)qr(vn(t,"originals",o));for(let h of e)qr(vn(t,h));let u=i.filter((h)=>h!==s),c=u[(s?i.indexOf(s):0)%u.length];if(c)Uo(t,r,c),Xo(t,r,c);return{key:s,left:u.length}}function Dg(n,r,t){if(dt(n,r)!==t)qo(n,r);if(t)qr(vn(Vt(n,r),t),{recursive:!0,force:!0});_g(n,r)}function Ao(n,r,t,e,i,s){let o=Ur(n),u=r.name,c=Bg(i);Go(vn(o,"originals"),{recursive:!0}),Dg(o,u,c);let h=Jo(e),{width:f,height:g}=zg(s.width,s.height),l=Ko(h,f,g,lt(e,h)),a=Zr(Xe(Tg(e,h),r.background,t.color)),m=Zr(Xe(Lo(e,l,f,g),r.background,t.color)),b=vn(o,`${u}.${Qg("sha1").update(a).update(m).digest("hex").slice(0,8)}`),E=`${b}.png`,F=`${b}@fill-${Math.round(l.focus*100)}.png`,H=vn(o,`${u}.conf`),p=vn(o,"originals",`${u}-${i.site}_${i.id}.${i.ext}`);return Wt(E,a),Wt(F,m),Wt(H,Cg(u,F,t.opacity,i.from,c)),Wt(p,i.bytes),[E,F,H,p]}function zo(n){let r=vn(Ur(n),"originals"),t=new Map,e;try{e=Ir(r)}catch{return new Map}for(let i of e){let s=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,o,u,c]=s??[];if(!o||!u||!c)continue;let h=Pg(vn(r,i)).mtimeMs,f=t.get(o);if(!f||h>f.at)t.set(o,{site:u,id:Number(c),at:h})}return new Map([...t].map(([i,{site:s,id:o}])=>[i,{site:s,id:o}]))}function Ye(n){let{slot:r,color:t,opacity:e}=Xt({name:n.name,background:n.background,foreground:n.foreground,cursor:n.cursor,selection:n.selectionBackground,ansi:n.ansi,waived:n.waive},n.signatureSlots);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.booruSites?{booruSites:n.booruSites}:{},...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:ms(n),...n.waive.length>0?{waived:n.waive}:{},backdrop:{slot:r,color:t,opacity:e}}}function Wr(n){return n.filter((r)=>r.default!==!0)}function nl(n){let[r]=n;if(!r)throw Error("manifest needs at least one theme");return{version:Dn.version,gate:Pt,placement:or,font:r.font,...r.ghostty.shader?{shader:r.ghostty.shader}:{},palettes:n.map(Ye)}}var Ae={id:"meta",emitShared(n){return[{path:"manifest.json",content:`${JSON.stringify(nl(n),null,2)}
|
|
15
|
+
`}]}};import{readdirSync as Rl,readFileSync as xe}from"node:fs";import{basename as Jl,join as De}from"node:path";import{readdirSync as rl,rmSync as tl,statSync as el}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as il}from"node:net";import{homedir as sl}from"node:os";import{join as mt}from"node:path";import{setTimeout as ol}from"node:timers/promises";var Nr=100,Te=25000000,ul=536870912,$t=["safe","questionable","explicit"],yr=["nudity","underwear"],cl={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},at={safe:"s",questionable:"q",explicit:"e"},hl=8191,fl=20000,gl=5000,To=3000,Co=8,ll=3000,Do=60000,_o=3,dl=`ttheme/${Dn.version} (+${Dn.homepage})`,al=["orig","tile","thumb","cut"],nu=new Map,ml=Il(process.env.TTHEME_FIND_HOSTS),$l=Fl(process.env.TTHEME_FIND_CUTOUTS);il(ll);function Bo(n){try{return rl(n)}catch{return[]}}function Yt(n){return n.startsWith("//")?`https:${n}`:n}function bt(n){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(n)?.[1]??"").toLowerCase()}function wt(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 bl(n){let r=n.trim(),e=(r?JSON.parse(r):{}).tags??{};return new Map(Object.entries(e).map(([i,s])=>[i,String(s)]))}function ze(n,r,t){let e=Yt(String(n??""));return{file:e,width:Number(r)||0,height:Number(t)||0,ext:bt(e)}}function ru(n,r){let t=Yt(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),solo:r.solo,family:Number(n.parent_id)||(n.has_children===!0?Number(n.id):0),smaller:r.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<e*i)}]}function wl(n){let r=bl(n);return wt(n).flatMap((t)=>{let e=Yt(String(t.file_url??"")),i=String(t.tags??"");return ru(t,{preview:t.preview_url,file:e,ext:String(t.file_ext||bt(e)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((s)=>r.get(s)==="artist")??"",md5:t.md5,tags:i,solo:void 0,versions:[ze(t.jpeg_url,t.jpeg_width,t.jpeg_height),ze(t.sample_url,t.sample_width,t.sample_height)]})})}function kl(n){return wt(n).flatMap((r)=>{let t=Yt(String(r.file_url??"")),e=String(r.tag_string??""),i=r.media_asset??{};return ru(r,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??r.preview_file_url,file:t,ext:String(r.file_ext||bt(t)).toLowerCase(),owner:"",artist:String(r.tag_string_artist??"").split(/\s+/)[0]??"",md5:r.md5,tags:e,solo:e.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>ze(s.url,s.width,s.height)).filter((s)=>s.ext==="jpg"||s.ext==="png").sort((s,o)=>o.width*o.height-s.width*s.height)})})}function pl(n){return wt(n).flatMap((r)=>{let t=String(r.value??"");return t?[{value:t,count:Number(r.post_count)||0}]:[]})}function Ml(n){return wt(n).flatMap((r)=>{let t=String(r.name??"");return t?[{value:t,count:Number(r.count)||0}]:[]})}function El(n){return Number(/count="(\d+)"/.exec(n)?.[1]??0)}function vl(n){let r=n.trim()?JSON.parse(n):{};return Number(r.counts?.posts)||0}function Fl(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 Il(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 s=new URL(t.slice(e+1));if(i&&s.protocol==="https:")r.set(i,s.origin)}catch{}}return r}function tu(n,r,t,e){let i=(n??"").split(/\s+/);if(e!==void 0&&i.includes(e))return[];let s=r.filter((o)=>i.includes(o));return s.length>0?s:[...t]}function At(n){return tu(n,$t,["safe"])}function zt(n){return tu(n,yr,yr,"none")}function eu(n,r,t){return{safe:new Set(n),questionable:new Set(r),explicit:new Set(t)}}function iu(n){let r=ml.get(n.key),t=$l.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 su(n){return n.length<2?n.join(""):n.map((r)=>`~${r}`).join(" ")}function xo(n){let r=iu(n),t=(e)=>new URLSearchParams({api_version:"2",include_tags:"1",...e});return{...r,cutouts:su(r.cutouts),ratings:eu([at.safe],[at.questionable],[at.explicit]),rate:(e)=>{let[i]=e;if(e.length===1&&i)return`rating:${at[i]}`;let s=$t.filter((u)=>!e.includes(u)),[o]=s;return s.length===1&&o?`-rating:${at[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(e,i)=>`${r.origin}/post.json?${t({limit:String(Nr),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:wl,count:El}}function Nl(n){let r=iu(n),t=eu(["g"],["s","q"],["e"]);return{...r,cutouts:su(r.cutouts),ratings:t,rate:(e)=>e.length===$t.length?"":`rating:${e.flatMap((i)=>[...t[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(e,i)=>`${r.origin}/posts.json?${new URLSearchParams({limit:String(Nr),page:String(i+1),tags:e})}`,countUrl:(e)=>`${r.origin}/counts/posts.json?${new URLSearchParams({tags:e})}`,postUrl:(e)=>`${r.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${e}`})}`,pageUrl:(e)=>`${r.origin}/posts/${e}`,parse:kl,count:vl}}function yl(n){return pn.find((r)=>r.key===n||r.name===n||new URL(r.origin).host===n)}function Ce(n){return n.split(/\s+/).filter((r)=>r&&!r.startsWith("rating:")).length}function ou(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=pn.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 s=yl(i.host),o=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return s&&o>0?{site:s,id:o}:void 0}var pn=[Nl({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),xo({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),xo({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Sr=134217728;function rr(n,r){return pn.indexOf(n)*Sr+r}function _e(n){let r;try{r=new URL(n).hostname}catch{return""}return r.split(".").slice(-2).join(".")}function uu(){return pn.filter((n)=>!n.tunneled).map((n)=>_e(n.origin)).flatMap((n)=>[n,`.${n}`]).join(",")}function cu(n,r=yr){return n.tags.filter((t)=>r.some((e)=>cl[e].has(t)))}function hu(n,r,t=["safe"]){return t.some((e)=>n.ratings[e].has(r.rating))}function kt(n){return[n,...n.smaller].find((r)=>r.width*r.height<=Te)}function fu(n){let r=new Map;for(let[t,e]of[...n].sort(([i],[s])=>i<s?-1:1)){if(e==="")continue;r.set(e,[...r.get(e)??[],t])}return r}function gu(){return mt(process.env.XDG_CACHE_HOME??mt(sl(),".cache"),"ttheme")}function pr(n){return mt(gu(),n.key)}function lu(n=ul,r=gu()){let t=[],e=0;for(let i of Bo(r))for(let s of al){let o=mt(r,i,s);for(let u of Bo(o)){let c=mt(o,u);try{let{size:h,mtimeMs:f}=el(c);t.push({path:c,size:h,at:f}),e+=h}catch{}}}t.sort((i,s)=>i.at-s.at);for(let i of t){if(e<=n)return;try{tl(i.path,{force:!0}),e-=i.size}catch{}}}function Sl(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)?Do:Math.max(0,t-r)}function wr(n){return nu.get(n.key)??0}function Hl(n){for(let r=n;r instanceof Error;r=r.cause)if(r.code==="ECONNRESET")return!0;return!1}function jl(n){return(n.headers.get("server")??"").startsWith("cloudflare")&&n.headers.get("cf-mitigated")==="challenge"}async function kr(n,r,t,e={},i=fl){for(let s=1;;s++){let o=wr(n)-Date.now();if(o>0)await ol(o,void 0,{signal:t});let u;try{u=await fetch(r,{headers:{"User-Agent":dl,Referer:`${n.origin}/`,...e},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t})}catch(c){if(s<_o&&!t.aborted&&Hl(c))continue;throw c}if(u.status===429&&s<_o){await u.body?.cancel();let c=Sl(u.headers.get("retry-after"),Date.now());if(c>Do)throw Error(`${n.name} asks to wait ${Math.ceil(c/1000)}s`);nu.set(n.key,Math.max(wr(n),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(jl(u)?`${n.name} is behind a Cloudflare challenge`:`${n.name} answered ${u.status}`);return u}}async function du(n,r,t,e){return n.parse(await(await kr(n,n.postsUrl(r,t),e)).text())}async function au(n,r,t){return n.count(await(await kr(n,n.countUrl(r),t)).text())}async function Be(n,r,t){let[e]=n.parse(await(await kr(n,n.postUrl(r),t)).text());return e}function Gl(n){let r=pn.find((e)=>e.key==="danbooru"),t=new URLSearchParams({limit:String(2*Nr),only:"md5,tag_string",tags:`md5:${n.join(",")}`});return`${r.origin}/posts.json?${t}`}function Ol(n){return new Map(wt(n).flatMap((r)=>{let t=String(r.md5??"");return t?[[t,String(r.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function mu(n,r){for(let t of n){let e=r.get(t.md5);if(e)t.tags=[...new Set([...t.tags,...e])],t.solo=e.includes("solo")}}async function $u(n,r){let t=pn.find((i)=>i.key==="danbooru"),e=new Map;if(wr(t)>Date.now())return e;for(let i=0;i<n.length;i+=Nr){let s=await(await kr(t,Gl(n.slice(i,i+Nr)),r,{},gl)).text();for(let[o,u]of Ol(s))e.set(o,u)}return e}async function bu(n,r){let t=pn.find((s)=>s.key==="danbooru");if(wr(t)<=Date.now())try{let s=new URLSearchParams({"search[query]":n,"search[type]":"tag_query",limit:String(Co)}),o=`${t.origin}/autocomplete.json?${s}`;return pl(await(await kr(t,o,r,{},To)).text())}catch(s){if(r.aborted)throw s}let e=pn.find((s)=>s.key==="yande"),i=new URLSearchParams({name:n,order:"count",limit:String(Co)});return Ml(await(await kr(e,`${e.origin}/tag.json?${i}`,r,{},To)).text())}async function wu(n,r,t){let e=await kr(n,r,t,{Range:`bytes=0-${hl}`});return Ue(new Uint8Array(await e.arrayBuffer()))}async function ku(n,r,t,e){let i=await kr(n,r,t,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let u=[],c=0;for(;;){let{done:g,value:l}=await o.read();if(g)break;u.push(l),c+=l.length,e?.(c,s)}let h=new Uint8Array(c),f=0;for(let g of u)h.set(g,f),f+=g.length;return h}var Kl="_defaults.toml",ur="_groups.toml",pu=3,Mu=["background","foreground","cursor","selection"],Ll=new Set(["next","help","preview","pin","unpin","config"]);function Fn(n,r){throw Error(`${n}: ${r}`)}function Hr(n,r,t){if(typeof t!=="string"||!hs(t))Fn(n,`${r} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Vn(n,r,t){if(typeof t!=="string"||t.length===0)Fn(n,`${r} must be a non-empty string`);return t}function cr(n){return n&&typeof n==="object"?n:{}}function Ql(n,r,t){let e={...cr(t),...cr(r)},i=e.codepoint_map??[];if(!Array.isArray(i))Fn(n,"font.codepoint_map must be an array");return{family:Vn(n,"font.family",e.family),size:Number(e.size),codepointMap:i.map((s)=>{let o=cr(s);return{range:Vn(n,"font.codepoint_map[].range",o.range),family:Vn(n,"font.codepoint_map[].family",o.family)}})}}function Pl(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)Fn(n,"ghostty.icon_screen must not be empty");return e.map((i,s)=>Hr(n,`ghostty.icon_screen[${s}]`,i))}function Zl(n,r,t,e){let i={...cr(t),...cr(r)};return{shader:i.shader===void 0?void 0:Vn(n,"ghostty.shader",i.shader),iconGhost:i.icon_ghost===void 0?e.cursor:Hr(n,"ghostty.icon_ghost",i.icon_ghost),iconScreen:Pl(n,i.icon_screen,e)}}function ql(n){return new Map([...Mu.map((r)=>[r,n[r]]),...n.ansi.map((r,t)=>[`ansi${t}`,r])])}function Ul(n,r,t){if(!Array.isArray(r)||r.length!==pu)Fn(n,`meta.signature must name exactly ${pu} palette slots`);let e=ql(t),i=[],s=[];for(let[o,u]of r.entries()){let c=`meta.signature[${o}]`,h=Vn(n,c,u),f=e.get(h);if(f===void 0)Fn(n,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Mu.join(", ")} or ansi0-ansi15`);i.push(h),s.push(f)}if(new Set(s).size!==s.length)Fn(n,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function Wl(n,r,t){if(r===void 0)return;if(!t)Fn(n,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!r||typeof r!=="object"||Array.isArray(r))Fn(n,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let e={};for(let[i,s]of Object.entries(r)){let o=pn.find((c)=>c.key===i);if(!o)Fn(n,`meta.booru_sites.${i} is not a find site — use ${pn.map((c)=>c.key).join(", ")}`);let u=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))Fn(n,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(u.length>1&&Number.isFinite(o.tagBudget))Fn(n,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);e[i]=u}return e}function Xl(n){let t=Bun.TOML.parse(xe(De(n,ur),"utf8")).group;if(!Array.isArray(t)||t.length===0)Fn(ur,"needs at least one [[group]] table");return t.map((e)=>{let i=cr(e);return{name:Vn(ur,"group.name",i.name),native:i.native===void 0?void 0:Vn(ur,"group.native",i.native),lead:Vn(ur,"group.lead",i.lead)}})}function Vl(n,r,t,e){let i=Bun.TOML.parse(r),s=cr(i.meta),o=cr(i.colors),u=cr(i.contrast),c=o.ansi;if(!Array.isArray(c)||c.length!==16)Fn(n,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let h=Vn(n,"meta.name",s.name);if(h!==Jl(n,".toml"))Fn(n,`meta.name "${h}" does not match the filename`);if(Ll.has(h))Fn(n,`meta.name "${h}" collides with a ttheme subcommand`);if(h.startsWith("-"))Fn(n,`meta.name "${h}" would be read as a flag by the ttheme CLI`);let f=s.role;if(f!==void 0&&f!=="default")Fn(n,`meta.role must be "default", got ${JSON.stringify(f)}`);let g=Vn(n,"meta.group",s.group),l=e.get(g);if(!l)Fn(n,`meta.group "${g}" has no [[group]] table in ${ur}`);let a=Hr(n,"colors.background",o.background),m=Hr(n,"colors.foreground",o.foreground),b=Hr(n,"colors.cursor",o.cursor),E=Hr(n,"colors.selection_background",o.selection_background),F=c.map((O,k)=>Hr(n,`colors.ansi[${k}]`,O)),H=Ul(n,s.signature,{background:a,foreground:m,cursor:b,selection:E,ansi:F}),p=s.booru===void 0?void 0:Vn(n,"meta.booru",s.booru);if(p!==void 0&&/\s/.test(p))Fn(n,`meta.booru must be a single booru tag, got ${JSON.stringify(p)}`);let I=Wl(n,s.booru_sites,p),w=Array.isArray(u.waive)?u.waive.map(String):[];if(w.length>0&&typeof u.reason!=="string")Fn(n,"contrast.waive needs a contrast.reason explaining why");return{name:h,group:g,native:l.native,lead:l.lead===h,order:Number(s.order),role:f,ansiSource:Vn(n,"meta.ansi_source",s.ansi_source),...p?{booru:p}:{},...I?{booruSites:I}:{},background:a,foreground:m,cursor:b,selectionBackground:E,ansi:F,signature:H.colors,signatureSlots:H.names,font:Ql(n,i.font,t.font),ghostty:Zl(n,i.ghostty,t.ghostty,{background:a,cursor:b,selectionBackground:E}),waive:w,waiveReason:typeof u.reason==="string"?u.reason:void 0}}function Eu(n){let r=Bun.TOML.parse(xe(De(n,Kl),"utf8")),t=Xl(n),e=new Map(t.map((o)=>[o.name,o]));if(e.size!==t.length)Fn(ur,"group.name must be unique");let i=Rl(n).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>Vl(o,xe(De(n,o),"utf8"),r,e)).sort((o,u)=>o.order-u.order);if(new Set(i.map((o)=>o.order)).size!==i.length)throw Error("themes: meta.order must be unique across all themes");for(let o of t){let u=i.filter((c)=>c.group===o.name);if(u.length===0)Fn(ur,`group "${o.name}" has no themes`);if(!u.some((c)=>c.name===o.lead))Fn(ur,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return i}function vu(n){return n.filter((r)=>r.role===void 0)}function pt(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 Tt=["ghostty","kitty","alacritty","iterm2"];var Fu=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Ct(n,r){let t=`# ttheme begin
|
|
14
16
|
${r}
|
|
15
17
|
# ttheme end
|
|
16
|
-
`;if(
|
|
18
|
+
`;if(Fu.test(n))return n.replace(Fu,t);if(n==="")return t;return`${n.replace(/\n*$/,`
|
|
17
19
|
`)}
|
|
18
|
-
${t}`}function
|
|
19
|
-
`)}function
|
|
20
|
+
${t}`}function Iu(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 Nu(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(`
|
|
21
|
+
`)}function yu(n){return`source ${n}/ttheme.zsh`}var Yl="# ttheme settings — uncomment a line to change it; exported variables win over this file",_t={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_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},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 — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function ni(n,r){let t=`: \${${n}:=${r}}`;return _t[n]?.default===r?`# ${t}`:t}function Su(n){return new RegExp(String.raw`^#? ?: \$\{${n}[^\n]*$`,"m")}function Al(n,r){if(Su(r).test(n))return n;let t=_t[r];return`${n.replace(/\n*$/,`
|
|
20
22
|
`)}
|
|
21
23
|
${t.doc}
|
|
22
|
-
${
|
|
23
|
-
`}function
|
|
24
|
-
${
|
|
24
|
+
${ni(r,t.default)}
|
|
25
|
+
`}function ri(){let n=Object.entries(_t).map(([r,t])=>`${t.doc}
|
|
26
|
+
${ni(r,t.default)}`);return`${[Yl,...n].join(`
|
|
25
27
|
|
|
26
28
|
`)}
|
|
27
|
-
`}function
|
|
29
|
+
`}function Bt(n,r,t){let e=ni(r,t),i=Su(r);if(i.test(n))return n.replace(i,e);return`${n.replace(/\n*$/,`
|
|
28
30
|
`)}
|
|
29
31
|
${e}
|
|
30
|
-
`}function
|
|
31
|
-
import = ["${n}"]`:""}function
|
|
32
|
-
`)}var
|
|
32
|
+
`}function Hu(n){if(n==="")return ri();return Object.keys(_t).reduce(Al,n)}function ju(n){return n?`include themes/${n}.conf`:""}function Gu(n){return n?`[general]
|
|
33
|
+
import = ["${n}"]`:""}function ti(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}"`,s=(u)=>u.map((c)=>c.name).join(" "),o=Wr(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='${ri().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=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(pt(o))})`,"","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(`
|
|
34
|
+
`)}var ei={id:"shell",emitShared(n){return[{path:"shell/palettes.zsh",content:ti(n.map(Ye))}]}};var Ou=(n)=>`[${n.map((r)=>`"${r}"`).join(", ")}]`,ii={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 = ${Ou(n.ansi.slice(0,8))}`,`brights = ${Ou(n.ansi.slice(8,16))}`,""].join(`
|
|
33
35
|
`),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
|
|
35
|
-
${t.length} themes (${
|
|
36
|
-
`)}function
|
|
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')
|
|
36
|
+
`);return[{path:`wezterm/colors/${n.name}.toml`,content:r},{path:`wezterm/config/${n.name}.lua`,content:t}]}};function Kr(n){return[`# ${n.name} — ${n.group}${n.native?` (${n.native})`:""}`,`# ANSI: ${n.ansiSource}`]}var Ju=Mt(import.meta.dirname,".."),Tl=Mt(Ju,"themes"),si=Mt(Ju,"dist"),xt=[ct,ft,ut,ii,ht],Cl=[ei,Ae],Ku=xt.map((n)=>n.id);async function Dt({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?xt.filter((s)=>n.includes(s.id)):xt,t=Eu(Tl),e=$s(t);if(e.length>0){for(let s of e)console.error(` ✗ ${s.theme} [${s.rule}] ${s.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===xt.length)Ru(si,{recursive:!0,force:!0});else for(let s of r)Ru(Mt(si,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...r,...Cl]){let o=t.flatMap((h)=>s.emit?.(h)??[]),u=s.emitShared?.(t)??[];for(let h of[...o,...u])await Bun.write(Mt(si,h.path),h.content),i++;let c=o.length>0?`${t.length} themes${s.limits?` (${s.limits})`:""}`:u.map((h)=>zl(h.path)).join(" ");console.log(` ${s.id.padEnd(10)} ${c}`)}console.log(`
|
|
37
|
+
${t.length} themes (${vu(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Kc}from"node:child_process";import{createHash as xd}from"node:crypto";import{existsSync as Tr,mkdirSync as vi,mkdtempSync as Dd,readFileSync as Lc,rmSync as wi,statSync as na,writeFileSync as Fi}from"node:fs";import{tmpdir as ra}from"node:os";import{dirname as yc,join as gr}from"node:path";import{existsSync as _l,mkdirSync as Bl,readFileSync as xl,writeFileSync as Dl}from"node:fs";import{dirname as nd,join as rd}from"node:path";var Lu="https://kecan0406.github.io/ttheme/manifest.json",td=20000;function ne(n){return rd(n,"ttheme","catalog.json")}function re(n,r){let t=ne(n);Bl(nd(t),{recursive:!0}),Dl(t,`${JSON.stringify(r,null,2)}
|
|
38
|
+
`)}function Pn(n){let r=ne(n);if(!_l(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);return Qu(xl(r,"utf8"))}function Qu(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 Pu(n){let r;try{r=await fetch(n,{signal:AbortSignal.timeout(td)})}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 Qu(await r.text())}function Zu(n){let r=new Set(n.waived??[]);return Pt.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 te(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 qu(n,r){let t=r.toLowerCase();return n.filter((e)=>[e.name,e.group,e.native??"",e.ansiSource].some((i)=>i.toLowerCase().includes(t)))}function Uu(n,r,t){let e=t.toLowerCase(),i=(s)=>s.name===r.name?0:s.group===r.group?1:2;return n.filter((s)=>s.booru?.toLowerCase().includes(e)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function Wu(n,r){return n.booruSites?.[r]??(n.booru?[n.booru]:[])}import{spawn as ed}from"node:child_process";var id=30000,sd=3,od=97,ud=`ObjC.import('Vision')
|
|
39
39
|
ObjC.import('CoreImage')
|
|
40
40
|
ObjC.import('CoreGraphics')
|
|
41
41
|
function run(argv) {
|
|
@@ -54,104 +54,104 @@ function run(argv) {
|
|
|
54
54
|
$.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
|
|
55
55
|
$.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
|
|
56
56
|
if (!written) throw new Error('write failed')
|
|
57
|
-
}`;function
|
|
58
|
-
`).at(-1)||`osascript exited ${u}`))})})}var
|
|
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
|
-
`)}function
|
|
57
|
+
}`;function oi(){return process.platform==="darwin"}function Xu(n){return n>=sd&&n<=od}function Vu(n,r,t){return new Promise((e,i)=>{let s=ed("osascript",["-l","JavaScript","-e",ud,n,r],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(id)])}),o="";s.stderr.on("data",(u)=>{o+=u}),s.on("error",i),s.on("close",(u)=>{if(u===0){e();return}i(Error(o.trim().split(`
|
|
58
|
+
`).at(-1)||`osascript exited ${u}`))})})}var Qn={pitch:25,cols:22,rows:9,height:13},jr={cols:25,rows:16},cd=2147483648,hd=-1073741826,fd=1600,gd="\x1B[0m",tr="\x1B[1m",cn="\x1B[2m",Et="\x1B[31m",hr="\x1B[32m",Zn="\x1B[33m",ee="\x1B[1;34m",ld="\x1B[35m",dd={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 zu(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(dd[`${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 Tu="\x1B]1337;ReportCellSize\x07\x1B[16t",Yu="\x1B]1337;ReportCellSize=";function hi(n){let r=n.indexOf(Yu);if(r!==-1){let i=n.slice(r+Yu.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((c)=>c!==-1),o=s.length>0?Math.min(...s):-1,u=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));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(o+(i[o]==="\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 Xr(n,r){return{perRow:Math.max(1,Math.floor((n+1)/Qn.pitch)),rowsVis:Math.max(1,Math.floor((r-4)/Qn.height))}}function Cu(n){return`\x1B_Ga=t,t=f,f=100,i=${n.id},q=2;${Buffer.from(n.path).toString("base64")}\x1B\\`}function _u(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 Bu(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function xu(n){return`\x1B[38;2;${On(n).join(";")}m`}function ui(n){return`\x1B[48;2;${On(n).join(";")}m`}function Yn(n){return Array.from(n).length}class ie{parts=[];cols;constructor(n){this.cols=n}put(n,r,t=""){return this.parts.push({col:n,text:r,sgr:t}),n+Yn(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+Yn(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?gd:""}`}return n}}function Du(n){return n>=1e6?`${(n/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(n/1000))} KB`}function ad(n,r){if(!r)return Du(n);return r>=1e6?`${(n/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB`:`${Math.round(n/1000)}/${Math.round(r/1000)} KB`}function nc(n){return n.replace(/_\([^)]*\)?$/,"")}function rc(n){return[`${n.reduced?"↓":""}${n.width}×${n.height}`,Math.max(n.width,n.height)<fd?Zn:cn]}function vt(n,r,t,e){let i=[...e.keys??[]],s=e.lead,o=e.right,u=()=>{let f=[...s?[Yn(s[0])]:[],...i.map(([l,a])=>Yn(l)+1+Yn(a))];return(e.badge?Yn(e.badge)+4:0)+f.reduce((l,a)=>l+a,0)+3*Math.max(0,f.length-1)+(o?3+Yn(o[0])+1+Yn(o[1]):0)};while(u()>r)if(i.length>2)i.splice(-2,1);else if(o)o=void 0;else if(i.length>1)i.splice(-2,1);else break;if(s&&u()>r){let f=Math.max(0,Yn(s[0])-(u()-r)-1);s=[`${Array.from(s[0]).slice(0,f).join("")}…`,s[1]]}let c=0;if(e.badge)c=n.put(0,` ${e.badge} `,`\x1B[7;1m${t}`)+2;if([...s?[[s]]:[],...i.map(([f,g])=>[[f,tr],[` ${g}`,cn]])].forEach((f,g)=>{c=n.run(c+(g?3:0),f)}),o)n.right(r,[[o[0],tr],[` ${o[1]}`,cn]])}function md(n,r,t,e,i,s){let{ansi:o,selection:u,cursor:c}=s.colors,h=e<44?3:4;if(e>=56)h=Math.min(7,Math.floor((e+1)/8)-1);let f=t;for(let m=0;m<8;m++)f=(n[r]?.put(f,"▀".repeat(h),xu(o[m]??c)+ui(o[m+8]??c))??f)+1;let g=["❯ ",hr],l=[[["~/code/demo",ee],[" on ",cn],["main",ld],[" +2",hr],[" ~1",Zn]]];if(l.push([g,["git status -sb",""]]),e>=44)l.push([["## ",""],["main",hr],["...",""],["origin/main",Et],[" [ahead 1]",Zn]]);if(l.push([[" M",Et],[" src/main.rs",""]]),l.push([["??",Et],[" notes.md",""]]),l.push([]),e>=44)l.push([g,["ls",""]]),l.push([["docs",ee],[" ",""],["src",ee],[" ",""],["tests",ee],[" Cargo.toml README.md",""]]),l.push([]);l.push([g,["cargo test",""]]),l.push([[" ✓",hr],[" parses config",""]]);let a=[[" ✗",Et],[" renders frame",""]];if(e>=44)a.push([" expected ",cn],["3",hr],[", received ",cn],["2",Et]);l.push(a),l.push([]),l.push([g,["echo ",""],["selected text",ui(u)],[" ",""],[" ",ui(c)]]),l.forEach((m,b)=>{let E=r+2+b;if(E<=i)n[E]?.run(t,m)})}function $d(n,r,t,e,i,s){n[r]?.put(t,`╭${"─".repeat(i-2)}╮`,s);for(let o=r+1;o<r+e-1;o++)n[o]?.put(t,"│",s),n[o]?.put(t+i-1,"│",s);n[r+e-1]?.put(t,`╰${"─".repeat(i-2)}╯`,s)}function ci(n,r=n.site,t=n.siteAnsi){return[` ${r} `,`\x1B[7;${30+t}m`]}function bd(n){return`${pn[Math.floor(n/Sr)]?.name??""} ${n%Sr}`}function wd(n,r,t){let e=[{name:"all",moved:!1},...pn].flatMap((o,u)=>{let c=`${o.name}${o.moved?"*":""}`,h=o.name===t.site?ci(t,c):[` ${c} `,cn];return u?[[" ",""],h]:[h]}),i=e.reduce((o,[u])=>o+Yn(u),0)<=r,s=n.run(0,i?e:[ci(t)]);if(t.asking!==void 0)n.run(s,[[` ${t.asking} was cut off — this network may block it. turn on the unblock proxy? `,Zn],["y",tr],[" turn on ",cn],["n",tr],[" not now",cn]])}function kd(n,r,t,e){if(t.editing!==void 0){let u=n.run(0,[["⌕ ",e],[t.editing,""],["█",e]]),c=t.suggest?.length?" ↑↓ pick enter searches":" enter searches";n.put(u,t.editing?c:` a tag, a post url or an id — ${t.tag||"esc leaves"}`,cn);return}let i=n.run(0,[["⌕ ",e],[t.tag||"nothing yet — / searches",t.tag?"":cn]]),s=yr.filter((u)=>!t.block.includes(u)),o=[t.preset,...t.solo?["solo"]:[],t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(n.put(i,` ${o.join(" ")}`,cn),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,cn]);n.right(r,u)}}function pd(n){if(n.cut==="on")return[[`cut out · ${n.clear}% transparent`,hr]];if(n.cut==="off")return[["opaque · x cuts out",Zn]];if(n.cut==="failed")return[["opaque · no cut-out",Zn]];return[n.clear>0?[`${n.clear}% transparent`,hr]:["opaque",Zn]]}function Au(n){return n.site==="all"?"any site":n.site}function tc(n){if(n.installing!==void 0)return[`installing ${n.palette} ← ${bd(n.installing)}`,Zn];if(n.error)return[n.error,Zn];if(n.waiting!==void 0)return[`${n.slow??n.site} asked to slow down · ${n.waiting}s`,Zn];if(n.fetching)return[`fetching ${n.fetching.id%Sr} · ${ad(n.fetching.got,n.fetching.size)}`,Zn];if(n.cutting!==void 0)return[`cutting out ${n.cutting%Sr}`,Zn];if(n.preparing!==void 0)return[`preparing ${n.preparing%Sr}`,Zn];if(n.saved)return[n.saved,hr];if(n.note)return[n.note,cn];return}function Md(n,r,t,e,i,s){let{perRow:o,rowsVis:u}=Xr(t,e);kd(n[0],t,i,s),wd(n[1],t,i);for(let a=0;a<o*u;a++){let m=i.top*o+a,b=i.tiles[m];if(!b)break;let E=2+Math.floor(a/o)*Qn.height,F=a%o*Qn.pitch,H=m===i.focus;if(H)$d(n,E,F,Qn.height,Qn.pitch-1,s);if(b.thumb)r.push({id:b.key,path:b.thumb,row:E+1,col:F+1,cols:Qn.cols,rows:Qn.rows,z:-1});if(n[E+10]?.run(F+1,[...i.installed.includes(b.key)?[["✓ ",hr]]:[],...i.site==="all"?[["● ",`\x1B[${30+b.siteAnsi}m`]]:[],[String(b.id),H?tr:""],[" ",""],rc(b)]),b.mates.length>0)n[E+10]?.put(F+Qn.cols,"≈",s);let p=b.artist?nc(b.artist):b.owner&&`@${b.owner}`;if(p)n[E+11]?.put(F+1,p.slice(0,Qn.cols-8),cn);let I=[];if(b.score>0)I.push([`★${b.score}`,cn]);if(b.variants>1)I.push([` ×${b.variants}`,s]);if(I.length>0)n[E+11]?.right(F+Qn.cols+1,I)}let c=i.top*o,h=i.tiles.length-(i.top+u)*o,f=[...c>0?[`↑ ${c} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(f.length>0)n[e-2]?.put(0,f.join(" "),cn);if(!i.searching&&i.tiles.length===0&&!i.error)n[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Au(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Au(i)} — tab tries ${i.nextSite}`,cn);let g=n[e-1],l=tc(i);if(i.searching&&i.tiles.length===0&&!l){vt(g,t,s,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",cn],right:["esc","back"]});return}vt(g,t,s,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Ed(n,r,t,e,i,s){let o=i.tiles[i.focus];if(!o)return;let u=i.shown?.id===o.key?i.shown:void 0,c=[ci(i,o.site,o.siteAnsi),[" ",""],[String(o.id),tr],[" ",""],rc(o)];if(o.artist)c.push([` · ${nc(o.artist)}`,""]);if(o.score>0)c.push([` · ★${o.score}`,cn]);if(u)c.push([` · ${Du(u.bytes)}`,cn]);if(c.push([` · ${o.owner}`,cn]),o.origin)c.push([` · ${o.origin}`,cn]);if(u)c.push([" ",""],...pd(u));if(n[0]?.run(0,c),o.mates.length>0)n[0]?.right(t,[["≈ ",s],[o.mates.join(" "),cn]]);if(md(n,3,2,t-4,e-2,i),i.shown)r.push({id:cd+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:e,z:hd});let h=tc(i);vt(n[e-1],t,s,{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 vd={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${pn.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, solo, 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 Fd(n,r,t,e,i){let s=e.panel??0,o=Math.max(...e.settings.map((l)=>l.label.length)),u=Math.max(...e.settings.map((l)=>l.choices.reduce((a,m)=>a+m.length+(l.multi?6:3),0))),c=Math.min(r-2,Math.max(28,o+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,a)=>{let m=n[g+2+a];m.put(f+3,l.label,a===s?tr:cn);let b=f+5+o,E=l.value.split(" ");l.choices.forEach((F,H)=>{let p=E.includes(F),I=l.multi&&a===s&&H===l.cursor?"4;":"",w=l.multi?` ${p?"[x]":"[ ]"} ${F} `:` ${F} `;b=m.put(b,w,p?`\x1B[${I}7;${30+e.siteAnsi}m`:I?`\x1B[4m${cn}`:cn)+1})}),n[g+h-1]?.put(f,`╰${"─".repeat(c-2)}╯`),vt(n[t-1],r,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function Id(n,r,t,e,i){let s=vd[e.mode],o=Math.min(r-2,50),u=s.length+4,c=Math.floor((r-o)/2),h=Math.max(2,Math.floor((t-u)/2));n[h]?.put(c,`╭─ keys ${"─".repeat(o-9)}╮`);for(let f=h+1;f<h+u-1;f++)n[f]?.put(c,`│${" ".repeat(o-2)}│`);s.forEach(([f,g],l)=>{n[h+2+l]?.put(c+3,f,tr),n[h+2+l]?.put(c+13,g.slice(0,o-16))}),n[h+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),vt(n[t-1],r,i,{badge:"KEYS",right:["? esc","close"]})}function Nd(n,r,t){let e=r.suggest??[],i=e.map((u)=>u.count>0?String(u.count):u.palette??"0"),s=Math.max(...e.map((u)=>Yn(u.value))),o=Math.max(7,...i.map(Yn));e.forEach((u,c)=>{let h=c===r.pick,f=n[1+c];f?.run(0,[[h?"▸ ":" ",t],[u.value,h?tr+t:""]]),f?.right(2+s+2+o,[[i[c],cn]])})}function ec(n,r,t){let e=Array.from({length:t},()=>new ie(r)),i=[],s=xu(n.colors.cursor);if(r<jr.cols||t<jr.rows)return e[0]?.put(0,"ttheme find",tr+s),e[1]?.put(0,`needs ${jr.cols}×${jr.rows} — now ${r}×${t}`),e[2]?.put(0,"esc quits",cn),{lines:e.map((o)=>o.render()),images:i};if(n.mode==="try")Ed(e,i,r,t,n,s);else Md(e,i,r,t,n,s);if(n.mode==="grid"&&n.editing!==void 0&&n.suggest?.length){for(let o=1;o<t-1;o++)e[o]=new ie(r);return Nd(e,n,s),{lines:e.map((o)=>o.render()),images:[]}}if(n.help||n.panel!==void 0){let o=n.mode==="try"?i:[];for(let u=0;u<t;u++)e[u]=new ie(r);if(n.help)Id(e,r,t,n,s);else Fd(e,r,t,n,s);return{lines:e.map((u)=>u.render()),images:o}}return{lines:e.map((o)=>o.render()),images:i}}var yd=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Sd=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),Hd=0.04,jd=0.1,Gd=0.05,Od=4096;function Rd(n){return new Set(n.cutouts.split(/\s+/).map((r)=>r.replace(/^~/,"")).filter(Boolean))}function Jd(n,r,t,e=0){let{site:i,post:s}=n,o=new Set(s.tags),u=[...Rd(i)].some((f)=>o.has(f)),c=Math.min(s.width,s.height),h=s.width>0&&s.height>0?s.width/s.height/(r.w/r.h):1;return(s.solo?2:0)+([...yd].some((f)=>o.has(f))?-3:0)+([...Sd].some((f)=>o.has(f))?-1.5:0)+2*Math.min(1,c/r.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(t>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(t):0)+2*e}function se(n,r,t=new Map){let e=new Map;for(let{site:i,post:s}of n)e.set(i,Math.max(e.get(i)??0,s.score));return n.map((i,s)=>({pick:i,at:s,score:Jd(i,r,e.get(i.site)??0,t.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function sc(n){let r=new Map;for(let e of n)r.set(e.site,[...r.get(e.site)??[],e]);let t=[];for(let e=0;t.length<n.length;e++)for(let i of r.values()){let s=i[e];if(s)t.push(s)}return t}function fi(n){let r=n/255;return r<=0.04045?r/12.92:((r+0.055)/1.055)**2.4}function ic(n,r,t){let[e,i,s]=[fi(n),fi(r),fi(t)],o=Math.cbrt(0.4122214708*e+0.5363325363*i+0.0514459929*s),u=Math.cbrt(0.2119034982*e+0.6806995451*i+0.1073969566*s),c=Math.cbrt(0.0883024619*e+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*u-0.0040720468*c,1.9779984951*o-2.428592205*u+0.4505937099*c,0.0259040371*o+0.7827717662*u-0.808675766*c]}function oc(n,r){let t=r.map((o)=>ic(...On(o))).filter(([,o,u])=>Math.hypot(o,u)>=Hd);if(t.length===0)return 0;let e=Math.max(1,Math.floor(Math.sqrt(n.width*n.height/Od))),i=t.map(()=>0),s=0;for(let o=0;o<n.height;o+=e)for(let u=0;u<n.width;u+=e){let c=(o*n.width+u)*4;if(n.data[c+3]<128)continue;s++;let[h,f,g]=ic(n.data[c],n.data[c+1],n.data[c+2]);t.forEach(([l,a,m],b)=>{if(Math.hypot(h-l,f-a,g-m)<jd)i[b]=i[b]+1})}if(s===0)return 0;return i.reduce((o,u)=>o+Math.min(1,u/s/Gd),0)/t.length}import{execFileSync as Kd}from"node:child_process";import{existsSync as gi,mkdirSync as oe,readFileSync as cc,rmSync as hc,writeFileSync as ue}from"node:fs";import{homedir as li}from"node:os";import{dirname as ce,join as Cn}from"node:path";var Ld={ghostty:ct,kitty:ft,alacritty:ut,iterm2:ht},uc="ttheme-default";function Vr(n=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let r=(t,e)=>Kd(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 Yr(n){return n.keepTheme?void 0:Ar(n)}function Ft(n,r){if(!n.terminals.includes("iterm2"))return n;let t=r.read();return t&&!t.startsWith("ttheme-")?{...n,itermBase:t}:n}function It(n,r){if(!n.terminals.includes("iterm2"))return!1;let t=r.read(),e=Yr(n)?uc:t===uc?n.itermBase:void 0;if(!e||e===t)return!1;return r.write(e),!0}function _n(){return process.env.XDG_CONFIG_HOME??Cn(li(),".config")}function fc(n){return Cn(n,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function gc(n){return Cn(n,"ttheme","installed.json")}function fr(n){let r=gc(n);if(!gi(r))throw Error(`nothing installed yet at ${r} — run \`ttheme init\` first`);let t=JSON.parse(cc(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)=>Tt.includes(e)),...t.startup?{startup:t.startup}:{},...t.keepTheme?{keepTheme:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},palettes:t.palettes}}function Nt(n,r){let t=gc(n);oe(ce(t),{recursive:!0}),ue(t,`${JSON.stringify(r,null,2)}
|
|
60
|
+
`)}function di(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}:{},...n.booruSites?{booruSites:n.booruSites}:{},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 lc(n,r){let t=new Map(n.palettes.map((s)=>[s.name,s])),e=r.filter((s)=>!t.has(s));if(e.length>0)throw Error(`not in the catalog: ${e.join(", ")} — \`ttheme list\` shows what is there`);let i=r.flatMap((s)=>{let o=Zu(t.get(s));return o.length>0?[`${s}: ${o.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
|
|
61
61
|
${i.join(`
|
|
62
|
-
`)}`);return n.palettes.filter((
|
|
62
|
+
`)}`);return n.palettes.filter((s)=>r.includes(s.name))}function dc(n,r){return(Ld[n].emit?.(r)??[]).flatMap((t)=>{let[,e,i]=t.path.split("/");return e==="themes"&&i!==void 0?[{file:i,content:t.content}]:[]})}function Ar(n){return n.startup&&n.palettes.includes(n.startup)?n.startup:n.palettes[0]}function Qd(n,r,t){let e=Cn(r,"ttheme");if(n==="ghostty")return{file:Cn(r,"ghostty","config"),body:Nu(e,t)};if(n==="kitty")return{file:Cn(r,"kitty","kitty.conf"),body:ju(t)};let i=t?Cn(r,"alacritty","themes",`${t}.toml`):void 0;return{file:Cn(r,"alacritty","alacritty.toml"),body:Gu(i)}}function ac(n,r,t,e,i){let s=Ur(n),o=t.map((h)=>di(h,r)),u=new Map;for(let h of o){let f=Po(s,h.name,i);if(f)u.set(h.name,f)}let c=new Set(Wr(t).map((h)=>h.name));return ks(o.filter((h)=>c.has(h.name)),u,o.find((h)=>h.name===Yr(e)),e.itermBase)}function zr(n,r=li()){let t=fr(n);if(!t.terminals.includes("iterm2"))return;let e=Pn(n),i=fc(r);oe(ce(i),{recursive:!0}),ue(i,ac(n,e,lc(e,t.palettes),t,r))}function yt(n,r,t,e=li()){let i=lc(r,t.palettes),s=[],o=(h,f)=>{oe(ce(h),{recursive:!0}),ue(h,f),s.push(h)},u=Yr(t);for(let h of t.terminals){if(h==="iterm2"){o(fc(e),ac(n,r,i,t,e));continue}for(let a of i)for(let{file:m,content:b}of dc(h,di(a,r)))o(Cn(n,h,"themes",m),b);let{file:f,body:g}=Qd(h,n,u),l=gi(f)?cc(f,"utf8"):"";if(h==="alacritty"&&l!==""&&!l.includes("# ttheme begin"))continue;oe(ce(f),{recursive:!0}),ue(f,Ct(l,g)),s.push(f)}let c=Cn(n,"ttheme","palettes.zsh");return o(c,ti(i,u,t.terminals)),hc(`${c}.zwc`,{force:!0}),s}function ai(n,r,t,e){let i=[];for(let s of t)for(let o of r.palettes.filter((u)=>e.includes(u.name)))for(let{file:u}of dc(s,di(o,r))){let c=Cn(n,s,"themes",u);if(gi(c))hc(c,{force:!0}),i.push(c)}return i}import{mkdirSync as kc,readFileSync as pc,writeFileSync as Mc}from"node:fs";import{dirname as Ec}from"node:path";import{isMainThread as Ud,parentPort as vc,Worker as Wd}from"node:worker_threads";var Pd=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,Zd=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function mi(n){let r=/(\d+)_p(\d+)/.exec(n.source);return[...n.md5?[`md5:${n.md5}`]:[],...r&&n.source.includes("pximg")?[`pixiv:${r[1]}_p${r[2]}`]:[]]}function mc(n,r){let t=Pd.exec(r.source)?.[1]?.toLowerCase();return[`post:${n.key}:${r.id}`,...r.md5?[`md5:${r.md5}`]:[],...t&&t!==r.md5?[`md5:${t}`]:[],...Zd.flatMap(([e,i])=>{let s=e.exec(r.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...r.family?[`family:${n.key}:${r.family}`]:[]]}function $c(n,r){let t=n.owner||n.artist;return t!==""&&t===(r.owner||r.artist)&&n.width===r.width&&n.height===r.height}function bc(n){let e=[];for(let s=0;s<8;s++){let o=Math.floor(s*n.height/8),u=Math.max(o+1,Math.floor((s+1)*n.height/8));for(let c=0;c<9;c++){let h=Math.floor(c*n.width/9),f=Math.max(h+1,Math.floor((c+1)*n.width/9)),g=0;for(let l=o;l<u;l++)for(let a=h;a<f;a++){let m=(l*n.width+a)*4,b=n.data[m+3]/255,E=0.299*n.data[m]+0.587*n.data[m+1]+0.114*n.data[m+2];g+=E*b+255*(1-b)}e.push(g/((f-h)*(u-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(e[s*9+o]>e[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function qd(n,r){let t=BigInt(`0x${n}`)^BigInt(`0x${r}`),e=0;while(t>0n)e+=Number(t&1n),t>>=1n;return e}function wc(n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return!1;return Math.abs(Math.log(n.width/n.height/(r.width/r.height)))<0.01&&qd(n.hash,r.hash)<=2}var Xd={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Vd(n){let r=Io(new Uint8Array(pc(n.from)),Te);if(n.job==="backdrop")return Ao(n.home,n.colors,n.tone,r,{...n.origin,bytes:new Uint8Array(pc(n.source))},n),0;if(n.job==="match")return{match:oc(r,n.colors),hash:bc(r)};if(n.job==="thumb")return kc(Ec(n.to),{recursive:!0}),Mc(n.to,Zr(yo(r,n.width,n.height))),0;let t=lt(r);return kc(Ec(n.to),{recursive:!0}),Mc(n.to,Zr(Qo(r,n.colors,n.tone,n.width,n.height))),t}function Yd(n){n.on("message",(r)=>{try{n.postMessage({id:r.id,value:Vd(r)})}catch(t){n.postMessage({id:r.id,error:t instanceof Error?t.message:String(t)})}})}class Fc{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 Wd(import.meta.filename);n.unref(),n.on("message",({id:t,value:e,error:i})=>{let s=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)n.unref();if(i!==void 0)s?.no(Error(i));else s?.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 $i{lines=new Map;run(n){let r=Xd[n.job],t=this.lines.get(r);if(!t)t=new Fc,this.lines.set(r,t);return t.send(n)}close(){for(let n of this.lines.values())n.close();this.lines.clear()}}if(!Ud&&vc)Yd(vc);import{connect as Ad,createServer as zd}from"node:net";var Td=20,Ic=22;function bi(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 Cd(n,r=Td){let t=n.subarray(5);if(n[0]!==Ic||t.length<2)return[n];let e=Math.max(1,Math.min(r,t.length-1)),i=(s)=>bi([Uint8Array.from([n[0],n[1],n[2],s.length>>8,s.length&255]),s]);return[i(t.subarray(0,e)),i(t.subarray(e))]}function _d(n,r,t,e){let i=Ad(t,r,()=>{i.setNoDelay(!0),n.write(`HTTP/1.1 200 Connection Established\r
|
|
63
63
|
\r
|
|
64
|
-
`);let
|
|
64
|
+
`);let s=e,o=!1,u=(c)=>{if(o){i.write(c);return}if(s=bi([s,c]),s.length<5)return;let h=s[3]*256+s[4];if(s[0]!==Ic){o=!0,i.write(s);return}if(s.length<5+h)return;o=!0;let[f,g]=Cd(s.subarray(0,5+h));i.write(f),setTimeout(()=>{if(g)i.write(g);i.write(s.subarray(5+h))},10)};if(n.on("data",u),s.length>0){let c=s;s=new Uint8Array(0),u(c)}i.pipe(n)});i.on("error",()=>n.destroy()),i.on("close",()=>n.destroy()),n.on("error",()=>i.destroy()),n.on("close",()=>i.destroy())}function Bd(n){n.setNoDelay(!0);let r=new Uint8Array(0),t=(e)=>{r=bi([r,e]);let i=Buffer.from(r).toString("latin1"),s=i.indexOf(`\r
|
|
65
65
|
\r
|
|
66
|
-
`);if(
|
|
66
|
+
`);if(s===-1)return;n.off("data",t);let o=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!o){n.end(`HTTP/1.1 405 Method Not Allowed\r
|
|
67
67
|
\r
|
|
68
|
-
`);return}
|
|
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
|
-
`),
|
|
71
|
-
`),
|
|
72
|
-
`),0}if(r==="drop"){let{key:e,left:i}=
|
|
73
|
-
`),0}if(r==="tuned")return
|
|
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===
|
|
75
|
-
`){if(
|
|
76
|
-
`){if(i&&
|
|
77
|
-
`)}var
|
|
78
|
-
`),
|
|
68
|
+
`);return}_d(n,o[1],Number(o[2]),r.subarray(s+4))};n.on("data",t),n.on("error",()=>n.destroy())}function Nc(){let n=zd(Bd);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 Cr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:$t,multi:{read:At}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:yr,multi:{read:zt,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...oi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function ta(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 ea=["fit","newest","score"];function Sc(n){return ea.find((r)=>r===n)??"fit"}function ia(n){return n.length>=2&&!/^\d+$/.test(n)&&!n.includes("://")&&!/^[\w.]+:\d+$/.test(n)}var Hc=12,sa=4,oa=150,jc=12,ua=2,ca=150,ha=30,fa=1280,Gc=2,ga=3,la=8;function ki(n,r){return{key:n,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:r}}function he(n){if(!(n instanceof Error))return String(n);if(n instanceof AggregateError&&n.errors[0])return he(n.errors[0]);if(n.cause)return he(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 pi(n,r){return`${n}: ${he(r)}`}function Oc(n){return n.width*n.height}function Rc(n){return`${n.id}-${xd("sha1").update(n.preview).digest("hex").slice(0,8)}`}function da(n){let r=n.lastIndexOf("\x1B");return r!==-1&&/^\[?[0-9;]*$/.test(n.slice(r+1))}function Mi(n,r){try{return JSON.parse(Lc(gr(pr(n),r),"utf8"))}catch{return{}}}function Ei(n,r,t){vi(pr(n),{recursive:!0}),Fi(gr(pr(n),r),`${JSON.stringify(t)}
|
|
69
|
+
`)}class Qc{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;looking=new Map;looked=new Map;matched=new Map;aheading=!1;pages=new Map;tab=0;values=new Map(Cr.map((n)=>[n.name,ta(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 $i;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";probeWait;done;dirty=!1;unblock=!1;scratch=Dd(gr(ra(),"ttheme-find-"));home;catalog;entry;constructor(n,r,t,e){this.home=n,this.catalog=r,this.entry=t,this.tone=Xt(t,t.signatureSlots),this.view={palette:t.name,tag:e,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Sc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:At(this.setting("TTHEME_FIND_RATING")),block:zt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:Cr.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:[],installed:[],checked:0,total:0,searching:e!=="",focus:0,top:0,mode:"grid",help:!1,editing:e===""?"":void 0},this.board=ki(this.boardKey,e!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:pn[this.tab-1]}get sites(){return this.site?[this.site]:pn}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??sa}get nextTabName(){let n=(this.tab+1)%(pn.length+1);return n===0?"all":pn[n-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(n){return this.values.get(n)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(n,r,t){return gr(pr(n),"orig",`${r}.${t}`)}previewPath(n){return gr(pr(n.site),"thumb",`${Rc(n.post)}.${bt(n.post.preview)}`)}tileOf(n,r){let{site:t,post:e}=n,i=rr(t,e.id),s=kt(e)??e;return{id:e.id,key:i,site:t.name,siteAnsi:t.ansi,width:s.width,height:s.height,reduced:s!==e,owner:e.owner,artist:e.artist,score:e.score,variants:r,origin:_e(e.source),mates:this.owners.get(t.key)?.get(e.owner)??[],thumb:this.thumbPath.get(i)}}show(){let n=this.view,r=this.board;n.tiles=r.groups.flatMap((t)=>t.open?t.posts.map((e)=>this.tileOf(e,0)):[this.tileOf(t.posts[0],t.posts.length)]),n.checked=r.checked,n.total=r.total,n.searching=r.searching,n.note=r.note,n.focus=Math.max(0,Math.min(r.focus,n.tiles.length-1)),n.top=r.top}syncSite(){let n=this.view;n.site=this.tabName,n.siteAnsi=this.tabAnsi,n.nextSite=this.nextTabName}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((o)=>{this.done=o}),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 s=await t;return this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),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(),wi(this.scratch,{recursive:!0,force:!0}),lu(),s}write(n){process.stdout.write(n)}get saved(){return this.view.saved}finish(n){this.done?.(n===2&&this.saved?0: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(Tu)})}onData=(n)=>{this.input+=n.toString("utf8");for(let r=hi(this.input);r;r=hi(this.input))this.input=r.rest,this.probeWait?.(r.cell);if(this.probeWait)return;if(clearTimeout(this.partial),da(this.input)){this.partial=setTimeout(this.flushKeys,ha);return}this.flushKeys()};flushKeys=()=>{let n=zu(this.input);this.input="";for(let r of n)this.key(r)};onClock=()=>{let n=this.sites.reduce((e,i)=>wr(i)>wr(e)?i:e),r=Math.ceil((wr(n)-Date.now())/1000),t=r>0?r:void 0;if(t!==this.view.waiting)this.view.waiting=t,this.view.slow=n.name,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.asking!==void 0){this.askKey(n);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<jr.cols||this.rows<jr.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}=Xr(this.cols,this.rows),s={left:-1,right:1,up:-t,down:t,pgup:-t*e,pgdn:t*e,home:-r.focus,end:r.tiles.length}[n];if(s!==void 0){this.focus(r.focus+s);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.tab=(this.tab+1)%(pn.length+1),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 s=e.choices.indexOf(e.value);e.value=e.choices[(s+i+e.choices.length)%e.choices.length]}this.draw();return}if(n===" "&&e?.multi){let i=e.value.split(" "),s=e.choices.filter((u,c)=>c===e.cursor?!i.includes(u):i.includes(u)),o=e.multi.none;if(s.length>0||o!==void 0)e.value=s.length>0?s.join(" "):o,this.draw();return}if(n==="esc"){r.settings.forEach((i,s)=>{i.value=this.setting(Cr[s]?.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=Cr.map((e)=>this.setting(e.name));n.settings.forEach((e,i)=>{let s=Cr[i];if(s)this.values.set(s.name,e.value)});let t=Cr.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=zt(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=Sc(this.setting("TTHEME_FIND_ORDER")),n.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,n.shown=void 0,n.mode="grid",this.search()}save(n){this.store(n.map((r)=>[r.name,this.setting(r.name)]))}store(n){let r=gr(this.home,"ttheme","config.zsh");try{let t=Tr(r)?Lc(r,"utf8"):"";return Fi(r,n.reduce((e,[i,s])=>Bt(e,i,s),t)),!0}catch(t){return this.view.error=t instanceof Error?t.message:String(t),!1}}askKey(n){let r=this.view;if(n==="y"){if(r.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(n==="n"||n==="esc")r.asking=void 0,this.draw()}editKey(n){let r=this.view,t=r.editing??"",e=r.suggest??[];if((n==="up"||n==="down")&&e.length>0){let i=r.pick??-1,s=n==="down"?Math.min(e.length-1,i+1):i-1;r.pick=s<0?void 0:s,this.draw();return}if(n==="esc"||n==="enter")this.quietSuggest();if(n==="esc"){if(r.editing=void 0,r.tag===""){this.finish(2);return}this.draw();return}if(n==="enter"){let i=r.pick===void 0?void 0:e[r.pick],s=i?t.replace(/\S*$/,i.value):t;if(r.editing=void 0,r.suggest=void 0,r.pick=void 0,s.trim()){this.commit(s.trim());return}if(r.tag===""){this.finish(2);return}this.draw();return}if(n==="backspace"){r.editing=t.slice(0,-1),this.suggest(),this.draw();return}if(n.length===1&&n>=" ")r.editing=t+n,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let n=this.view;n.pick=void 0;let r=/\S*$/.exec(n.editing??"")?.[0]??"";if(!ia(r)){n.suggest=void 0;return}let t=[...new Map(Uu(this.catalog.palettes,this.entry,r).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,ga);n.suggest=t.length>0?t:void 0;let e=new AbortController;this.suggesting=e,this.suggestTimer=setTimeout(async()=>{try{let i=await bu(r,AbortSignal.any([this.signal,e.signal]));if(this.suggesting===e&&n.editing!==void 0){let s=new Map(i.map((u)=>[u.value,u.count])),o=new Set(t.map((u)=>u.value));n.suggest=[...t.map((u)=>({...u,count:s.get(u.value)??0})),...i.filter((u)=>!o.has(u.value))].slice(0,la),n.pick=n.pick!==void 0&&n.pick<t.length?n.pick:void 0,this.draw()}}catch{}},oa)}async commit(n){let r=ou(n,this.site??pn[0]);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.tab=pn.indexOf(n)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let e=ki(`${n.key}|post:${r}`,!0);this.board=e,this.boards.set(e.key,e),this.show(),this.draw();try{let i=await Be(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{let s={site:n,post:i};this.posts.set(rr(n,i.id),s),e.groups=[{posts:[s],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(s),this.thumbs(),this.view.mode="try"}if(this.show(),i)this.select();this.draw()}catch(i){this.fail(t,i,n)}}async turn(){this.fetch?.abort(),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(rr(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}r+=e}}openPage(){let n=this.view.tiles[this.view.focus],r=n&&this.posts.get(n.key);if(!r)return;let t=process.platform==="darwin"?"open":"xdg-open";try{Kc(t,[r.site.pageUrl(r.post.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}=Xr(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===this.entry.booru?Wu(this.entry,n.key):[r.tag];if(t.length===0)return;let e=t.length>1,i=r.preset==="cutouts"?n.cutouts:"",s=e&&i.includes("~"),o=[e?t.map((h)=>`~${h}`).join(" "):t[0],n.rate(this.view.rating),s?"":i,r.order==="score"?n.best:""].filter(Boolean),u=[],c=[];for(let h of o)if(Ce([...u,h].join(" "))<=n.tagBudget)u.push(h);else c.push(h);return{tags:u.join(" "),notes:[...c.length>0?[`${n.name} takes ${n.tagBudget} tags — ${c.join(" ")} left out`]:[],...s?[`${n.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let n=++this.gen,r=ki(this.boardKey,!0);this.board=r,this.boards.set(r.key,r),this.view.error=void 0;let t=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),e=this.sites.filter((s)=>!t.some((o)=>o.site===s)),i=[...t.flatMap(({notes:s})=>s),...e.length>0?[`${this.entry.name} has no tag on ${e.map((s)=>s.name).join(", ")}`]:[]];if(r.note=i.length>0?i.join(" · "):void 0,t.length===0)r.searching=!1;this.show(),this.draw(),this.tally(n,r,t);try{let s=await Promise.all(t.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(n!==this.gen)return;r.sources=s.flatMap(({plan:{site:o,tags:u},owners:c})=>[...Ce(u)+1<=o.tagBudget?[...c.keys()].map((h)=>({site:o,tags:`${u} user:${h}`,page:0,done:!1})):[],{site:o,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(s){this.fail(n,s)}}async tally(n,r,t){let e=await Promise.allSettled(t.map(({site:i,tags:s})=>au(i,s,this.signal)));if(n===this.gen)r.total=e.reduce((i,s)=>i+(s.status==="fulfilled"?s.value:0),0),this.show(),this.draw()}fail(n,r,t=this.site){if(n!==this.gen||this.signal.aborted)return;this.board.error=pi(t?.name??this.tabName,r),this.board.searching=!1,this.view.error=this.board.error,this.offer(t,r),this.show(),this.draw()}offer(n,r){if(n&&!this.view.unblocked&&Pc()&&he(r)==="ECONNRESET")this.view.asking=n.name}drop(n,r,t){for(let e of n.sources)if(e.site===r)e.done=!0;n.note=[n.note,pi(r.name,t)].filter(Boolean).join(" · "),this.offer(r,t)}wants(){let{perRow:n,rowsVis:r}=Xr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+r+Gc)*n}need(){let{perRow:n,rowsVis:r}=Xr(this.cols,this.rows);return(r+Gc)*n}live(n){return this.boards.get(n.key)===n}page(n,r,t){let e=`${n.key}|${r}|${t}`,i=this.pages.get(e);if(!i)i=du(n,r,t,this.signal).then((s)=>this.borrow(s)),this.pages.set(e,i),i.catch(()=>this.pages.delete(e));return i}async borrow(n){let r=n.filter((t)=>t.solo===void 0&&t.md5!=="");if(r.length>0)try{mu(r,await $u(r.map((t)=>t.md5),this.signal))}catch{}return n}async round(n){let r=pn.flatMap((u)=>{let c=n.sources.find((h)=>h.site===u&&!h.done);return c?[c]:[]}),t=await Promise.all(r.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(n.sources.every((h)=>h.site===u.site)||this.signal.aborted)throw c;return this.drop(n,u.site,c),{source:u,posts:void 0}}}));if(!this.live(n))return;let e=[];for(let{source:u,posts:c}of t){if(!c)continue;u.page++,u.done=c.length<Nr;let h=n.last.get(u);for(let f of c){let g=h&&$c(h.post,f)?h.set:`set:${u.site.key}:${f.id}`;h={post:f,set:g};let l=rr(u.site,f.id);if(n.seen.has(l))continue;n.seen.add(l);let a={site:u.site,post:f};if(this.eligible(a))n.kin.set(a,[g,...mc(u.site,f)]),e.push(a);else n.checked++}if(h)n.last.set(u,h)}let i=this.dedupe(n,e),s=++n.rounds,o;if(this.view.order!=="fit")o=r.length>1?sc(i):i;else{let u=se(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(n))return;o=[...se(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of o)n.roundOf.set(u,s);n.queue.push(...o),this.ahead(n)}ahead(n){if(this.aheading||this.view.order!=="fit"||!this.live(n))return;let r=n.queue.slice(0,this.need()).filter((t)=>!this.looking.has(rr(t.site,t.post.id)));if(r.length===0)return;this.aheading=!0,this.looks(r).then(()=>{this.aheading=!1;for(let t of new Set(r.map((e)=>n.roundOf.get(e)??0)))this.resort(n,t);this.ahead(n)})}resort(n,r){let t=n.queue.flatMap((i,s)=>n.roundOf.get(i)===r?[s]:[]),e=se(t.map((i)=>n.queue[i]),this.frame(),this.matched);t.forEach((i,s)=>{n.queue[i]=e[s]})}dedupe(n,r){let t=[];for(let e of r){let i=mi(e.post),s=i.map((u)=>n.same.get(u)).find(Boolean);if(!s){for(let u of i)n.same.set(u,e);t.push(e);continue}if(n.checked++,Oc(e.post)<=Oc(s.post))continue;for(let u of[...i,...mi(s.post)])n.same.set(u,e);let o=t.indexOf(s);if(o>=0){t[o]=e;continue}this.replace(n,s,e)}return t}replace(n,r,t){n.roundOf.set(t,n.roundOf.get(r)??0);let e=n.queue.indexOf(r);if(e>=0){n.queue[e]=t;return}for(let i of n.groups){let s=i.posts.indexOf(r);if(s>=0){i.posts[s]=t,this.posts.set(rr(t.site,t.post.id),t),this.thumbQueue.push(t),this.thumbs();return}}}async looks(n){let r=0;await Promise.all(Array.from({length:jc},async()=>{while(r<n.length)await this.look(n[r++])}))}look(n){let r=rr(n.site,n.post.id),t=this.looking.get(r);if(!t)t=(async()=>{let e=this.previewPath(n);await this.cached(n.site,e,n.post.preview);let i=await this.renders.run({job:"match",from:e,colors:this.entry.signature});return this.looked.set(r,i),this.matched.set(n.post,i.match),i})().catch(()=>{return}),this.looking.set(r,t);return t}async pump(){let n=this.gen,r=this.board;if(this.pumping===n||r.sources.length===0)return;this.pumping=n;let t=[],e;try{r.searching=!0;while(n===this.gen){while(t.length<Hc&&r.queue.length>0&&this.wants()){let o=r.queue.shift();t.push({pick:o,passed:this.vet(o)})}if(this.ahead(r),!e&&r.queue.length<Hc&&r.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(r).then(()=>{if(e===o)e=void 0});o.catch(()=>{}),e=o}let i=t.shift();if(!i){if(!e)break;await e,this.show(),this.draw();continue}let s=await i.passed;if(n!==this.gen)return;if(r.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(n===this.gen)r.searching=!1,this.show(),this.draw()}catch(i){this.fail(n,i)}finally{if(this.saveProbes(),this.pumping===n)this.pumping=0}}eligible({site:n,post:r}){let t=kt(r);if(!hu(n,r,this.view.rating)||cu(r,this.view.block).length>0||!t)return!1;if(this.view.solo&&r.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(t.ext):r.ext==="png"}async vet(n){let[r]=await Promise.all([this.passes(n),this.look(n)]);return r}async passes({site:n,post:r}){return this.view.preset==="all"||n.vouched||this.transparent(n,r)}probes(n){let r=this.probed.get(n.key);if(!r)r=Mi(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 wu(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=pn.find((t)=>t.key===n);if(r)Ei(r,"probes.json",this.probes(r))}this.unsaved.clear()}admit(n){let{site:r,post:t}=n,e=this.board,i=rr(r,t.id);this.posts.set(i,n);let s=e.kin.get(n)??[],o=this.looked.get(i),u=o&&{hash:o.hash,width:t.width,height:t.height},c=this.view.sets==="fold"?this.kindred(e,s,u):void 0;if(c){if(c.posts.push(n),this.register(e,c,s,u),c.open)this.thumbQueue.push(n),this.thumbs();return}let h={posts:[n],open:!1};e.groups.push(h),this.register(e,h,s,u),this.thumbQueue.push(n),this.thumbs()}kindred(n,r,t){for(let e of r){let i=n.kindred.get(e);if(i)return i}return t&&n.shapes.find((e)=>wc(e.shape,t))?.group}register(n,r,t,e){for(let i of t)if(!n.kindred.has(i))n.kindred.set(i,r);if(e)n.shapes.push({shape:e,group:r})}async mateOwners(n){let r=this.owners.get(n.key);if(r)return r;let t=zo(this.home),e=Mi(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}]:[]}),s=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 Be(n,c.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let c of s)if(c)e[c.id]=c.owner,o.set(c.name,c.owner);Ei(n,"owners.json",e);let u=fu(o);return this.owners.set(n.key,u),u}async cached(n,r,t,e){if(Tr(r))return na(r).size;let i=this.inflight.get(r);if(i)return i;let s=(async()=>{let o=await ku(n,t,this.signal,e);return vi(yc(r),{recursive:!0}),Fi(r,o),o.length})();this.inflight.set(r,s);try{return await s}finally{this.inflight.delete(r)}}thumbs(){while(this.thumbing<jc&&this.thumbQueue.length>0){let n=this.thumbQueue.shift();this.thumbing++,this.thumb(n).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(n){let{site:r,post:t}=n,e=Qn.cols*this.cell.w,i=Qn.rows*this.cell.h,s=gr(pr(r),"tile",`${Rc(t)}-${e}x${i}.png`);if(!Tr(s)){let o=this.previewPath(n);await this.cached(r,o,t.preview),await this.renders.run({job:"thumb",from:o,to:s,width:e,height:i})}this.thumbPath.set(rr(r,t.id),s),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?.key===r.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(r),ca),this.draw()}async load(n){let r=this.view,t=this.posts.get(n.key),e=t&&kt(t.post);if(!t||!e)return;let{site:i}=t,s=this.board,o=new AbortController;this.fetch=o;try{let u=this.origPath(i,n.id,e.ext);if(!Tr(u))r.fetching={id:n.key,got:0,size:0},this.draw();let c=await this.cached(i,u,e.file,(g,l)=>{if(r.fetching?.id===n.key)r.fetching={id:n.key,got:g,size:l},this.draw()});if(o.signal.aborted)return;if(r.fetching=void 0,s!==this.board)return;let h={site:i,id:n.id,key:n.key,path:u,ext:e.ext,size:c,using:"plain",failed:!1};r.preparing=n.key,this.flush();let f=await this.render(h,"plain");if(o.signal.aborted||s!==this.board)return;if(f.clear===0&&oi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(r.preparing=void 0,r.cutting=n.key,this.flush(),h.cut=await this.cutOut(i,n.id,u,o.signal),o.signal.aborted||s!==this.board)return;if(r.cutting=void 0,h.cut){r.preparing=n.key,this.flush();let g=await this.render(h,"cut").catch(()=>{return});if(o.signal.aborted||s!==this.board)return;if(g&&Xu(g.clear))h.using="cut";else wi(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,r.tiles[r.focus]?.key===n.key)await this.present();this.preload()}catch(u){if(!o.signal.aborted&&!this.signal.aborted)r.error=pi(i.name,u)}finally{if(r.fetching?.id===n.key)r.fetching=void 0;if(r.preparing===n.key)r.preparing=void 0;if(r.cutting===n.key)r.cutting=void 0;this.draw()}}async cutOut(n,r,t,e){let i=gr(pr(n),"cut",`${r}.png`);if(Tr(i))return i;try{return vi(yc(i),{recursive:!0}),await Vu(t,i,e),i}catch{wi(i,{force:!0});return}}swap(){let n=this.current;if(!n?.cut||this.view.shown?.id!==n.key)return;n.using=n.using==="cut"?"plain":"cut",this.reveal()}preload(){let n=this.view;if(n.mode!=="try")return;for(let r of[n.focus+this.direction,n.focus-this.direction]){if(this.prefetching>=ua)return;let t=n.tiles[r],e=t&&this.posts.get(t.key),i=e&&kt(e.post);if(!e||!i)continue;let{site:s,post:o}=e,u=this.origPath(s,o.id,i.ext);this.prefetching++,this.cached(s,u,i.file).then(()=>this.render({site:s,id:o.id,key:t.key,path:u,ext:i.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,fa),s=Math.max(1,Math.round(e*i/t)),o=gr(this.scratch,`${n.site.key}-${n.id}${r==="cut"?"c":""}-${i}x${s}.png`),u=`${n.site.key}:${n.id}:${r}`,c=this.clarity.get(u);if(c!==void 0&&Tr(o))return{clear:c,path:o};let h=await this.renders.run({job:"show",from:r==="cut"?n.cut:n.path,to:o,width:i,height:s,colors:this.entry,tone:this.tone});return this.clarity.set(u,h),{clear:h,path:o}}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.key,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?.key,this.flush(),this.present().catch((r)=>{n.error=r instanceof Error?r.message:String(r)}).finally(()=>{if(n.preparing===this.current?.key)n.preparing=void 0;this.draw()})}async install(){let n=this.view,r=n.tiles[n.focus],t=this.current;if(!r||t?.key!==r.key||n.preparing!==void 0||n.shown?.id!==r.key)return;n.installing=r.key,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)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let e=Mi(t.site,"owners.json");e[t.id]=this.posts.get(t.key)?.post.owner??"",Ei(t.site,"owners.json",e),zr(this.home),n.saved=`background · ${this.entry.name} ← ${t.site.name} ${t.id}`,n.installed.push(r.key),this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid"}catch(e){n.error=e instanceof Error?e.message:String(e)}n.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let n=ec(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+=Cu(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+=_u(e),this.placed.set(e.id,i)}for(let e of this.sent.keys())if(!t.has(e))r+=Bu(e),this.sent.delete(e),this.placed.delete(e);this.write(`${r}\x1B[?2026l`)}}function Pc(){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 Jc(){if(!Pc())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
70
|
+
`),1;let n=await Nc(),r=Kc(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}`,NO_PROXY:[process.env.NO_PROXY,uu()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(n.port)}}),t=await new Promise((e)=>r.on("exit",(i)=>e(i??1)));return n.close(),t}async function Zc(n){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Jc();let r=_n(),t=Pn(r),e=te(t.palettes,n);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("ttheme find needs a terminal");let i=new Qc(r,t,e,e.booru??""),s=await i.run(),o=i.unblock?await Jc():s;if(i.saved&&o!==0)return process.stderr.write(`${i.saved}
|
|
71
|
+
`),0;return o}function qc(n,r){let t=_n();if(te(Pn(t).palettes,n),r==="next"||r==="prev"){let{key:e,at:i,of:s}=Vo(t,n,r==="next"?1:-1);return zr(t),process.stderr.write(`background · ${n} ${i}/${s} ${e}
|
|
72
|
+
`),0}if(r==="drop"){let{key:e,left:i}=Yo(t,n);return zr(t),process.stderr.write(`background · ${n} removed ${e??"the picture"} · ${i} left
|
|
73
|
+
`),0}if(r==="tuned")return zr(t),0;throw Error(`unknown image action ${r} — next, prev, drop or tuned`)}import{chmodSync as am,copyFileSync as mm,existsSync as dr,mkdirSync as Ai,readdirSync as $m,readFileSync as jt,rmSync as qh,writeFileSync as Uh}from"node:fs";import{homedir as bm}from"node:os";import{dirname as Ht,join as wn}from"node:path";import{styleText as Gi}from"node:util";import{stdout as ih,stdin as Ha}from"node:process";import ja from"node:readline";var Uc=(()=>{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}})(),Wc=(n)=>{return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510},Xc=(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 aa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ma=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Vc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,$a=/\t{1,1000}/y,Yc=/[\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,ba=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wa=/\p{M}+/gu,ka={limit:1/0,ellipsis:""},Ac=(n,r={},t={})=>{let e=r.limit??1/0,i=r.ellipsis??"",s=r?.ellipsisWidth??(i?Ac(i,ka,t).width:0),o=0,u=t.controlWidth??0,c=t.tabWidth??8,h=t.emojiWidth??2,f=2,g=t.regularWidth??1,l=t.wideWidth??2,a=[[ba,g],[aa,0],[ma,u],[$a,c],[Yc,h],[Vc,l]],m=0,b=0,E=n.length,F=0,H=!1,p=E,I=Math.max(0,e-s),w=0,O=0,k=0,G=0;n:while(!0){if(O>w||b>=E&&b>m){let S=n.slice(w,O)||n.slice(m,b);F=0;for(let K of S.replaceAll(wa,"")){let R=K.codePointAt(0)||0;if(Wc(R))G=2;else if(Xc(R))G=l;else G=g;if(k+G>I)p=Math.min(p,Math.max(w,m)+F);if(k+G>e){H=!0;break n}F+=K.length,k+=G}w=O=0}if(b>=E)break n;for(let S=0,K=a.length;S<K;S++){let[R,z]=a[S];if(R.lastIndex=b,R.test(n)){if(F=R===Vc?Uc(n.slice(b,R.lastIndex)):R===Yc?1:R.lastIndex-b,G=F*z,k+G>I)p=Math.min(p,b+Math.floor((I-k)/z));if(k+G>e){H=!0;break n}k+=G,w=m,O=b,b=m=R.lastIndex;continue n}}b+=1}return{width:H?I:k,index:H?p:E,truncated:H,ellipsed:H&&e>=s}},zc=Ac;var pa={limit:1/0,ellipsis:"",ellipsisWidth:0},Ma=(n,r={})=>{return zc(n,pa,r).width},Kn=Ma;var fe="\x1B",xc="",Ea=39,Ni="\x07",Dc="[",va="]",nh="m",yi=`${va}8;;`,Tc=new RegExp(`(?:\\${Dc}(?<code>\\d+)m|\\${yi}(?<uri>.*)${Ni})`,"y"),Cc=(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},_c=(n)=>`${fe}${Dc}${n}${nh}`,Bc=(n)=>`${fe}${yi}${n}${Ni}`,Ii=(n,r,t)=>{let e=r[Symbol.iterator](),i=!1,s=!1,o=n.at(-1),u=o===void 0?0:Kn(o),c=e.next(),h=e.next(),f=0;while(!c.done){let g=c.value,l=Kn(g);if(u+l<=t)n[n.length-1]+=g;else n.push(g),u=0;if(g===fe||g===xc)i=!0,s=r.startsWith(yi,f+1);if(i){if(s){if(g===Ni)i=!1,s=!1}else if(g===nh)i=!1}else if(u+=l,u===t&&!h.done)n.push(""),u=0;c=h,h=e.next(),f+=g.length}if(o=n.at(-1),!u&&o!==void 0&&o.length&&n.length>1)n[n.length-2]+=n.pop()},Fa=(n)=>{let r=n.split(" "),t=r.length;while(t){if(Kn(r[t-1]))break;t--}if(t===r.length)return n;return r.slice(0,t).join(" ")+r.slice(t).join("")},Ia=(n,r,t={})=>{if(t.trim!==!1&&n.trim()==="")return"";let e="",i,s,o=n.split(" "),u=[""],c=0;for(let g=0;g<o.length;g++){let l=o[g];if(t.trim!==!1){let m=u.at(-1)??"",b=m.trimStart();if(m.length!==b.length)u[u.length-1]=b,c=Kn(b)}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 a=Kn(l);if(t.hard&&a>r){let m=r-c,b=1+Math.floor((a-m-1)/r);if(Math.floor((a-1)/r)<b)u.push("");Ii(u,l,r),c=Kn(u.at(-1)??"");continue}if(c+a>r&&c&&a){if(t.wordWrap===!1&&c<r){Ii(u,l,r),c=Kn(u.at(-1)??"");continue}u.push(""),c=0}if(c+a>r&&t.wordWrap===!1){Ii(u,l,r),c=Kn(u.at(-1)??"");continue}u[u.length-1]+=l,c+=a}if(t.trim!==!1)u=u.map((g)=>Fa(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===fe||l===xc){Tc.lastIndex=g+1;let m=Tc.exec(h)?.groups;if(m?.code!==void 0){let b=Number.parseFloat(m.code);i=b===Ea?void 0:b}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(h[g+1]===`
|
|
75
|
+
`){if(s)e+=Bc("");let a=i?Cc(i):void 0;if(i&&a)e+=_c(a)}else if(l===`
|
|
76
|
+
`){if(i&&Cc(i))e+=_c(i);if(s)e+=Bc(s)}}return e},Na=/\r?\n/;function Mr(n,r,t){return String(n).normalize().split(Na).map((e)=>Ia(e,r,t)).join(`
|
|
77
|
+
`)}var qn=Kt(Hi(),1);function lr(n,r,t){if(!t.some((o)=>!o.disabled))return n;let e=n+r,i=Math.max(t.length-1,0),s=e<0?i:e>i?0:e;return t[s]?.disabled?lr(s,r<0?-1:1,t):s}function ge(n,r,t,e){let i=e.split(`
|
|
78
|
+
`),s=0,o=n;for(let c of i){if(o<=c.length)break;o-=c.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+t)),o=Math.min(o,i[s].length)+r;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let u=0;for(let c=0;c<s;c++)u+=i[c].length+1;return u+o}var Ga=["up","down","left","right","space","enter","cancel"],Oa=["January","February","March","April","May","June","July","August","September","October","November","December"],Ln={actions:new Set(Ga),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:[...Oa],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 sh(n,r){if(typeof n=="string")return Ln.aliases.get(n)===r;for(let t of n)if(t!==void 0&&sh(t,r))return!0;return!1}function Ra(n,r){if(n===r)return;let t=n.split(`
|
|
79
79
|
`),e=r.split(`
|
|
80
|
-
`),i=Math.max(t.length,e.length),
|
|
81
|
-
`).map((u,c,h)=>{let f=
|
|
82
|
-
`)}function
|
|
83
|
-
`),
|
|
84
|
-
`).length-1;this.output.write(
|
|
85
|
-
`);this.output.write(s
|
|
86
|
-
`).slice(
|
|
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===`
|
|
80
|
+
`),i=Math.max(t.length,e.length),s=[];for(let o=0;o<i;o++)t[o]!==e[o]&&s.push(o);return{lines:s,numLinesBefore:t.length,numLinesAfter:e.length,numLines:i}}var I1=globalThis.process.platform.startsWith("win"),Oi=Symbol("clack:cancel");function _r(n){return n===Oi}function le(n,r){let t=n;t.isTTY&&t.setRawMode(r)}var ae=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Ji=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20;function Er(n,r,t,e=t,i=t,s){let o=ae(n??ih);return Mr(r,o-t.length,{hard:!0,trim:!1}).split(`
|
|
81
|
+
`).map((u,c,h)=>{let f=s?s(u,c):u;return c===0?`${e}${f}`:c===h.length-1?`${i}${f}`:`${t}${f}`}).join(`
|
|
82
|
+
`)}function oh(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 er{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=Ha,output:e=ih,render:i,signal:s,...o}=n;this.opts=o,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=s,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(Oi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ja.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),le(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(qn.cursor.show),this.output.off("resize",this.render),le(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(qn.cursor.show),this.output.off("resize",this.render),le(this.input,!1),n(Oi)})})}_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&&Ln.aliases.has(r.name)&&this.emit("cursor",Ln.aliases.get(r.name)),Ln.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=oh(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")}sh([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
|
+
`),le(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=Mr(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
84
|
+
`).length-1;this.output.write(qn.cursor.move(-999,n*-1))}render(){let n=Mr(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(qn.cursor.hide);else{let r=Ra(this._prevFrame,n),t=Ji(this.output);if(this.restoreCursor(),r){let e=Math.max(0,r.numLinesAfter-t),i=Math.max(0,r.numLinesBefore-t),s=r.lines.find((o)=>o>=e);if(s===void 0){this._prevFrame=n;return}if(r.lines.length===1){this.output.write(qn.cursor.move(0,s-i)),this.output.write(qn.erase.lines(1));let o=n.split(`
|
|
85
|
+
`);this.output.write(o[s]),this._prevFrame=n,this.output.write(qn.cursor.move(0,o.length-s-1));return}else if(r.lines.length>1){if(e<i)s=e;else{let u=s-i;u>0&&this.output.write(qn.cursor.move(0,u))}this.output.write(qn.erase.down());let o=n.split(`
|
|
86
|
+
`).slice(s);this.output.write(o.join(`
|
|
87
|
+
`)),this._prevFrame=n;return}}this.output.write(qn.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function Ja(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 Ka(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function La(n,r){if(r)return n?r:r[0]}var Qa=class extends er{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#r=0;#i="";#n;#s;#u;get cursor(){return this.#r}get userInputWithCursor(){if(!this.userInput)return Gi(["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}${Gi("inverse",t)}${e}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(r){super(r),this.#s=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??Ka;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 s=t.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#r=s)}this.focusedValue=this.options[this.#r]?.value,this.on("key",(i,s)=>this.#t(i,s)),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",s=t.name==="return",o=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"&&o&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}e||i?(this.#r=lr(this.#r,e?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#r]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=La(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((s)=>this.#n?.(r,s)):this.filteredOptions=[...t];let e=Ja(this.focusedValue,this.filteredOptions);this.#r=lr(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 Ki extends er{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(qn.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Pa={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function th(n){return[...n].map((r)=>Pa[r])}function Za(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 ji(n){return Number.parseInt((n||"0").replace(/_/g,"0"),10)||0}function de(n){return{year:ji(n.year),month:ji(n.month),day:ji(n.day)}}function Ri(n,r){return new Date(n||2001,r||1,0).getDate()}function uh(n){let{year:r,month:t,day:e}=de(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 eh(n){let r=uh(n);return r?new Date(Date.UTC(r.year,r.month-1,r.day)):void 0}function qa(n,r,t,e){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,s=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null;return n==="year"?{min:i?.year??1,max:s?.year??9999}:n==="month"?{min:i&&r.year===i.year?i.month:1,max:s&&r.year===s.year?s.month:12}:{min:i&&r.year===i.year&&r.month===i.month?i.day:1,max:s&&r.year===s.year&&r.month===s.month?s.day:Ri(r.year,r.month)}}class ch extends er{#r;#i;#n;#s;#u;#t={segmentIndex:0,positionInSegment:0};#e=!0;#o=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(eh(this.#n)??void 0)}constructor(n){let r=n.format?{segments:th(n.format),separator:n.separator??"/"}:Za(n.locale),t=n.separator??r.separator,e=n.format?th(n.format):r.segments,i=n.initialValue??n.defaultValue,s=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:"__"},o=e.map((u)=>s[u.type]).join(t);super({...n,initialUserInput:o},!1),this.#r=e,this.#i=t,this.#n=s,this.#s=n.minDate,this.#u=n.maxDate,this.#c(),this.on("cursor",(u)=>this.#a(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#$(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.#o=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,"")==="",s=Number.parseInt((e||"0").replace(/_/g,"0"),10)||0,o=qa(t.type,de(this.#n),this.#s,this.#u),u;i?u=n===1?o.min:o.max:u=Math.max(Math.min(o.max,s+n),o.min),this.#n={...this.#n,[t.type]:u.toString().padStart(t.len,"0")},this.#e=!0,this.#o=null,this.#c()}#a(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)}}#m(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.#o!==null&&!i){let l=this.#o+n,a={...this.#n,[e.type]:l},m=this.#d(a,e);if(m){this.inlineError=m,this.#o=null,this.#e=!1;return}this.inlineError="",this.#n[e.type]=l,this.#o=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.#o=null;let s=this.#n[e.type],o=s.indexOf("_"),u=o>=0?o:Math.min(this.#t.positionInSegment,e.len-1);if(u<0||u>=e.len)return;let c=s.slice(0,u)+n+s.slice(u+1),h=!1;if(u===0&&s==="__"&&(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=(s.replace(/_/g,"")+n).padStart(e.len,"_")),!c.includes("_")){let l={...this.#n,[e.type]:c},a=this.#d(l,e);if(a){this.inlineError=a;return}}this.inlineError="",this.#n[e.type]=c;let f=c.includes("_")?void 0:uh(this.#n);if(f){let{year:l,month:a}=f,m=Ri(l,a);this.#n={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,a))).padStart(2,"0"),day:String(Math.max(1,Math.min(m,f.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");h?(this.#e=!0,this.#o=n):g>=0?this.#t.positionInSegment=g:o>=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)}}#d(n,r){let{month:t,day:e}=de(n);if(r.type==="month"&&(t<0||t>12))return Ln.date.messages.invalidMonth;if(r.type==="day"&&(e<0||e>31))return Ln.date.messages.invalidDay(31,"any month")}#$(n){let{year:r,month:t,day:e}=de(this.#n);if(r&&t&&e){let i=Ri(r,t);this.#n={...this.#n,day:String(Math.min(e,i)).padStart(2,"0")}}this.value=eh(this.#n)??n.defaultValue??void 0}}var Ua=class extends er{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((s)=>s.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((s)=>({...s,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}})}},Wa=new Set(["up","down","left","right"]);class hh extends er{#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}${
|
|
89
|
+
${e}`:`${r}${Gi("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))}#s(n){let r=this.value??"";switch(n){case"up":this._cursor=ge(this._cursor,0,-1,r);return;case"down":this._cursor=ge(this._cursor,0,1,r);return;case"left":this._cursor=ge(this._cursor,-1,0,r);return;case"right":this._cursor=ge(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&&
|
|
93
|
-
`);
|
|
94
|
-
`:""}${
|
|
95
|
-
`,c=this.value?r:t;switch(this.state){case"submit":{let h=e?`${
|
|
96
|
-
${
|
|
97
|
-
${
|
|
98
|
-
`:` ${
|
|
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&&Wa.has(e.name)){this.#r=!1,this.#s(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 Li extends er{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?lr(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=lr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var fh=class extends er{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?lr(e,1,this.options):e,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=lr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lr(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as M,stripVTControlCharacters as J1}from"node:util";import An from"node:process";var mh=Kt(Hi(),1);function Xa(){if(An.platform!=="win32")return An.env.TERM!=="linux";return Boolean(An.env.CI)||Boolean(An.env.WT_SESSION)||Boolean(An.env.TERMINUS_SUBLIME)||An.env.ConEmuTask==="{cmd::Cmder}"||An.env.TERM_PROGRAM==="Terminus-Sublime"||An.env.TERM_PROGRAM==="vscode"||An.env.TERM==="xterm-256color"||An.env.TERM==="alacritty"||An.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Va=Xa();var dn=(n,r)=>Va?n:r,Ya=dn("◆","*"),Aa=dn("■","x"),za=dn("▲","x"),$h=dn("◇","o"),Ta=dn("┌","T"),hn=dn("│","|"),Gr=dn("└","—"),P1=dn("┐","T"),Z1=dn("┘","—"),Qi=dn("●",">"),$e=dn("○"," "),Ca=dn("◻","[•]"),gh=dn("◼","[+]"),lh=dn("◻","[ ]"),q1=dn("▪","•"),dh=dn("─","-"),_a=dn("╮","+"),Ba=dn("├","+"),xa=dn("╯","+"),Da=dn("╰","+"),U1=dn("╭","+"),W1=dn("●","•"),X1=dn("◆","*"),V1=dn("▲","!"),Y1=dn("■","x"),Zi=(n)=>{switch(n){case"initial":case"active":return M("cyan",Ya);case"cancel":return M("red",Aa);case"error":return M("yellow",za);case"submit":return M("green",$h)}},bh=(n)=>{switch(n){case"initial":case"active":return M("cyan",hn);case"cancel":return M("red",hn);case"error":return M("yellow",hn);case"submit":return M("green",hn)}};function wh(n,r){let t=[`${r?`${M("cyan",hn)} `:""}${n.join(" • ")}`];return r&&t.push(M("cyan",Gr)),t}var ah=(n,r,t,e,i,s=!1)=>{let o=r,u=0;if(s)for(let c=e-1;c>=t;c--){let h=n[c];if(h&&(o-=h.length),u++,o<=i)break}else for(let c=t;c<e;c++){let h=n[c];if(h&&(o-=h.length),u++,o<=i)break}return{lineCount:o,removals:u}},Pi=({cursor:n,options:r,style:t,output:e=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let u=ae(e)-s,c=Ji(e),h=M("dim","..."),f=Math.max(c-o,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 a=g<r.length&&l>0,m=g<r.length&&l+g<r.length,b=Math.min(l+g,r.length),E=[],F=0;a&&F++,m&&F++;let H=l+(a?1:0),p=b-(m?1:0);for(let w=H;w<p;w++){let O=r[w],k=O?t(O,w===n):"",G=Mr(k,u,{hard:!0,trim:!1}).split(`
|
|
93
|
+
`);E.push(G),F+=G.length}if(F>f){let w=0,O=0,k=F,G=n-H,S=f,K=()=>ah(E,k,0,G,S),R=()=>ah(E,k,G+1,E.length,S,!0);a?({lineCount:k,removals:w}=K(),k>S&&(m||(S-=1),{lineCount:k,removals:O}=R())):(m||(S-=1),{lineCount:k,removals:O}=R(),k>S&&(S-=1,{lineCount:k,removals:w}=K())),w>0&&(a=!0,E.splice(0,w)),O>0&&(m=!0,E.splice(E.length-O,O))}let I=[];a&&I.push(h);for(let w of E)for(let O of w)I.push(O);return m&&I.push(h),I};var kh=(n)=>{let r=n.active??"Yes",t=n.inactive??"No";return new Ki({active:r,inactive:t,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let e=n.withGuide??Ln.withGuide,i=`${Zi(this.state)} `,s=e?`${M("gray",hn)} `:"",o=Er(n.output,n.message,s,i),u=`${e?`${M("gray",hn)}
|
|
94
|
+
`:""}${o}
|
|
95
|
+
`,c=this.value?r:t;switch(this.state){case"submit":{let h=e?`${M("gray",hn)} `:"";return`${u}${h}${M("dim",c)}`}case"cancel":{let h=e?`${M("gray",hn)} `:"";return`${u}${h}${M(["strikethrough","dim"],c)}${e?`
|
|
96
|
+
${M("gray",hn)}`:""}`}default:{let h=e?`${M("cyan",hn)} `:"",f=e?M("cyan",Gr):"";return`${u}${h}${this.value?`${M("green",Qi)} ${r}`:`${M("dim",$e)} ${M("dim",r)}`}${n.vertical?e?`
|
|
97
|
+
${M("cyan",hn)} `:`
|
|
98
|
+
`:` ${M("dim","/")} `}${this.value?`${M("dim",$e)} ${M("dim",t)}`:`${M("green",Qi)} ${t}`}
|
|
99
99
|
${f}
|
|
100
|
-
`}}}}).prompt()};var
|
|
100
|
+
`}}}}).prompt()};var nm=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`],St=(n,r)=>n.split(`
|
|
101
101
|
`).map((t)=>r(t)).join(`
|
|
102
|
-
`),
|
|
103
|
-
${
|
|
104
|
-
`:""}${
|
|
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(
|
|
106
|
-
${
|
|
107
|
-
`).map((
|
|
108
|
-
`),g=
|
|
102
|
+
`),ph=(n)=>{let r=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${M("gray",lh)} ${St(o,(u)=>M(["strikethrough","gray"],u))}${i.hint?` ${M("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${M("cyan",Ca)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${M("green",gh)} ${St(o,(u)=>M("dim",u))}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${St(o,(u)=>M(["strikethrough","dim"],u))}`:s==="active-selected"?`${M("green",gh)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${St(o,(u)=>M("dim",u))}`:`${M("dim",lh)} ${St(o,(u)=>M("dim",u))}`},t=n.required??!0,e=n.showInstructions??!0;return new Li({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
|
+
${M("reset",M("dim",`Press ${M(["gray","bgWhite","inverse"]," space ")} to select, ${M("gray",M("bgWhite",M("inverse"," enter ")))} to submit`))}`},render(){let i=n.withGuide??Ln.withGuide,s=Er(n.output,n.message,i?`${bh(this.state)} `:"",`${Zi(this.state)} `),o=`${i?`${M("gray",hn)}
|
|
104
|
+
`:""}${s}
|
|
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(M("dim",", "))||M("dim","none"),f=Er(n.output,h,i?`${M("gray",hn)} `:"");return`${o}${f}`}case"cancel":{let h=this.options.filter(({value:g})=>u.includes(g)).map((g)=>r(g,"cancelled")).join(M("dim",", "));if(h.trim()==="")return`${o}${M("gray",hn)}`;let f=Er(n.output,h,i?`${M("gray",hn)} `:"");return`${o}${f}${i?`
|
|
106
|
+
${M("gray",hn)}`:""}`}case"error":{let h=i?`${M("yellow",hn)} `:"",f=this.error.split(`
|
|
107
|
+
`).map((a,m)=>m===0?`${i?`${M("yellow",Gr)} `:""}${M("yellow",a)}`:` ${a}`).join(`
|
|
108
|
+
`),g=o.split(`
|
|
109
109
|
`).length,l=f.split(`
|
|
110
|
-
`).length+1;return`${
|
|
110
|
+
`).length+1;return`${o}${h}${Pi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:g+l,style:c}).join(`
|
|
111
111
|
${h}`)}
|
|
112
112
|
${f}
|
|
113
|
-
`}default:{let h=i?`${
|
|
114
|
-
`).length,g=e?
|
|
115
|
-
`)
|
|
113
|
+
`}default:{let h=i?`${M("cyan",hn)} `:"",f=o.split(`
|
|
114
|
+
`).length,g=e?wh(nm,i):i?[M("cyan",Gr)]:[],l=g.join(`
|
|
115
|
+
`),a=g.length+1;return`${o}${h}${Pi({output:n.output,options:this.options,cursor:this.cursor,maxItems:n.maxItems,columnPadding:h.length,rowPadding:f+a,style:c}).join(`
|
|
116
116
|
${h}`)}
|
|
117
117
|
${l}
|
|
118
|
-
`}}}}).prompt()};var
|
|
118
|
+
`}}}}).prompt()};var be=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",Gr)} `:"";t.write(`${e}${M("red",n)}
|
|
119
119
|
|
|
120
|
-
`)},
|
|
121
|
-
`)},
|
|
122
|
-
${
|
|
120
|
+
`)},Mh=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",Ta)} `:"";t.write(`${e}${n}
|
|
121
|
+
`)},Eh=(n="",r)=>{let t=r?.output??process.stdout,e=r?.withGuide??Ln.withGuide?`${M("gray",hn)}
|
|
122
|
+
${M("gray",Gr)} `:"";t.write(`${e}${n}
|
|
123
123
|
|
|
124
|
-
`)};var
|
|
125
|
-
`),
|
|
126
|
-
`).map(
|
|
127
|
-
`),f=i?`${
|
|
128
|
-
`:"",g=i?
|
|
124
|
+
`)};var rm=(n)=>n,tm=(n,r,t)=>{let e={hard:!0,trim:!1},i=Mr(n,r,e).split(`
|
|
125
|
+
`),s=i.reduce((c,h)=>Math.max(Kn(h),c),0),o=i.map(t).reduce((c,h)=>Math.max(Kn(h),c),0),u=r-(o-s);return Mr(n,u,e)},we=(n="",r="",t)=>{let e=t?.output??An.stdout,i=t?.withGuide??Ln.withGuide,s=t?.format??rm,o=["",...tm(n,ae(e)-6,s).split(`
|
|
126
|
+
`).map(s),""],u=Kn(r),c=Math.max(o.reduce((l,a)=>{let m=Kn(a);return m>l?m:l},0),u)+2,h=o.map((l)=>`${M("gray",hn)} ${l}${" ".repeat(c-Kn(l))}${M("gray",hn)}`).join(`
|
|
127
|
+
`),f=i?`${M("gray",hn)}
|
|
128
|
+
`:"",g=i?Ba:Da;e.write(`${f}${M("green",$h)} ${M("reset",r)} ${M("gray",dh.repeat(Math.max(c-u-1,1))+_a)}
|
|
129
129
|
${h}
|
|
130
|
-
${
|
|
131
|
-
`)};var
|
|
130
|
+
${M("gray",g+dh.repeat(c+2)+xa)}
|
|
131
|
+
`)};var A1={light:dn("─","-"),heavy:dn("━","="),block:dn("█","#")};var em=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Enter:")} confirm`],me=(n,r)=>n.includes(`
|
|
132
132
|
`)?n.split(`
|
|
133
133
|
`).map((t)=>r(t)).join(`
|
|
134
|
-
`):r(n),
|
|
135
|
-
`:""}${
|
|
136
|
-
`;switch(this.state){case"submit":{let c=e?`${
|
|
137
|
-
${
|
|
138
|
-
`).length,f=t?
|
|
139
|
-
`),l=f.length+1;return`${u}${c}${
|
|
134
|
+
`):r(n),vh=(n)=>{let r=(e,i)=>{if(e===void 0)return"";let s=e.label??String(e.value);switch(i){case"disabled":return`${M("gray",$e)} ${me(s,(o)=>M("gray",o))}${e.hint?` ${M("dim",`(${e.hint??"disabled"})`)}`:""}`;case"selected":return`${me(s,(o)=>M("dim",o))}`;case"active":return`${M("green",Qi)} ${s}${e.hint?` ${M("dim",`(${e.hint})`)}`:""}`;case"cancelled":return`${me(s,(o)=>M(["strikethrough","dim"],o))}`;default:return`${M("dim",$e)} ${me(s,(o)=>M("dim",o))}`}},t=n.showInstructions??!0;return new fh({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let e=n.withGuide??Ln.withGuide,i=`${Zi(this.state)} `,s=`${bh(this.state)} `,o=Er(n.output,n.message,s,i),u=`${e?`${M("gray",hn)}
|
|
135
|
+
`:""}${o}
|
|
136
|
+
`;switch(this.state){case"submit":{let c=e?`${M("gray",hn)} `:"",h=Er(n.output,r(this.options[this.cursor],"selected"),c);return`${u}${h}`}case"cancel":{let c=e?`${M("gray",hn)} `:"",h=Er(n.output,r(this.options[this.cursor],"cancelled"),c);return`${u}${h}${e?`
|
|
137
|
+
${M("gray",hn)}`:""}`}default:{let c=e?`${M("cyan",hn)} `:"",h=u.split(`
|
|
138
|
+
`).length,f=t?wh(em,e):e?[M("cyan",Gr)]:[],g=f.join(`
|
|
139
|
+
`),l=f.length+1;return`${u}${c}${Pi({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:c.length,rowPadding:h+l,style:(a,m)=>r(a,a.disabled?"disabled":m?"active":"inactive")}).join(`
|
|
140
140
|
${c}`)}
|
|
141
141
|
${g}
|
|
142
|
-
`}}}}).prompt()};var
|
|
143
|
-
`)}}function
|
|
144
|
-
${n} palettes installed — open a new tab, or reload your terminal config`)}function
|
|
145
|
-
`))}function
|
|
146
|
-
${u} palettes — ${
|
|
142
|
+
`}}}}).prompt()};var z1=`${M("gray",hn)} `;import{existsSync as lm}from"node:fs";import{openSync as im,writeSync as sm}from"node:fs";import{ReadStream as om}from"node:tty";var Ih=["10","11","12","17",...Array.from({length:16},(n,r)=>`4;${r}`)];function ke(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 Nh(n){let r=new Map;for(let t of n.split("\x1B")){let e=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=e??[];if(i&&s)r.set(i,s)}return r}function yh(n){return[...n].map(([r,t])=>`\x1B]${r};${t}\x1B\\`).join("")}async function Sh(){let n,r;try{n=im("/dev/tty","r+"),r=new om(n),r.setRawMode(!0)}catch{return new Map}try{sm(n,Ih.map((e)=>`\x1B]${e};?\x1B\\`).join(""));let t="";return await new Promise((e)=>{let i=setTimeout(e,120);r.on("data",(s)=>{if(t+=s.toString(),Nh(t).size>=Ih.length)clearTimeout(i),e()})}),Nh(t)}finally{r.setRawMode(!1),r.destroy()}}function Br(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 Hh(n,r){return`\x1B[48;2;${Br(r)}m ${n} \x1B[0m`}function qi(n,r){return`\x1B[48;2;${Br(n)};38;2;${Br(r)}m ● \x1B[0m`}function jh(n){return`\x1B[38;2;${Br(n)}m`}function Ui(n,r){return`\x1B[48;2;${Br(r)}m${n.map((t)=>`\x1B[38;2;${Br(t)}m▄`).join("")} \x1B[0m`}function pe(n,r){let t=r.toLowerCase();return[n.name,n.group,n.native??""].some((e)=>e.toLowerCase().includes(t))}function Oh(n,r,t){let e=t.trim(),i=[],s=new Set;for(let o of n){if(o.default||s.has(o.group))continue;s.add(o.group);let u=n.filter((f)=>!f.default&&f.group===o.group),c=e?u.filter((f)=>pe(f,e)):u;if(e&&c.length===0)continue;let h=e.length>0||r.has(o.group);if(i.push({kind:"group",name:o.group,native:o.native,lead:u.find((f)=>f.lead)??o,expanded:h,count:c.length}),h)i.push(...c.map((f)=>({kind:"palette",entry:f})))}return i}function um(n,r){let t=r.trim(),e=new Set(n.filter((i)=>!i.default&&(t===""||pe(i,t))).map((i)=>i.group));return Oh(n,new Set,"").filter((i)=>i.kind==="group"&&e.has(i.name))}function cm(n){let r=n.findIndex((t)=>t.kind==="palette");return r===-1?0:r}var Bn="\x1B[0m",xr="\x1B[2m",hm="\x1B[1m",Gh="\x1B[1;7m",fm="\x1B[36m",gm="\x1B[33m";function Rh(n){return n==="decode"||n==="glitch"?n:"typewriter"}class Wi extends er{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===""||pe(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"?um(this.entries,this.userInput):Oh(this.entries,this.expanded,this.userInput),e=t.length>0?cm(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:"",s=i?this.rows.findIndex((o)=>o.kind==="palette"&&o.entry.name===i):-1;this.cursor=s===-1?e:s}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 s=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",o=`(${n.count})`;return`${t}${s}select all ${this.color?`${xr}${o}${Bn}`:o}`}if(n.kind==="group"&&this.scope==="series"){let s=this.pickedIn(n.name)===n.count?"● ":"○ ",o=n.name.padEnd(this.seriesPad),u=`(${n.count})${n.native?` ${n.native}`:""}`;if(!this.color)return`${t}${s}${o} ${u}`;let c=n.lead;return`${t}${s}${o} ${qi(c.background,c.cursor)}${Ui(c.ansi.slice(1,7),c.background)} ${xr}${u}${Bn}`}if(n.kind==="group"){let s=n.expanded?"▾":"▸",o=this.rows[this.cursor],u=o?.kind==="palette"&&o.entry.group===n.name?o.entry:void 0,c=this.color?r?`${Gh} ${n.name} ${Bn}`:u?`${Gh}${jh(u.cursor)} ${n.name} ${Bn}`:` ${hm}${n.name}${Bn} `:r?`[${n.name}]`:` ${n.name}`,h=this.color?Hh("●",n.lead.selection):"",f=`${this.pickedIn(n.name)}/${n.count}`,g=this.color?` ${xr}(${f})${Bn}`:` (${f})`,l=n.native?this.color?` ${xr}${n.native}${Bn}`:` ${n.native}`:"";return`${s}${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)} ${qi(e.background,e.cursor)}${Ui(e.ansi.slice(1,7),e.background)} ${xr}${e.ansiSource}${Bn}`}draw(){let n=(b)=>this.color?`${xr}${b}${Bn}`:b,r=(b)=>this.color?`${fm}${b}${Bn}`:b,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,s=this.scope==="series"?this.rows.filter((b)=>b.kind==="group").length:e?this.named.filter((b)=>pe(b,e)).length:i,o=`${r("◆")} ${t} ${n(`(${s}/${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((b,E)=>`${r("│")} ${this.renderRow(b,this.top+E===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",a=this.scope==="series"?"continue":"install",m=this.state==="error"?`${r("└")} ${this.color?`${gm}${this.error}${Bn}`:this.error}`:`${r("└")} ${n(`↑↓ move${l} · space pick · type to filter · enter ${a} · esc cancel`)}`;return[o,u,...h,g,m].join(`
|
|
143
|
+
`)}}function Xi(n,r,t,e){let i=Vr(),s=Boolean(Yr(t))!==Boolean(Yr(e)),o=s?Ft(e,i):e;if(yt(n,r,o),Nt(n,o),s)It(o,i)}function Vi(n){console.log(`
|
|
144
|
+
${n} palettes installed — open a new tab, or reload your terminal config`)}function Jh(n){let r=_n(),t=Pn(r),e=fr(r),i=n.filter((u)=>e.palettes.includes(u)),s=n.filter((u)=>!e.palettes.includes(u));if(s.length===0){console.log(`already installed: ${i.join(", ")}`);return}let o={...e,palettes:[...e.palettes,...s]};Xi(r,t,e,o);for(let u of s)console.log(` + ${u}`);Vi(o.palettes.length)}function Kh(n){let r=_n(),t=Pn(r),e=fr(r),i=n.filter((o)=>e.palettes.includes(o));if(i.length===0){console.log(`not installed: ${n.join(", ")}`);return}let s={...e,palettes:e.palettes.filter((o)=>!i.includes(o))};Xi(r,t,e,s),ai(r,t,e.terminals,i);for(let o of i)console.log(` - ${o}`);Vi(s.palettes.length)}function Lh(n){let r=_n(),t=Pn(r),e=fr(r);if(!e.palettes.includes(n))throw Error(`${n} is not installed — \`ttheme add ${n}\` first`);let{keepTheme:i,...s}=e,o=Vr(),u=Ft({...s,startup:n},o);yt(r,t,u),Nt(r,u);let c=It(u,o);console.log(dm(n,u.terminals,c&&o.running()).join(`
|
|
145
|
+
`))}function dm(n,r,t){let e=r.filter((s)=>s!=="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 Qh(n){let r=_n(),t=Pn(r),e=new Set(fr(r).palettes),i=Wr(t.palettes),s=pt(n?qu(i,n):i),o=Math.max(...s.map((c)=>c.name.length),0);for(let c of s)console.log(` ${e.has(c.name)?"●":"○"} ${c.name.padEnd(o)} ${c.group}`);let u=n?`${s.length} of ${i.length}`:`${i.length}`;console.log(`
|
|
146
|
+
${u} palettes — ${s.filter((c)=>e.has(c.name)).length} installed`)}async function Ph(){let n=_n(),r=lm(ne(n))?Pn(n).palettes.length:0,t=await Pu(Lu);re(n,t);let e=t.palettes.length-r;console.log(`catalog ${t.version} — ${t.palettes.length} palettes${e>0?` (+${e})`:""}`)}async function Yi(n,r,t,e=!1){let i=process.env.TTHEME_SORT==="series"?n.palettes:pt(n.palettes),s=process.stdout.isTTY===!0&&!process.env.NO_COLOR,o=s?await Sh():new Map,u=new Wi({entries:i,scope:t,installed:r,required:e,color:!process.env.NO_COLOR,fx:Rh(process.env.TTHEME_FX),onFocus:s?(h)=>process.stdout.write(ke(h)):void 0}),c=await u.prompt();if(process.stdout.write(yh(o)),_r(c))return;return n.palettes.filter((h)=>u.picked.has(h.name)).map((h)=>h.name)}async function Zh(){let n=_n(),r=Pn(n),t=fr(n),e=await Yi(r,t.palettes,"palette");if(!e){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!e.includes(u)),s=e.filter((u)=>!t.palettes.includes(u));if(s.length===0&&i.length===0){console.log("nothing changed");return}let o={...t,palettes:e};Xi(n,r,t,o),ai(n,r,t.terminals,i);for(let u of s)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);Vi(o.palettes.length)}function Wh(n,r,t){for(let e of $m(r))n.push({from:wn(r,e),to:wn(t,e)})}function Ah(n){return JSON.parse(jt(wn(n,"dist","manifest.json"),"utf8"))}function Xh(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")}];Wh(i,wn(r.root,"shell","adapters"),wn(e,"adapters"));let s=[{file:wn(r.zdotdir,".zshrc"),block:yu(e)}],o=wn(e,"config.zsh"),u=Hu(dr(o)?jt(o,"utf8"):""),c={file:o,content:n.wear?Bt(u,"TTHEME_TAB_PALETTE",n.wear==="rotate"?"seq":"off"):u},h=[];if(n.terminals.includes("ghostty"))Wh(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(dr(g)&&!jt(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:s,settings:c,catalog:Ah(r.root),installed:f,notes:h}}function wm(n){try{return fr(n).itermBase}catch{return}}function Vh(n,r=Vr()){for(let s of n.copies)if(Ai(Ht(s.to),{recursive:!0}),qh(s.to,{force:!0}),qh(`${s.to}.zwc`,{force:!0}),mm(s.from,s.to),s.executable)am(s.to,493);Ai(Ht(n.settings.file),{recursive:!0}),Uh(n.settings.file,n.settings.content);let t=Ht(Ht(n.settings.file)),e=wm(t),i=Ft(e?{...n.installed,itermBase:e}:n.installed,r);re(t,n.catalog),Nt(t,i),yt(t,n.catalog,i,n.home);for(let s of n.edits){Ai(Ht(s.file),{recursive:!0});let o=dr(s.file)?jt(s.file,"utf8"):"";Uh(s.file,Ct(o,s.block))}return It(i,r)}function zi(n){if(_r(n))be("nothing changed"),process.exit(1);return n}function zh(){return Tt.filter((n)=>n!=="iterm2"||process.platform==="darwin")}function km(n,r){return n==="iterm2"?dr(wn(r.home,"Library","Application Support","iTerm2")):dr(wn(r.configHome,n))}async function pm(n,r){return zi(await ph({message:"wire which terminals?",options:zh().map((t)=>({value:t,hint:t===n?"detected":void 0})),initialValues:r,required:!0}))}function Mm(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 Em(n){return zi(await vh({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 Yh(n){let r=[...n.copies.filter((t)=>!dr(t.to)).map((t)=>t.to),...dr(n.settings.file)?[]:[n.settings.file],...n.edits.filter((t)=>!jt(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
|
|
149
|
-
`),`installed ${r.palettes.length} palettes`);let
|
|
150
|
-
`),"next"),
|
|
151
|
-
`))}async function
|
|
152
|
-
`),`wiring ${h.join(", ")}`),!
|
|
153
|
-
`)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...
|
|
154
|
-
`)}async function
|
|
148
|
+
`)}`)}function Th(n,r){return[...new Set(n.palettes.filter((t)=>r.includes(t.name)).map((t)=>t.group))]}function vm(n,r){let t=n.palettes.find((i)=>i.name===Ar(r)),e=process.stdout.isTTY===!0&&!process.env.NO_COLOR&&!process.env.TMUX;if(!t||!e)return!1;return process.stdout.write(ke(t)),!0}function Fm(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 Im(n,r,t,e,i){let s=Th(n.catalog,r.palettes);we([`${s.join(", ")} (${r.palettes.length})`,...Fm(t,Ar(n.installed),e)].join(`
|
|
149
|
+
`),`installed ${r.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(r.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(r.terminals.includes("kitty"))o.push("new kitty window picks up its config");if(r.terminals.includes("iterm2"))o.push(...Nm(t==="default"?Ar(n.installed):void 0,i));we([...o,...n.notes].join(`
|
|
150
|
+
`),"next"),Eh("done")}function Nm(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 ym(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 Ch(n={}){let r=wn(import.meta.dirname,"..");if(!dr(wn(r,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!dr(wn(r,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Dt()}let t=bm(),e=process.env.XDG_CONFIG_HOME??wn(t,".config"),i=process.env.ZDOTDIR??t,s={root:r,home:t,configHome:e,zdotdir:i},o=Iu(process.env),u=zh().filter((F)=>F===o||km(F,s));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 F={terminals:u,palettes:[]},H=Xh(F,s);Vh(H),Yh(H),ym(H,F);return}Mh("ttheme init");let h=await pm(o,u),f=await Yi(Ah(r),[],"series",!0);if(!f)be("nothing changed"),process.exit(1);let g=Ar({terminals:h,palettes:f}),l=await Em(g),a={terminals:h,palettes:f,wear:l},m=Xh(a,s);if(we([`install ${f.length} palettes — ${Th(m.catalog,f).join(", ")}`,`copy ${m.copies.length} files under ${e}`,`write ${m.settings.file}`,...m.edits.map((F)=>`edit ${F.file}`),Mm(l,g),...h.includes("iterm2")&&l!=="keep"?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
|
|
152
|
+
`),`wiring ${h.join(", ")}`),!zi(await kh({message:"apply these changes?"})))be("nothing changed"),process.exit(1);let b=Vr(),E=Vh(m,b);Yh(m),Im(m,a,l,l!=="keep"&&vm(m.catalog,m.installed),E&&b.running())}var Dh=[{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table",flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ku,about:"rebuild just this terminal — repeat it for more"}},run:(n,{only:r})=>Dt({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})=>Ch({yes:r})},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",run:()=>Zh()},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",run:([n])=>Qh(n)},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",run:(n)=>Jh(n)},{name:"remove",args:["<palette...>"],about:"uninstall palettes",run:(n)=>Kh(n)},{name:"default",args:["<palette>"],about:"make an installed palette the one new tabs open with",run:([n])=>Lh(n)},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",hidden:!0,run:([n])=>Zc(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])=>qc(n,r)},{name:"update",args:[],about:"refresh the catalog from the registry",run:()=>Ph()}];class Or extends Error{verb;constructor(n,r){super(n);this.verb=r}}function _h(n){let r=Dh.find((t)=>t.name===n);if(!r)throw new Or(n.startsWith("-")?`unknown option '${n}'`:`unknown command '${n}'`);return r}function Hm(n,r){let t={help:{type:"boolean",short:"h"}};for(let[e,{type:i,multiple:s}]of Object.entries(n.flags??{}))t[e]={type:i,multiple:s===!0};try{return Sm({args:r,options:t,allowPositionals:!0})}catch(e){let[i=""]=(e instanceof Error?e.message:String(e)).split(". ");throw new Or(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,n)}}function jm(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:_h(t[0]),code:0};let e=_h(r),i=Hm(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 Or(`--${f} takes ${g.join(", ")} — not ${l}`,e);let s=i.positionals,o=e.args.filter((f)=>f.startsWith("<")).length,u=e.args.some((f)=>f.includes("..."))?Number.POSITIVE_INFINITY:e.args.length;if(s.length<o)throw new Or(`missing ${e.args[s.length]}`,e);if(s.length>u)throw new Or(`too many arguments: ${s.slice(u).join(" ")}`,e);let{help:c,...h}=i.values;return{kind:"run",verb:e,args:s,flags:h}}function Bh(n){let r=Object.entries(n.flags??{}).map(([t,{value:e}])=>`[--${t}${e?` ${e}`:""}]`);return[n.name,...r,...n.args].join(" ")}function xh(n){let r=Math.max(...n.map(([t])=>t.length));return n.map(([t,e])=>` ${t.padEnd(r)} ${e}`)}function Ti(n){if(n){let r=Object.entries(n.flags??{}).map(([t,{value:e,about:i}])=>[`--${t}${e?` ${e}`:""}`,i]);return[`Usage: ttheme ${Bh(n)}`,"",n.about,...r.length>0?["","Options:",...xh(r)]:[]].join(`
|
|
153
|
+
`)}return["Usage: ttheme <command>","",Dn.description,"","Commands:",...xh(Dh.filter((r)=>!r.hidden).map((r)=>[Bh(r),r.about])),"","ttheme <command> --help describes one command · ttheme --version prints the version"].join(`
|
|
154
|
+
`)}async function nf(n){try{let r=jm(n);if(r.kind==="version")return console.log(Dn.version),0;if(r.kind==="help"){if(r.code===0)console.log(Ti(r.verb));else console.error(Ti(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 Or)return console.error(`ttheme${r.verb?` ${r.verb.name}`:""}: ${r.message}
|
|
155
155
|
|
|
156
|
-
${
|
|
157
|
-
${r instanceof Error?r.message:String(r)}`),1}}if(
|
|
156
|
+
${Ti(r.verb)}`),1;return console.error(`
|
|
157
|
+
${r instanceof Error?r.message:String(r)}`),1}}if(Gm)process.exitCode=await nf(process.argv.slice(2));
|