@kecan0406/ttheme 1.0.40 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,66 +1,438 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as el}from"node:module";var Xf=Object.create;var{getPrototypeOf:Vf,defineProperty:gs,getOwnPropertyNames:Yf}=Object;var zf=Object.prototype.hasOwnProperty;function Bf(t){return this[t]}var Df,tl,yr=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var i=e?Df??=new WeakMap:tl??=new WeakMap,o=i.get(t);if(o)return o}n=t!=null?Xf(Vf(t)):{};let s=e||!t||!t.__esModule?gs(n,"default",{value:t,enumerable:!0}):n;for(let c of Yf(t))if(!zf.call(s,c))gs(s,c,{get:Bf.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var $t=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Gt=el(import.meta.url);var Ws=$t((Vw,Fr)=>{var Js=Js||function(t){return Buffer.from(t).toString("base64")};function kl(t){var e=this,n=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,a,f,l=Array(65535),p=Array(65535),b=Array(64),g=Array(64),$=[],y=0,F=7,E=Array(64),v=Array(64),d=Array(64),j=Array(256),k=Array(2048),H,R=[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],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],P=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],U=[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],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],K=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],yt=[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 mt(m){var G=[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 J=0;J<64;J++){var A=r((G[J]*m+50)/100);if(A<1)A=1;else if(A>255)A=255;i[R[J]]=A}var Z=[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 q=0;q<64;q++){var rt=r((Z[q]*m+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[R[q]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var bt=0;bt<8;bt++)for(var M=0;M<8;M++)s[St]=1/(i[R[St]]*it[bt]*it[M]*8),c[St]=1/(o[R[St]]*it[bt]*it[M]*8),St++}function B(m,G){var J=0,A=0,Z=[];for(var q=1;q<=16;q++){for(var rt=1;rt<=m[q];rt++)Z[G[A]]=[],Z[G[A]][0]=J,Z[G[A]][1]=q,A++,J++;J*=2}return Z}function Nt(){u=B(L,P),h=B(Ft,K),a=B(C,U),f=B(z,yt)}function ot(){var m=1,G=2;for(var J=1;J<=15;J++){for(var A=m;A<G;A++)p[32767+A]=J,l[32767+A]=[],l[32767+A][1]=J,l[32767+A][0]=A;for(var Z=-(G-1);Z<=-m;Z++)p[32767+Z]=J,l[32767+Z]=[],l[32767+Z][1]=J,l[32767+Z][0]=G-1+Z;m<<=1,G<<=1}}function tt(){for(var m=0;m<256;m++)k[m]=19595*m,k[m+256>>0]=38470*m,k[m+512>>0]=7471*m+32768,k[m+768>>0]=-11059*m,k[m+1024>>0]=-21709*m,k[m+1280>>0]=32768*m+8421375,k[m+1536>>0]=-27439*m,k[m+1792>>0]=-5329*m}function X(m){var G=m[0],J=m[1]-1;while(J>=0){if(G&1<<J)y|=1<<F;if(J--,F--,F<0){if(y==255)w(255),w(0);else w(y);F=7,y=0}}}function w(m){$.push(m)}function T(m){w(m>>8&255),w(m&255)}function at(m,G){var J,A,Z,q,rt,it,St,bt,M=0,O,Q=8,Mt=64;for(O=0;O<Q;++O){J=m[M],A=m[M+1],Z=m[M+2],q=m[M+3],rt=m[M+4],it=m[M+5],St=m[M+6],bt=m[M+7];var _=J+bt,D=J-bt,lt=A+St,W=A-St,st=Z+it,Ht=Z-it,Et=q+rt,Ct=q-rt,re=_+Et,je=_-Et,_e=lt+st,Ce=lt-st;m[M]=re+_e,m[M+4]=re-_e;var yn=(Ce+je)*0.707106781;m[M+2]=je+yn,m[M+6]=je-yn,re=Ct+Ht,_e=Ht+W,Ce=W+D;var Mn=(re-Ce)*0.382683433,br=0.5411961*re+Mn,vn=1.306562965*Ce+Mn,Sn=_e*0.707106781,In=D+Sn,Fn=D-Sn;m[M+5]=Fn+br,m[M+3]=Fn-br,m[M+1]=In+vn,m[M+7]=In-vn,M+=8}M=0;for(O=0;O<Q;++O){J=m[M],A=m[M+8],Z=m[M+16],q=m[M+24],rt=m[M+32],it=m[M+40],St=m[M+48],bt=m[M+56];var ts=J+bt,wi=J-bt,es=A+St,ns=A-St,rs=Z+it,is=Z-it,os=q+rt,Cf=q-rt,Nn=ts+os,bi=ts-os,$r=es+rs,kr=es-rs;m[M]=Nn+$r,m[M+32]=Nn-$r;var ss=(kr+bi)*0.707106781;m[M+16]=bi+ss,m[M+48]=bi-ss,Nn=Cf+is,$r=is+ns,kr=ns+wi;var cs=(Nn-kr)*0.382683433,us=0.5411961*Nn+cs,hs=1.306562965*kr+cs,as=$r*0.707106781,fs=wi+as,ls=wi-as;m[M+40]=ls+us,m[M+24]=ls-us,m[M+8]=fs+hs,m[M+56]=fs-hs,M++}var Er;for(O=0;O<Mt;++O)Er=m[O]*G[O],b[O]=Er>0?Er+0.5|0:Er-0.5|0;return b}function ft(){T(65504),T(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),T(1),T(1),w(0),w(0)}function et(m){if(!m)return;if(T(65505),m[0]===69&&m[1]===120&&m[2]===105&&m[3]===102)T(m.length+2);else T(m.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var G=0;G<m.length;G++)w(m[G])}function nt(m,G){T(65472),T(17),w(8),T(G),T(m),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function V(){T(65499),T(132),w(0);for(var m=0;m<64;m++)w(i[m]);w(1);for(var G=0;G<64;G++)w(o[G])}function N(){T(65476),T(418),w(0);for(var m=0;m<16;m++)w(L[m+1]);for(var G=0;G<=11;G++)w(P[G]);w(16);for(var J=0;J<16;J++)w(C[J+1]);for(var A=0;A<=161;A++)w(U[A]);w(1);for(var Z=0;Z<16;Z++)w(Ft[Z+1]);for(var q=0;q<=11;q++)w(K[q]);w(17);for(var rt=0;rt<16;rt++)w(z[rt+1]);for(var it=0;it<=161;it++)w(yt[it])}function I(m){if(typeof m>"u"||m.constructor!==Array)return;m.forEach((G)=>{if(typeof G!=="string")return;T(65534);var J=G.length;T(J+2);var A;for(A=0;A<J;A++)w(G.charCodeAt(A))})}function wt(){T(65498),T(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function x(m,G,J,A,Z){var q=Z[0],rt=Z[240],it,St=16,bt=63,M=64,O=at(m,G);for(var Q=0;Q<M;++Q)g[R[Q]]=O[Q];var Mt=g[0]-J;if(J=g[0],Mt==0)X(A[0]);else it=32767+Mt,X(A[p[it]]),X(l[it]);var _=63;for(;_>0&&g[_]==0;_--);if(_==0)return X(q),J;var D=1,lt;while(D<=_){var W=D;for(;g[D]==0&&D<=_;++D);var st=D-W;if(st>=St){lt=st>>4;for(var Ht=1;Ht<=lt;++Ht)X(rt);st=st&15}it=32767+g[D],X(Z[(st<<4)+p[it]]),X(l[it]),D++}if(_!=bt)X(q);return J}function Y(){var m=String.fromCharCode;for(var G=0;G<256;G++)j[G]=m(G)}this.encode=function(m,G){var J=new Date().getTime();if(G)_t(G);$=[],y=0,F=7,T(65496),ft(),I(m.comments),et(m.exifBuffer),V(),nt(m.width,m.height),N(),wt();var A=0,Z=0,q=0;y=0,F=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=m,bt=it*4,M=it*3,O,Q=0,Mt,_,D,lt,W,st,Ht,Et;while(Q<St){O=0;while(O<bt){lt=bt*Q+O,W=lt,st=-1,Ht=0;for(Et=0;Et<64;Et++){if(Ht=Et>>3,st=(Et&7)*4,W=lt+Ht*bt+st,Q+Ht>=St)W-=bt*(Q+1+Ht-St);if(O+st>=bt)W-=O+st-bt+4;Mt=rt[W++],_=rt[W++],D=rt[W++],E[Et]=(k[Mt]+k[_+256>>0]+k[D+512>>0]>>16)-128,v[Et]=(k[Mt+768>>0]+k[_+1024>>0]+k[D+1280>>0]>>16)-128,d[Et]=(k[Mt+1280>>0]+k[_+1536>>0]+k[D+1792>>0]>>16)-128}A=x(E,s,A,u,a),Z=x(v,c,Z,h,f),q=x(d,c,q,h,f),O+=32}Q+=8}if(F>=0){var Ct=[];Ct[1]=F+1,Ct[0]=(1<<F+1)-1,X(Ct)}if(T(65497),typeof Fr>"u")return new Uint8Array($);return Buffer.from($);var re,je};function _t(m){if(m<=0)m=1;if(m>100)m=100;if(H==m)return;var G=0;if(m<50)G=Math.floor(5000/m);else G=Math.floor(200-m*2);mt(G),H=m}function zt(){var m=new Date().getTime();if(!t)t=50;Y(),Nt(),ot(),tt(),_t(t);var G=new Date().getTime()-m}zt()}if(typeof Fr<"u")Fr.exports=Ks;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ks;function Ks(t,e){if(typeof e>"u")e=50;var n=new kl(e),r=n.encode(t,e);return{data:r,width:t.width,height:t.height}}});var Qs=$t((Yw,Ni)=>{var Fi=function(){var e=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]),n=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function a(){}function f(F,E){var v=0,d=[],j,k,H=16;while(H>0&&!F[H-1])H--;d.push({children:[],index:0});var R=d[0],L;for(j=0;j<H;j++){for(k=0;k<F[j];k++){R=d.pop(),R.children[R.index]=E[v];while(R.index>0){if(d.length===0)throw Error("Could not recreate Huffman Table");R=d.pop()}R.index++,d.push(R);while(d.length<=j)d.push(L={children:[],index:0}),R.children[R.index]=L.children,R=L;v++}if(j+1<H)d.push(L={children:[],index:0}),R.children[R.index]=L.children,R=L}return d[0].children}function l(F,E,v,d,j,k,H,R,L,P){var{precision:C,samplesPerLine:U,scanLines:Ft,mcusPerLine:K,progressive:z,maxH:yt,maxV:mt}=v,B=E,Nt=0,ot=0;function tt(){if(ot>0)return ot--,Nt>>ot&1;if(Nt=F[E++],Nt==255){var M=F[E++];if(M)throw Error("unexpected marker: "+(Nt<<8|M).toString(16))}return ot=7,Nt>>>7}function X(M){var O=M,Q;while((Q=tt())!==null){if(O=O[Q],typeof O==="number")return O;if(typeof O!=="object")throw Error("invalid huffman sequence")}return null}function w(M){var O=0;while(M>0){var Q=tt();if(Q===null)return;O=O<<1|Q,M--}return O}function T(M){var O=w(M);if(O>=1<<M-1)return O;return O+(-1<<M)+1}function at(M,O){var Q=X(M.huffmanTableDC),Mt=Q===0?0:T(Q);O[0]=M.pred+=Mt;var _=1;while(_<64){var D=X(M.huffmanTableAC),lt=D&15,W=D>>4;if(lt===0){if(W<15)break;_+=16;continue}_+=W;var st=e[_];O[st]=T(lt),_++}}function ft(M,O){var Q=X(M.huffmanTableDC),Mt=Q===0?0:T(Q)<<L;O[0]=M.pred+=Mt}function et(M,O){O[0]|=tt()<<L}var nt=0;function V(M,O){if(nt>0){nt--;return}var Q=k,Mt=H;while(Q<=Mt){var _=X(M.huffmanTableAC),D=_&15,lt=_>>4;if(D===0){if(lt<15){nt=w(lt)+(1<<lt)-1;break}Q+=16;continue}Q+=lt;var W=e[Q];O[W]=T(D)*(1<<L),Q++}}var N=0,I;function wt(M,O){var Q=k,Mt=H,_=0;while(Q<=Mt){var D=e[Q],lt=O[D]<0?-1:1;switch(N){case 0:var W=X(M.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)nt=w(_)+(1<<_),N=4;else _=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");I=T(st),N=_?2:3}continue;case 1:case 2:if(O[D])O[D]+=(tt()<<L)*lt;else if(_--,_===0)N=N==2?3:0;break;case 3:if(O[D])O[D]+=(tt()<<L)*lt;else O[D]=I<<L,N=0;break;case 4:if(O[D])O[D]+=(tt()<<L)*lt;break}Q++}if(N===4){if(nt--,nt===0)N=0}}function x(M,O,Q,Mt,_){var D=Q/K|0,lt=Q%K,W=D*M.v+Mt,st=lt*M.h+_;if(M.blocks[W]===void 0&&P.tolerantDecoding)return;O(M,M.blocks[W][st])}function Y(M,O,Q){var Mt=Q/M.blocksPerLine|0,_=Q%M.blocksPerLine;if(M.blocks[Mt]===void 0&&P.tolerantDecoding)return;O(M,M.blocks[Mt][_])}var _t=d.length,zt,m,G,J,A,Z;if(z)if(k===0)Z=R===0?ft:et;else Z=R===0?V:wt;else Z=at;var q=0,rt,it;if(_t==1)it=d[0].blocksPerLine*d[0].blocksPerColumn;else it=K*v.mcusPerColumn;if(!j)j=it;var St,bt;while(q<it){for(m=0;m<_t;m++)d[m].pred=0;if(nt=0,_t==1){zt=d[0];for(A=0;A<j;A++)Y(zt,Z,q),q++}else for(A=0;A<j;A++){for(m=0;m<_t;m++){zt=d[m],St=zt.h,bt=zt.v;for(G=0;G<bt;G++)for(J=0;J<St;J++)x(zt,Z,q,G,J)}if(q++,q===it)break}if(q===it)do{if(F[E]===255){if(F[E+1]!==0)break}E+=1}while(E<F.length-2);if(ot=0,rt=F[E]<<8|F[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function p(F,E){var v=[],d=E.blocksPerLine,j=E.blocksPerColumn,k=d<<3,H=new Int32Array(64),R=new Uint8Array(64);function L(B,Nt,ot){var tt=E.quantizationTable,X,w,T,at,ft,et,nt,V,N,I=ot,wt;for(wt=0;wt<64;wt++)I[wt]=B[wt]*tt[wt];for(wt=0;wt<8;++wt){var x=8*wt;if(I[1+x]==0&&I[2+x]==0&&I[3+x]==0&&I[4+x]==0&&I[5+x]==0&&I[6+x]==0&&I[7+x]==0){N=u*I[0+x]+512>>10,I[0+x]=N,I[1+x]=N,I[2+x]=N,I[3+x]=N,I[4+x]=N,I[5+x]=N,I[6+x]=N,I[7+x]=N;continue}X=u*I[0+x]+128>>8,w=u*I[4+x]+128>>8,T=I[2+x],at=I[6+x],ft=h*(I[1+x]-I[7+x])+128>>8,V=h*(I[1+x]+I[7+x])+128>>8,et=I[3+x]<<4,nt=I[5+x]<<4,N=X-w+1>>1,X=X+w+1>>1,w=N,N=T*c+at*s+128>>8,T=T*s-at*c+128>>8,at=N,N=ft-nt+1>>1,ft=ft+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=X-at+1>>1,X=X+at+1>>1,at=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=ft*o+V*i+2048>>12,ft=ft*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+x]=X+V,I[7+x]=X-V,I[1+x]=w+nt,I[6+x]=w-nt,I[2+x]=T+et,I[5+x]=T-et,I[3+x]=at+ft,I[4+x]=at-ft}for(wt=0;wt<8;++wt){var Y=wt;if(I[8+Y]==0&&I[16+Y]==0&&I[24+Y]==0&&I[32+Y]==0&&I[40+Y]==0&&I[48+Y]==0&&I[56+Y]==0){N=u*ot[wt+0]+8192>>14,I[0+Y]=N,I[8+Y]=N,I[16+Y]=N,I[24+Y]=N,I[32+Y]=N,I[40+Y]=N,I[48+Y]=N,I[56+Y]=N;continue}X=u*I[0+Y]+2048>>12,w=u*I[32+Y]+2048>>12,T=I[16+Y],at=I[48+Y],ft=h*(I[8+Y]-I[56+Y])+2048>>12,V=h*(I[8+Y]+I[56+Y])+2048>>12,et=I[24+Y],nt=I[40+Y],N=X-w+1>>1,X=X+w+1>>1,w=N,N=T*c+at*s+2048>>12,T=T*s-at*c+2048>>12,at=N,N=ft-nt+1>>1,ft=ft+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=X-at+1>>1,X=X+at+1>>1,at=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=ft*o+V*i+2048>>12,ft=ft*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+Y]=X+V,I[56+Y]=X-V,I[8+Y]=w+nt,I[48+Y]=w-nt,I[16+Y]=T+et,I[40+Y]=T-et,I[24+Y]=at+ft,I[32+Y]=at-ft}for(wt=0;wt<64;++wt){var _t=128+(I[wt]+8>>4);Nt[wt]=_t<0?0:_t>255?255:_t}}y(k*j*8);var P,C;for(var U=0;U<j;U++){var Ft=U<<3;for(P=0;P<8;P++)v.push(new Uint8Array(k));for(var K=0;K<d;K++){L(E.blocks[U][K],R,H);var z=0,yt=K<<3;for(C=0;C<8;C++){var mt=v[Ft+C];for(P=0;P<8;P++)mt[yt+P]=R[z++]}}}return v}function b(F){return F<0?0:F>255?255:F}a.prototype={load:function(E){var v=new XMLHttpRequest;v.open("GET",E,!0),v.responseType="arraybuffer",v.onload=function(){var d=new Uint8Array(v.response||v.mozResponseArrayBuffer);if(this.parse(d),this.onload)this.onload()}.bind(this),v.send(null)},parse:function(E){var v=this.opts.maxResolutionInMP*1000*1000,d=0,j=E.length;function k(){var W=E[d]<<8|E[d+1];return d+=2,W}function H(){var W=k(),st=E.subarray(d,d+W-2);return d+=st.length,st}function R(W){var st=1,Ht=1,Et,Ct;for(Ct in W.components)if(W.components.hasOwnProperty(Ct)){if(Et=W.components[Ct],st<Et.h)st=Et.h;if(Ht<Et.v)Ht=Et.v}var re=Math.ceil(W.samplesPerLine/8/st),je=Math.ceil(W.scanLines/8/Ht);for(Ct in W.components)if(W.components.hasOwnProperty(Ct)){Et=W.components[Ct];var _e=Math.ceil(Math.ceil(W.samplesPerLine/8)*Et.h/st),Ce=Math.ceil(Math.ceil(W.scanLines/8)*Et.v/Ht),yn=re*Et.h,Mn=je*Et.v,br=Mn*yn,vn=[];y(br*256);for(var Sn=0;Sn<Mn;Sn++){var In=[];for(var Fn=0;Fn<yn;Fn++)In.push(new Int32Array(64));vn.push(In)}Et.blocksPerLine=_e,Et.blocksPerColumn=Ce,Et.blocks=vn}W.maxH=st,W.maxV=Ht,W.mcusPerLine=re,W.mcusPerColumn=je}var L=null,P=null,C=null,U,Ft,K=[],z=[],yt=[],mt=[],B=k(),Nt=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=k();while(B!=65497){var ot,tt,X;switch(B){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 w=H();if(B===65534){var T=String.fromCharCode.apply(null,w);this.comments.push(T)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)L={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)P={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var at=k(),ft=at+d-2;while(d<ft){var et=E[d++];y(256);var nt=new Int32Array(64);if(et>>4===0)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=E[d++]}else if(et>>4===1)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=k()}else throw Error("DQT: invalid table spec");K[et&15]=nt}break;case 65472:case 65473:case 65474:k(),U={},U.extended=B===65473,U.progressive=B===65474,U.precision=E[d++],U.scanLines=k(),U.samplesPerLine=k(),U.components={},U.componentsOrder=[];var N=U.scanLines*U.samplesPerLine;if(N>v){var I=Math.ceil((N-v)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var wt=E[d++],x,Y=0,_t=0;for(ot=0;ot<wt;ot++){x=E[d];var zt=E[d+1]>>4,m=E[d+1]&15,G=E[d+2];if(zt<=0||m<=0)throw Error("Invalid sampling factor, expected values above 0");U.componentsOrder.push(x),U.components[x]={h:zt,v:m,quantizationIdx:G},d+=3}R(U),z.push(U);break;case 65476:var J=k();for(ot=2;ot<J;){var A=E[d++],Z=new Uint8Array(16),q=0;for(tt=0;tt<16;tt++,d++)q+=Z[tt]=E[d];y(16+q);var rt=new Uint8Array(q);for(tt=0;tt<q;tt++,d++)rt[tt]=E[d];ot+=17+q,(A>>4===0?mt:yt)[A&15]=f(Z,rt)}break;case 65501:k(),Ft=k();break;case 65500:k(),k();break;case 65498:var it=k(),St=E[d++],bt=[],M;for(ot=0;ot<St;ot++){M=U.components[E[d++]];var O=E[d++];M.huffmanTableDC=mt[O>>4],M.huffmanTableAC=yt[O&15],bt.push(M)}var Q=E[d++],Mt=E[d++],_=E[d++],D=l(E,d,U,bt,Ft,Q,Mt,_>>4,_&15,this.opts);d+=D;break;case 65535:if(E[d]!==255)d--;break;default:if(E[d-3]==255&&E[d-2]>=192&&E[d-2]<=254){d-=3;break}else if(B===224||B==225){if(Nt!==-1)throw Error(`first unknown JPEG marker at offset ${Nt.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${(d-1).toString(16)}`);Nt=d-1;let W=k();if(E[d+W-2]===255){d+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=k()}if(z.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<z.length;ot++){var lt=z[ot].components;for(var tt in lt)lt[tt].quantizationTable=K[lt[tt].quantizationIdx],delete lt[tt].quantizationIdx}this.width=U.samplesPerLine,this.height=U.scanLines,this.jfif=L,this.adobe=P,this.components=[];for(var ot=0;ot<U.componentsOrder.length;ot++){var M=U.components[U.componentsOrder[ot]];this.components.push({lines:p(U,M),scaleX:M.h/U.maxH,scaleY:M.v/U.maxV})}},getData:function(E,v){var d=this.width/E,j=this.height/v,k,H,R,L,P,C,U,Ft,K,z,yt=0,mt,B,Nt,ot,tt,X,w,T,at,ft,et,nt=E*v*this.components.length;y(nt);var V=new Uint8Array(nt);switch(this.components.length){case 1:k=this.components[0];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j];for(K=0;K<E;K++)mt=P[0|K*k.scaleX*d],V[yt++]=mt}break;case 2:k=this.components[0],H=this.components[1];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j];for(K=0;K<E;K++)mt=P[0|K*k.scaleX*d],V[yt++]=mt,mt=C[0|K*H.scaleX*d],V[yt++]=mt}break;case 3:if(et=!0,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],H=this.components[1],R=this.components[2];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j],U=R.lines[0|z*R.scaleY*j];for(K=0;K<E;K++){if(!et)T=P[0|K*k.scaleX*d],at=C[0|K*H.scaleX*d],ft=U[0|K*R.scaleX*d];else mt=P[0|K*k.scaleX*d],B=C[0|K*H.scaleX*d],Nt=U[0|K*R.scaleX*d],T=b(mt+1.402*(Nt-128)),at=b(mt-0.3441363*(B-128)-0.71413636*(Nt-128)),ft=b(mt+1.772*(B-128));V[yt++]=T,V[yt++]=at,V[yt++]=ft}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(et=!1,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],H=this.components[1],R=this.components[2],L=this.components[3];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j],U=R.lines[0|z*R.scaleY*j],Ft=L.lines[0|z*L.scaleY*j];for(K=0;K<E;K++){if(!et)tt=P[0|K*k.scaleX*d],X=C[0|K*H.scaleX*d],w=U[0|K*R.scaleX*d],ot=Ft[0|K*L.scaleX*d];else mt=P[0|K*k.scaleX*d],B=C[0|K*H.scaleX*d],Nt=U[0|K*R.scaleX*d],ot=Ft[0|K*L.scaleX*d],tt=255-b(mt+1.402*(Nt-128)),X=255-b(mt-0.3441363*(B-128)-0.71413636*(Nt-128)),w=255-b(mt+1.772*(B-128));V[yt++]=255-tt,V[yt++]=255-X,V[yt++]=255-w,V[yt++]=255-ot}}break;default:throw Error("Unsupported color mode")}return V},copyToImageData:function(E,v){var{width:d,height:j,data:k}=E,H=this.getData(d,j),R=0,L=0,P,C,U,Ft,K,z,yt,mt,B;switch(this.components.length){case 1:for(C=0;C<j;C++)for(P=0;P<d;P++)if(U=H[R++],k[L++]=U,k[L++]=U,k[L++]=U,v)k[L++]=255;break;case 3:for(C=0;C<j;C++)for(P=0;P<d;P++)if(yt=H[R++],mt=H[R++],B=H[R++],k[L++]=yt,k[L++]=mt,k[L++]=B,v)k[L++]=255;break;case 4:for(C=0;C<j;C++)for(P=0;P<d;P++)if(K=H[R++],z=H[R++],U=H[R++],Ft=H[R++],yt=255-b(K*(1-Ft/255)+Ft),mt=255-b(z*(1-Ft/255)+Ft),B=255-b(U*(1-Ft/255)+Ft),k[L++]=yt,k[L++]=mt,k[L++]=B,v)k[L++]=255;break;default:throw Error("Unsupported color mode")}}};var g=0,$=0;function y(F=0){var E=g+F;if(E>$){var v=Math.ceil((E-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${v}MB`)}g=E}return a.resetMaxMemoryUsage=function(F){g=0,$=F},a.getBytesAllocated=function(){return g},a.requestMemoryAllocation=y,a}();if(typeof Ni<"u")Ni.exports=xs;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=xs;function xs(t,e={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...e},i=new Uint8Array(t),o=new Fi;o.opts=r,Fi.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{Fi.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);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(u,r.formatAsRGBA),u}});var qs=$t((zw,Zs)=>{var El=Ws(),yl=Qs();Zs.exports={encode:El,decode:yl}});var Ri=$t((Bw,Cs)=>{var Ml=Gt("util"),_s=Gt("stream"),Dt=Cs.exports=function(){_s.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Ml.inherits(Dt,_s);Dt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Dt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(t))n=t;else n=Buffer.from(t,e||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Dt.prototype.end=function(t,e){if(t)this.write(t,e);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Dt.prototype.destroySoon=Dt.prototype.end;Dt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Dt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Dt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];if(e.length>t.length)this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length));else this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e)};Dt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);while(e<t.length){let i=this._buffers[n++],o=Math.min(i.length,t.length-e);if(i.copy(r,e,0,o),e+=o,o!==i.length)this._buffers[--n]=i.slice(o)}if(n>0)this._buffers.splice(0,n);this._buffered-=t.length,t.func.call(this,r)};Dt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var Oi=$t((vl)=>{var Ee=[{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]}];vl.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,o=(t-r)/8,s=(e-i)/8;for(let c=0;c<Ee.length;c++){let u=Ee[c],h=o*u.x.length,a=s*u.y.length;for(let f=0;f<u.x.length;f++)if(u.x[f]<r)h++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)a++;else break;if(h>0&&a>0)n.push({width:h,height:a,index:c})}return n};vl.getInterlaceIterator=function(t){return function(e,n,r){let i=e%Ee[r].x.length,o=(e-i)/Ee[r].x.length*8+Ee[r].x[i],s=n%Ee[r].y.length,c=(n-s)/Ee[r].y.length*8+Ee[r].y[s];return o*4+c*t*4}}});var Hi=$t((tb,Xs)=>{Xs.exports=function(e,n,r){let i=e+n-r,o=Math.abs(i-e),s=Math.abs(i-n),c=Math.abs(i-r);if(o<=s&&o<=c)return e;if(s<=c)return n;return r}});var ji=$t((eb,Ys)=>{var Fl=Oi(),Nl=Hi();function Vs(t,e,n){let r=t*e;if(n!==8)r=Math.ceil(r/(8/n));return r}var Ye=Ys.exports=function(t,e){let{width:n,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let c=Fl.getImagePasses(n,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:Vs(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:Vs(n,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Ye.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ye.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let o=0;o<n;o++){let s=t[1+o],c=o>i?e[o-r]:0;e[o]=s+c}};Ye.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let o=t[1+i],s=r?r[i]:0;e[i]=o+s}};Ye.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=Math.floor((h+u)/2);e[s]=c+a}};Ye.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=s>i&&o?o[s-r]:0,f=Nl(h,u,a);e[s]=c+f}};Ye.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw Error("Unrecognised filter type - "+e)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ds=$t((nb,Bs)=>{var Rl=Gt("util"),zs=Ri(),Ol=ji(),Hl=Bs.exports=function(t){zs.call(this);let e=[],n=this;this._filter=new Ol(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Rl.inherits(Hl,zs)});var ze=$t((rb,tc)=>{tc.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 Li=$t((ib,ec)=>{var Pi=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)if(e&1)e=3988292384^e>>>1;else e=e>>>1;Pi[t]=e}})();var Gi=ec.exports=function(){this._crc=-1};Gi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Pi[(this._crc^t[e])&255]^this._crc>>>8;return!0};Gi.prototype.crc32=function(){return this._crc^-1};Gi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Pi[(e^t[n])&255]^e>>>8;return e^-1}});var Ti=$t((ob,nc)=>{var Rt=ze(),jl=Li(),Ot=nc.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Rt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Rt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Rt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Rt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Rt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Rt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Rt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let e=Rt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&n!==Rt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new jl,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(Error("Crc error - "+e+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Rt.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(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Rt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:Boolean(c),palette:Boolean(i&Rt.COLORTYPE_PALETTE),color:Boolean(i&Rt.COLORTYPE_COLOR),alpha:Boolean(i&Rt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Rt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}if(this._colorType===Rt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Rt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Rt.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Rt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(e);let n=t-e.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ai=$t((Ul)=>{var rc=Oi(),Pl=[function(){},function(t,e,n,r){if(r===e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Gl=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Ll(t,e){let n=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,a,f,l,p;switch(e){default:throw Error("unrecognised depth");case 16:l=t[r],r++,n.push((o<<8)+l);break;case 4:l=o&15,p=o>>4,n.push(p,l);break;case 2:a=o&3,f=o>>2&3,l=o>>4&3,p=o>>6&3,n.push(p,l,f,a);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,a=o>>4&1,f=o>>5&1,l=o>>6&1,p=o>>7&1,n.push(p,l,f,a,h,u,c,s);break}}return{get:function(o){while(n.length<o)i();let s=n.slice(0,o);return n=n.slice(o),s},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Tl(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let a=0;a<s;a++){let f=n(a,h,u);Pl[r](e,i,f,o),o+=r}return o}function Al(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let a=0;a<s;a++){let f=i.get(r),l=n(a,h,u);Gl[r](e,f,l,o)}i.resetAfterLine()}}Ul.dataToBitMap=function(t,e){let{width:n,height:r,depth:i,bpp:o,interlace:s}=e,c;if(i!==8)c=Ll(t,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let h=Math.pow(2,i)-1,a=0,f,l;if(s)f=rc.getImagePasses(n,r),l=rc.getInterlaceIterator(n,r);else{let p=0;l=function(){let b=p;return p+=4,b},f=[{width:n,height:r}]}for(let p=0;p<f.length;p++)if(i===8)a=Tl(f[p],u,l,o,t,a);else Al(f[p],u,l,o,c,h);if(i===8){if(a!==t.length)throw Error("extra data found")}else c.end();return u}});var Ui=$t((cb,ic)=>{function Jl(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)e[o+h]=u[h];o+=4}}function Wl(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)e[o+h]=0;o+=4}}function xl(t,e,n,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<n;h++){for(let a=0;a<4;a++)e[c+a]=Math.floor(t[c+a]*o/s+0.5);c+=4}}ic.exports=function(t,e,n=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=e,h=t;if(s===3)Jl(t,h,i,o,u);else{if(c)Wl(t,h,i,o,c);if(r!==8&&!n){if(r===16)h=Buffer.alloc(i*o*4);xl(t,h,i,o,r)}}return h}});var cc=$t((ub,sc)=>{var Ql=Gt("util"),Ki=Gt("zlib"),oc=Ri(),Zl=Ds(),ql=Ti(),_l=Ai(),Cl=Ui(),oe=sc.exports=function(t){oc.call(this),this._parser=new ql(t,{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=t,this.writable=!0,this._parser.start()};Ql.inherits(oe,oc);oe.prototype._handleError=function(t){if(this.emit("error",t),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};oe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ki.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Ki.Z_MIN_CHUNK);this._inflate=Ki.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};oe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Zl(this._bitmapInfo)};oe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};oe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};oe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};oe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};oe.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};oe.prototype._complete=function(t){if(this.errord)return;let e;try{let n=_l.dataToBitMap(t,this._bitmapInfo);e=Cl(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var hc=$t((hb,uc)=>{var Xt=ze();uc.exports=function(t,e,n,r){let i=[Xt.COLORTYPE_COLOR_ALPHA,Xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let b=function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&b)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(e*n*u),a=0,f=0,l=r.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 p(){let b,g,$,y=s;switch(r.inputColorType){case Xt.COLORTYPE_COLOR_ALPHA:y=o[a+3],b=o[a],g=o[a+1],$=o[a+2];break;case Xt.COLORTYPE_COLOR:b=o[a],g=o[a+1],$=o[a+2];break;case Xt.COLORTYPE_ALPHA:y=o[a+1],b=o[a],g=b,$=b;break;case Xt.COLORTYPE_GRAYSCALE:b=o[a],g=b,$=b;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,b=Math.min(Math.max(Math.round((1-y)*l.red+y*b),0),s),g=Math.min(Math.max(Math.round((1-y)*l.green+y*g),0),s),$=Math.min(Math.max(Math.round((1-y)*l.blue+y*$),0),s)}return{red:b,green:g,blue:$,alpha:y}}for(let b=0;b<n;b++)for(let g=0;g<e;g++){let $=p(o,a);switch(r.colorType){case Xt.COLORTYPE_COLOR_ALPHA:case Xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[f]=$.red,h[f+1]=$.green,h[f+2]=$.blue,i)h[f+3]=$.alpha}else if(h.writeUInt16BE($.red,f),h.writeUInt16BE($.green,f+2),h.writeUInt16BE($.blue,f+4),i)h.writeUInt16BE($.alpha,f+6);break;case Xt.COLORTYPE_ALPHA:case Xt.COLORTYPE_GRAYSCALE:{let y=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(h[f]=y,i)h[f+1]=$.alpha}else if(h.writeUInt16BE(y,f),i)h.writeUInt16BE($.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}a+=c,f+=u}return h}});var lc=$t((ab,fc)=>{var ac=Hi();function Xl(t,e,n,r,i){for(let o=0;o<n;o++)r[i+o]=t[e+o]}function Vl(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++)r+=Math.abs(t[o]);return r}function Yl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=t[e+s]-c;r[i+s]=u}}function zl(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=t[e+o]-s;i+=Math.abs(c)}return i}function Bl(t,e,n,r,i){for(let o=0;o<n;o++){let s=e>0?t[e+o-n]:0,c=t[e+o]-s;r[i+o]=c}}function Dl(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++){let s=e>0?t[o-n]:0,c=t[o]-s;r+=Math.abs(c)}return r}function tg(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=t[e+s]-(c+u>>1);r[i+s]=h}}function eg(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=t[e+o]-(s+c>>1);i+=Math.abs(u)}return i}function ng(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=e>0&&s>=o?t[e+s-(n+o)]:0,a=t[e+s]-ac(c,u,h);r[i+s]=a}}function rg(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=e>0&&o>=r?t[e+o-(n+r)]:0,h=t[e+o]-ac(s,c,u);i+=Math.abs(h)}return i}var ig={0:Xl,1:Yl,2:Bl,3:tg,4:ng},og={0:Vl,1:zl,2:Dl,3:eg,4:rg};fc.exports=function(t,e,n,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=e*i,c=0,u=0,h=Buffer.alloc((s+1)*n),a=o[0];for(let f=0;f<n;f++){if(o.length>1){let l=1/0;for(let p=0;p<o.length;p++){let b=og[o[p]](t,u,s,i);if(b<l)a=o[p],l=b}}h[c]=a,c++,ig[a](t,u,s,h,c,i),c+=s,u+=s}return h}});var Ji=$t((fb,gc)=>{var Lt=ze(),sg=Li(),cg=hc(),ug=lc(),hg=Gt("zlib"),ye=gc.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||hg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Lt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Lt.COLORTYPE_COLOR_ALPHA,[Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};ye.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ye.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ye.prototype.filterData=function(t,e,n){let r=cg(t,e,n,this._options),i=Lt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ug(r,e,n,this._options,i)};ye.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e)e.copy(r,8);return r.writeInt32BE(sg.crc32(r.slice(4,r.length-4)),r.length-4),r};ye.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Lt.GAMMA_DIVISION),0),this._packChunk(Lt.TYPE_gAMA,e)};ye.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Lt.TYPE_IHDR,n)};ye.prototype.packIDAT=function(t){return this._packChunk(Lt.TYPE_IDAT,t)};ye.prototype.packIEND=function(){return this._packChunk(Lt.TYPE_IEND,null)}});var wc=$t((lb,pc)=>{var ag=Gt("util"),dc=Gt("stream"),fg=ze(),lg=Ji(),mc=pc.exports=function(t){dc.call(this);let e=t||{};this._packer=new lg(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ag.inherits(mc,dc);mc.prototype.pack=function(t,e,n,r){if(this.emit("data",Buffer.from(fg.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);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 Mc=$t((Ln,yc)=>{var bc=Gt("assert").ok,Be=Gt("zlib"),gg=Gt("util"),$c=Gt("buffer").kMaxLength;function Pe(t){if(!(this instanceof Pe))return new Pe(t);if(t&&t.chunkSize<Be.Z_MIN_CHUNK)t.chunkSize=Be.Z_MIN_CHUNK;if(Be.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function dg(t){return new Pe(t)}function kc(t,e){if(e)process.nextTick(e);if(!t._handle)return;t._handle.close(),t._handle=null}Pe.prototype._processChunk=function(t,e,n){if(typeof n==="function")return Be.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,a;this.on("error",function(b){a=b});function f(b,g){if(r._hadError)return;let $=o-g;if(bc($>=0,"have should not go down"),$>0){let y=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,y.length>s)y=y.slice(0,s);if(u.push(y),h+=y.length,s-=y.length,s===0)return!1}if(g===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(g===0)return c+=i-b,i=b,!0;return!1}bc(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(e,t,c,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&f(l[0],l[1]));if(this._hadError)throw a;if(h>=$c)throw kc(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+$c.toString(16)+" bytes");let p=Buffer.concat(u,h);return kc(this),p};gg.inherits(Pe,Be.Inflate);function mg(t,e){if(typeof e==="string")e=Buffer.from(e);if(!(e instanceof Buffer))throw TypeError("Not a string or buffer");let n=t._finishFlushFlag;if(n==null)n=Be.Z_FINISH;return t._processChunk(e,n)}function Ec(t,e){return mg(new Pe(e),t)}yc.exports=Ln=Ec;Ln.Inflate=Pe;Ln.createInflate=dg;Ln.inflateSync=Ec});var Wi=$t((gb,Sc)=>{var vc=Sc.exports=function(t){this._buffer=t,this._reads=[]};vc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};vc.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.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 Ic=$t((bg)=>{var pg=Wi(),wg=ji();bg.process=function(t,e){let n=[],r=new pg(t);return new wg(e,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Oc=$t((mb,Rc)=>{var Fc=!0,Nc=Gt("zlib"),kg=Mc();if(!Nc.deflateSync)Fc=!1;var Eg=Wi(),yg=Ic(),Mg=Ti(),vg=Ai(),Sg=Ui();Rc.exports=function(t,e){if(!Fc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(v){n=v}let i;function o(v){i=v}function s(v){i.transColor=v}function c(v){i.palette=v}function u(){i.alpha=!0}let h;function a(v){h=v}let f=[];function l(v){f.push(v)}let p=new Eg(t);if(new Mg(e,{read:p.read.bind(p),error:r,metadata:o,gamma:a,palette:c,transColor:s,inflateData:l,simpleTransparency:u}).start(),p.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(i.interlace)$=Nc.inflateSync(g);else{let d=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=kg(g,{chunkSize:d,maxLength:d})}if(g=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let y=yg.process($,i);g=null;let F=vg.dataToBitMap(y,i);y=null;let E=Sg(F,i,e.skipRescale);return i.data=E,i.gamma=h||0,i}});var Gc=$t((pb,Pc)=>{var Hc=!0,jc=Gt("zlib");if(!jc.deflateSync)Hc=!1;var Ig=ze(),Fg=Ji();Pc.exports=function(t,e){if(!Hc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Fg(e||{}),i=[];if(i.push(Buffer.from(Ig.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=jc.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var Lc=$t((Og)=>{var Ng=Oc(),Rg=Gc();Og.read=function(t,e){return Ng(t,e||{})};Og.write=function(t,e){return Rg(t,e)}});var Ac=$t((Ag)=>{var Pg=Gt("util"),Tc=Gt("stream"),Gg=cc(),Lg=wc(),Tg=Lc(),At=Ag.PNG=function(t){if(Tc.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Gg(t),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(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Lg(t),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"))};Pg.inherits(At,Tc);At.sync=Tg;At.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};At.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};At.prototype.write=function(t){return this._parser.write(t),!0};At.prototype.end=function(t){this._parser.end(t)};At.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};At.prototype._gamma=function(t){this.gamma=t};At.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};At.bitblt=function(t,e,n,r,i,o,s,c){if(n|=0,r|=0,i|=0,o|=0,s|=0,c|=0,n>t.width||r>t.height||n+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>e.width||c>e.height||s+i>e.width||c+o>e.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(c+u)*e.width+s<<2,(r+u)*t.width+n<<2,(r+u)*t.width+n+i<<2)};At.prototype.bitblt=function(t,e,n,r,i,o,s){return At.bitblt(this,t,e,n,r,i,o,s),this};At.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};At.prototype.adjustGamma=function(){At.adjustGamma(this)}});var Go=$t((zk,Xa)=>{var Po={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},c0={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},u0={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Po.up():"");if(t)e+=Po.left;return e}};Xa.exports={cursor:Po,scroll:c0,erase:u0,beep:"\x07"}});import{spawnSync as Nw}from"node:child_process";import{isMainThread as Rw}from"node:worker_threads";import{parseArgs as Mw}from"node:util";var ie={name:"@kecan0406/ttheme",version:"1.0.40",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",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 hh}from"node:fs";import{basename as Dd,join as nr}from"node:path";var rl=/^#[0-9a-f]{6}$/;function ds(t){return rl.test(t)}function jt(t){let e=Number.parseInt(t.slice(1),16);return[e>>16&255,e>>8&255,e&255]}function Bt(t){let[e,n,r]=jt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*e+0.7152*n+0.0722*r}function fe(t,e){let n=Bt(t),r=Bt(e);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Mr(t,e){return Math.round(fe(t,e)*100)/100}function il(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function ms(t){let[e,n,r]=jt(t).map(il),i=Math.cbrt(0.4122214708*e+0.5363325363*n+0.0514459929*r),o=Math.cbrt(0.2119034982*e+0.6806995451*n+0.1073969566*r),s=Math.cbrt(0.0883024619*e+0.2817188376*n+0.6299787005*r),c=1.9779984951*i-2.428592205*o+0.4505937099*s,u=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(c,u),h:(Math.atan2(u,c)*180/Math.PI+360)%360}}var $e=7,ps=3,$i=0.15,ws=1.6,yi=[1,2,3,4,5,6,9,10,11,12,13,14],bs=[7,15],vr=[1,2,3,4,5,6],Ms={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},ol=0.03,ki=25,vs=15,Ss=0.08;function le(t,e){let n=t.ansi[e];if(n===void 0)throw Error(`${t.name}: missing ANSI ${e}`);return n}function Ei(t,e,n){let r=t.background;return e.flatMap((i)=>{let o=le(t,i);return fe(o,r)<n?[`ANSI ${i} ${o} on ${r} is ${Mr(o,r)}:1, needs ${n}:1`]:[]})}function $s(t,e){return Math.min(...e.map((n)=>fe(le(t,n),t.background)))}var Is=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:$e,measure:({foreground:t,background:e})=>fe(t,e),check:({foreground:t,background:e})=>fe(t,e)<$e?[`foreground ${t} on ${e} is ${Mr(t,e)}:1, needs ${$e}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ps,measure:(t)=>$s(t,yi),check:(t)=>Ei(t,yi,ps)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:$i,measure:(t)=>Bt(le(t,0)),check:(t)=>{let e=le(t,0);return Bt(e)>$i?[`ANSI 0 ${e} has luminance ${Bt(e).toFixed(3)}, needs <= ${$i}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:$e,measure:(t)=>$s(t,bs),check:(t)=>Ei(t,bs,$e)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:ws,measure:(t)=>fe(le(t,8),t.background),check:(t)=>Ei(t,[8],ws)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:$e,measure:({foreground:t,selectionBackground:e})=>e===void 0?Number.NaN:fe(t,e),check:({foreground:t,selectionBackground:e})=>e!==void 0&&fe(t,e)<$e?[`foreground ${t} on selection ${e} is ${Mr(t,e)}:1, needs ${$e}:1`]:[]}];function Mi(t,e){let n=Math.abs(t-e)%360;return Math.min(n,360-n)}var vi=(t)=>t>8?t-8:t;function Fs(t){let e=t.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(e.flatMap((n)=>vr.includes(vi(n))?[n,n>8?n-8:n+8]:[n]))}function Rn(t,e){let n=ms(le(t,e));return n.c<ol?void 0:n}function ks(t){let e=Fs(t);return yi.flatMap((n)=>{let r=Rn(t,n),i=Ms[vi(n)];if(r===void 0||i===void 0||e.has(n))return[];let o=Mi(r.h,i.center)-i.width;return o>0?[{slot:n,hue:r.h,over:o}]:[]})}function Es(t){let e=new Set(t.signatureSlots);return vr.flatMap((n)=>{let r=Rn(t,n),i=Rn(t,n+8);if(r===void 0||i===void 0||e.has(`ansi${n}`)&&e.has(`ansi${n+8}`))return[];return[{normal:n,gap:Mi(r.h,i.h)}]})}function ys(t){let e=Fs(t);return[0,8].flatMap((n)=>vr.flatMap((r)=>vr.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[n+r,n+i],c=Rn(t,o),u=Rn(t,s);if(c===void 0||u===void 0||e.has(o)&&e.has(s))return[];return Mi(c.h,u.h)<vs&&Math.abs(c.l-u.l)<Ss?[[o,s]]:[]})))}var sl=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(t)=>Math.max(0,...ks(t).map((e)=>e.over)),check:(t)=>ks(t).map(({slot:e,hue:n,over:r})=>{let i=Ms[vi(e)];return`ANSI ${e} ${le(t,e)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:ki,measure:(t)=>Math.max(0,...Es(t).map((e)=>e.gap)),check:(t)=>Es(t).filter((e)=>e.gap>ki).map(({normal:e,gap:n})=>`ANSI ${e+8} is ${n.toFixed(0)}° from ANSI ${e}, needs <= ${ki}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(t)=>ys(t).length,check:(t)=>ys(t).map(([e,n])=>`ANSI ${e} ${le(t,e)} and ANSI ${n} ${le(t,n)} are within ${vs}° hue and ${Ss} lightness`)}],Sr=[...Is,...sl],Lw=Sr.map((t)=>t.rule),Ir=Sr.map(({rule:t,label:e,unit:n,min:r,max:i})=>({rule:t,label:e,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Ns(t){return Sr.map((e)=>Math.round(e.measure(t)*1000)/1000)}function Rs(t,e){return t.filter((n)=>!e.waive.includes(n.rule)).flatMap((n)=>n.check(e).map((r)=>({theme:e.name,rule:n.rule,detail:r})))}function cl(t){return Rs(Sr,t)}function Os(t){return Rs(Is,t)}function Hs(t){return t.flatMap(cl)}var ul=["black","red","green","yellow","blue","magenta","cyan","white"];function js(t,e){return[t,...ul.map((n,r)=>`${n} = '${e[r]}'`),""].join(`
3
- `)}var On={id:"alacritty",limits:"no runtime color API (OSC only)",emit(t){let e=[...Xe(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",js("[colors.normal]",t.ansi.slice(0,8)),js("[colors.bright]",t.ansi.slice(8,16))].join(`
4
- `);return[{path:`alacritty/themes/${ut(t.name)}.toml`,content:e}]}};var Hn={id:"ghostty",emit(t){let e=[...Xe(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
5
- `);return[{path:`ghostty/themes/${ut(t.name)}`,content:e}]}};function ke(t){let[e,n,r]=jt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":e/255}}function Ps(t){return{...Object.fromEntries(t.ansi.map((e,n)=>[`Ansi ${n} Color`,ke(e)])),"Background Color":ke(t.background),"Bold Color":ke(t.foreground),"Cursor Color":ke(t.cursor),"Cursor Text Color":ke(t.background),"Foreground Color":ke(t.foreground),"Selected Text Color":ke(t.foreground),"Selection Color":ke(t.selectionBackground)}}function hl(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function Gs(t,e,n,r){let i=(s,c)=>({Name:`ttheme · ${c}`,Guid:`ttheme-${c}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...hl(e.get(s.name)),...Ps(s)}),o=[...n?[i(n,"default")]:[],...t.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
6
- `}function al(t,e){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(e).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
7
- `)}var jn={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let e=['<?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(Ps(t)).map(([n,r])=>al(n,r)),"</dict>","</plist>",""].join(`
8
- `);return[{path:`iterm2/${ut(t.name)}.itermcolors`,content:e}]}};var Pn={id:"kitty",emit(t){let e=[...Xe(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
9
- `);return[{path:`kitty/themes/${ut(t.name)}.conf`,content:e}]}};function Ls(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, 'ttheme-' + palette + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
10
- `)}import{createHash as Jg}from"node:crypto";import{existsSync as zc,mkdirSync as Wg,readdirSync as xg,readFileSync as Qg,renameSync as Bc,rmSync as tn}from"node:fs";import{basename as Zg,isAbsolute as qg,join as ct}from"node:path";import{chmodSync as fl,copyFileSync as ll,existsSync as Ve,mkdirSync as gl,readFileSync as Si,realpathSync as dl,renameSync as ml,rmSync as Ts,statSync as pl,writeFileSync as wl}from"node:fs";import{dirname as bl}from"node:path";function As(t){return`${t}.ttheme.bak`}var $l=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Ii(t){let e=As(t);if(Ve(t)&&!Ve(e)&&!$l.test(Si(t,"utf8")))ll(t,e)}function Tt(t,e){let n=Ve(t)?dl(t):t;gl(bl(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(wl(r,e),Ve(n))fl(r,pl(n).mode&4095);ml(r,n)}function Gn(t,e){if((Ve(t)?Si(t,"utf8"):void 0)===e)return!1;return Ii(t),Tt(t,e),!0}function Us(t,e){let n=As(t),r=Ve(n)?Si(n,"utf8"):void 0;if(e===""&&r===void 0)return Ts(t,{force:!0}),"removed";if(Tt(t,e),r===void 0||r===e)return Ts(n,{force:!0}),"restored";return"kept backup"}var Jc=yr(qs(),1),Nr=yr(Ac(),1),Uc=[137,80,78,71,13,10,26,10],Wc=13;function Tn(t){return t.length>=Uc.length&&Uc.every((e,n)=>t[n]===e)}function Ug(t){let e=Nr.PNG.sync.read(Buffer.from(t));return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function xc(t,e){if(Tn(t)){let n=An(t);if(n&&n.width*n.height>e)throw Error(`${n.width}×${n.height} is over ${e/1e6} megapixels`);return Ug(t)}if(t[0]===255&&t[1]===216){let n=Jc.decode(t,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:e/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function De(t){let e=new Nr.PNG({width:t.width,height:t.height});return e.data=Buffer.from(t.data),Nr.PNG.sync.write(e)}function Kc(t,e){for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let i=0;i<e.length&&r;i++)r=t[n+i]===e.charCodeAt(i);if(r)return n}return-1}function An(t){if(t.length<33||!Tn(t))return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint32(16),r=e.getUint32(20);if(t[25]===4||t[25]===6)return{width:n,height:r,alpha:!0};let i=Kc(t,"IDAT");return{width:n,height:r,alpha:Kc(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function Qc(t,e=Wc){let{width:n,height:r}=t,i=-1,o=-1;for(let s=0;s<t.height;s++)for(let c=0;c<t.width;c++)if((t.data[(s*t.width+c)*4+3]??0)>=e)n=Math.min(n,c),i=Math.max(i,c),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:n,y:r,w:i-n+1,h:o-r+1}}function Un(t,e={x:0,y:0,w:t.width,h:t.height}){let n=0;for(let r=e.y;r<e.y+e.h;r++)for(let i=e.x;i<e.x+e.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<Wc)n++;return Math.round(n*100/(e.w*e.h))}function Kg(t,e){if(e<=1)return t;let n=Math.max(1,Math.floor(t.width/e)),r=Math.max(1,Math.floor(t.height/e)),i=new Uint8Array(n*r*4),o=t.data;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=0,h=0,a=0,f=0;for(let p=0;p<e;p++)for(let b=0;b<e;b++){let g=((s*e+p)*t.width+c*e+b)*4,$=o[g+3]??0;u+=(o[g]??0)*$,h+=(o[g+1]??0)*$,a+=(o[g+2]??0)*$,f+=$}let l=(s*n+c)*4;if(f>0)i[l]=Math.round(u/f),i[l+1]=Math.round(h/f),i[l+2]=Math.round(a/f);i[l+3]=Math.round(f/(e*e))}return{width:n,height:r,data:i}}function Zc(t,e,n){let r=Math.min(e/t.width,n/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=Rr(t,{x:0,y:0,w:t.width,h:t.height},i,o),c=new Uint8Array(e*n*4),u=Math.floor((e-i)/2),h=Math.floor((n-o)/2);for(let a=0;a<o;a++)c.set(s.data.subarray(a*i*4,(a+1)*i*4),((h+a)*e+u)*4);return{width:e,height:n,data:c}}function Rr(t,e,n,r){let i=Math.max(1,Math.floor(Math.min(e.w/n,e.h/r))),o=Kg(t,i),s=o.data,c=new Uint8Array(n*r*4);for(let u=0;u<r;u++){let h=Math.min(o.height-1,Math.max(0,e.y/i+(u+0.5)*e.h/i/r-0.5)),a=Math.floor(h),f=Math.min(o.height-1,a+1),l=h-a;for(let p=0;p<n;p++){let b=Math.min(o.width-1,Math.max(0,e.x/i+(p+0.5)*e.w/i/n-0.5)),g=Math.floor(b),$=Math.min(o.width-1,g+1),y=b-g,F=(a*o.width+g)*4,E=(a*o.width+$)*4,v=(f*o.width+g)*4,d=(f*o.width+$)*4,j=(s[F+3]??0)*(1-y)*(1-l),k=(s[E+3]??0)*y*(1-l),H=(s[v+3]??0)*(1-y)*l,R=(s[d+3]??0)*y*l,L=j+k+H+R,P=(u*n+p)*4;if(L>0)for(let C=0;C<3;C++){let U=(s[F+C]??0)*j+(s[E+C]??0)*k+(s[v+C]??0)*H+(s[d+C]??0)*R;c[P+C]=Math.round(U/L)}c[P+3]=Math.round(L)}}return{width:n,height:r,data:c}}var qc={width:2560,height:1550},_g=2560,Cg=0.1,ge={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Xg=Bt(Qi("#19161e","#9b86c8",0.2)),Vg="shelf",Or="originals",Yg="images.json",xi=1;function Qi(t,e,n){let r=jt(t),i=jt(e);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*n).toString(16).padStart(2,"0")).join("")}`}function zg(t,e){if(e==="background"||e==="foreground"||e==="cursor")return t[e];if(e==="selection"&&t.selection)return t.selection;let n=/^ansi(\d|1[0-5])$/.exec(e),r=n?t.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${e}`);return r}function _c(t){if(t(1))return 1;let e=0,n=1;for(let r=0;r<40;r++){let i=(e+n)/2;if(t(i))e=i;else n=i}return e}function Cc(t,e){let n=zg(t,e),i=_c((h)=>Os({name:t.name,background:Qi(t.background,n,h),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),o=_c((h)=>Bt(Qi(t.background,n,h))<=Xg),s=Math.floor(Math.min(i,o)*1000)/1000,c=jt(t.background),u=Math.hypot(...jt(n).map((h,a)=>(h-(c[a]??0))*s));return{slot:e,color:n,cap:i,matched:o,opacity:s,reach:u}}function jr(t,e){let n=Cc(t,"cursor");if(n.opacity>=Cg)return n;return e.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Cc(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function Zi(t,e,n){let r=jt(e),i=jt(n),o=t.data;for(let s=0;s<o.length;s+=4){let c=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)+((i[u]??0)-(r[u]??0))*c)}return t}function Bg(t,e,n){let r=jt(e),i=t.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let c=(i[s+3]??0)/255*n;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)*(1-c)+(i[s+u]??0)*c);o[s+3]=255}return{width:t.width,height:t.height,data:o}}function Dc(t){return Qc(t)??{x:0,y:0,w:t.width,h:t.height}}function Dg(t,e){if(t<=0||e<=0)return qc;let n=Math.min(1,qc.width/Math.max(t,e));return{width:Math.round(t*n),height:Math.round(e*n)}}function td(t,e){let n=Math.min(1,_g/Math.max(e.w,e.h));return Rr(t,e,Math.round(e.w*n),Math.round(e.h*n))}function tu(t,e,n,r){if(r<ge.stands){let u=t.w*n>t.h*e?{x:t.x+(t.w-t.h*e/n)/2,y:t.y,w:t.h*e/n,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*n/e};return{crop:u,at:{x:0,y:0,w:e,h:n},focus:(u.y-t.y+u.h/2)/t.h}}let i=Math.max(ge.tall*n,ge.reach*e*t.h/t.w),o=i*t.w/t.h;if(o>ge.widest*e)o=ge.widest*e,i=o*t.h/t.w;let s=ge.headroom*n,c=Math.min(1,(n-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*c},at:{x:e*(1-ge.margin)-o,y:s,w:o,h:i*c},focus:Math.min(1,(n/2-s)/i)}}function eu(t,e,n,r){let i=Math.max(1,Math.round(e.at.w)),o=Math.max(1,Math.round(e.at.h)),s=Rr(t,e.crop,i,o),c=new Uint8Array(n*r*4),u=Math.round(e.at.x),h=Math.round(e.at.y);for(let a=0;a<o;a++){let f=h+a,l=Math.max(0,-u),p=Math.min(i,n-u);if(f<0||f>=r||p<=l)continue;c.set(s.data.subarray((a*i+l)*4,(a*i+p)*4),(f*n+u+l)*4)}return{width:n,height:r,data:c}}function nu(t,e,n,r,i){let o=Dc(t),s=eu(t,tu(o,r,i,Un(t,o)),r,i);return Bg(Zi(s,e.background,n.color),e.background,n.opacity)}function de(t){return ct(t,"ttheme","backgrounds")}function qi(t){return ct(t,Yg)}function Hr(t){try{return Qg(t,"utf8")}catch{return}}function Me(t){try{return xg(t)}catch{return[]}}function en(t){let e=Hr(qi(t));if(e===void 0)return nd(t);let n=JSON.parse(e);if(n.version!==xi)throw Error(`${qi(t)} is version ${n.version} — this ttheme reads version ${xi}`);return n}function ed(t,e){let n=e.pictures.findIndex((i)=>i.key===e.active),r=e.pictures[n];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${e.pictures.length}`,`background-image = ${ct(t,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
11
- `)}function Pr(t,e,n){Tt(qi(t),`${JSON.stringify(e,null,2)}
12
- `);for(let r of n){let i=e.palettes[r],o=ct(t,`${r}.conf`);if(i)Tt(o,ed(t,i));else tn(o,{force:!0})}}function ru(t,e){for(let n of Me(t))if(n.startsWith(`${e.stem}.`)||n.startsWith(`${e.stem}@`))tn(ct(t,n),{force:!0});if(e.original)tn(ct(t,e.original),{force:!0})}function Xc(t,e,n,r){let i=Zg(/^background-image\s*=\s*(.*?)\s*$/m.exec(e??"")?.[1]??"");if(!i.startsWith(`${t}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(t.length)))return;let o=i.slice(0,i.indexOf("@")),s=r??/^# image (\S+)$/m.exec(e??"")?.[1]??`picture_${o.slice(t.length+1)}`,c=/^# from (.+)$/m.exec(e??"")?.[1],u=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(e??"")?.[1]??1),h=n.find((a)=>a.startsWith(`${t}-${s}.`));return{key:s,stem:o,fill:i,opacity:Number.isFinite(u)?u:1,...c?{from:c}:{},...h?{original:ct(Or,h)}:{}}}function Vc(t,e){if(zc(t))Bc(t,e)}function nd(t){let e={version:xi,palettes:{}};if(!zc(t))return e;let n=Me(ct(t,Or)),r=Me(t).filter((o)=>o.endsWith(".conf")&&o!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(o)).map((o)=>o.slice(0,-5)),i=ct(t,Vg);for(let o of new Set([...r,...Me(i)])){let s=[],c=Xc(o,Hr(ct(t,`${o}.conf`)),n);if(c)Vc(ct(t,`${o}.tune.conf`),ct(t,`${c.stem}.tune.conf`)),Vc(ct(t,`${o}.off.conf`),ct(t,`${c.stem}.off.conf`)),s.push(c);for(let u of Me(ct(i,o))){let h=ct(i,o,u),a=Xc(o,Hr(ct(h,".conf")),n,u);if(!a)continue;for(let f of Me(h)){let l=f===".tune.conf"||f===".off.conf"?`${a.stem}${f}`:`${o}${f}`;if(f!==".conf")Bc(ct(h,f),ct(t,l))}tn(h,{recursive:!0}),s.push(a)}if(Me(ct(i,o)).length===0)tn(ct(i,o),{recursive:!0,force:!0});if(s.length>0)s.sort((u,h)=>u.key<h.key?-1:u.key>h.key?1:0),e.palettes[o]={active:(c??s[0]).key,pictures:s}}if(Me(i).length===0)tn(i,{recursive:!0,force:!0});return Pr(t,e,Object.keys(e.palettes)),e}function Yc(t,e,n){return e.startsWith("~/")?ct(n,e.slice(2)):qg(e)?e:ct(t,e)}function iu(t,e,n){let r=new Map,i=(c,u)=>{let h=Hr(c);if(h===void 0)return!1;for(let a of h.split(`
13
- `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(a);if(f?.[1]==="config-file"&&u<4)i(Yc(t,f[2].replace(/^\?/,""),n),u+1);else if(f&&/^background-image(?:-fit|-opacity)?$/.test(f[1]))r.set(f[1],f[2])}return!0};if(!i(ct(t,`${e}.conf`),0))return;let o=r.get("background-image")??"";if(o==="")return;let s=Number(r.get("background-image-opacity")??1);return{image:Yc(t,o,n),opacity:Number.isFinite(s)?s:1,cover:r.get("background-image-fit")==="cover"}}function rd(t){return`${t.site}_${t.id}`}function ou(t,e,n){let r=de(t),i=en(r),o=i.palettes[e];if(!o||o.pictures.length<2)throw Error(`${e} has no other image`);let s=o.pictures.length,c=(o.pictures.findIndex((u)=>u.key===o.active)+n+s)%s;return o.active=o.pictures[c].key,Pr(r,i,[e]),{key:o.active,at:c+1,of:s}}function su(t,e){let n=de(t),r=en(n),i=r.palettes[e];if(!i)throw Error(`${e} has no image`);let o=i.pictures.findIndex((u)=>u.key===i.active),[s]=i.pictures.splice(o,1);ru(n,s);let c=i.pictures[o%Math.max(i.pictures.length,1)];if(c)i.active=c.key;else delete r.palettes[e];return Pr(n,r,[e]),{key:s.key,left:i.pictures.length}}function cu(t,e,n,r,i,o){let s=de(t),c=e.name,u=rd(i),h=en(s),a=h.palettes[c]??{active:u,pictures:[]},f=Dc(r),{width:l,height:p}=Dg(o.width,o.height),b=tu(f,l,p,Un(r,f)),g=De(Zi(td(r,f),e.background,n.color)),$=De(Zi(eu(r,b,l,p),e.background,n.color)),y=`${c}.${Jg("sha1").update(g).update($).digest("hex").slice(0,8)}`,F={key:u,stem:y,fill:`${y}@fill-${Math.round(b.focus*100)}.png`,opacity:n.opacity,...i.from?{from:i.from}:{},original:ct(Or,`${c}-${u}.${i.ext}`)},E=a.pictures.find((d)=>d.key===u);if(E)ru(s,E);let v=[ct(s,`${y}.png`),ct(s,F.fill),ct(s,F.original)];return Wg(ct(s,Or),{recursive:!0}),Tt(v[0],g),Tt(v[1],$),Tt(v[2],i.bytes),a.pictures=E?a.pictures.map((d)=>d===E?F:d):[...a.pictures,F],a.active=u,h.palettes[c]=a,Pr(s,h,[c]),[...v,ct(s,`${c}.conf`)]}function uu(t){let e=new Map;for(let[n,r]of Object.entries(en(de(t)).palettes)){let[,i,o]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&o)e.set(n,{site:i,id:Number(o)})}return e}function _i(t){let{slot:e,color:n,opacity:r}=jr({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,group:t.group,...t.native?{native:t.native}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Ns(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:e,color:n,opacity:r}}}function Ge(t){return t.filter((e)=>e.default!==!0)}function id(t){let[e]=t;if(!e)throw Error("manifest needs at least one theme");return{version:ie.version,gate:Ir,placement:ge,palettes:t.map(_i)}}var Ci={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(id(t),null,2)}
14
- `}]}};import{readdirSync as Td,readFileSync as Gu}from"node:fs";import{basename as Ad,join as Lu}from"node:path";import{readdirSync as od,rmSync as sd,statSync as cd}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as ud}from"node:net";import{homedir as hd}from"node:os";import{join as Jn}from"node:path";import{setTimeout as ad}from"node:timers/promises";var Le=100,Ae=25000000,fd=536870912,Wn=["safe","questionable","explicit"],Te=["nudity","underwear"],ld={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Kn={safe:"s",questionable:"q",explicit:"e"},gd=8191,dd=20000,md=5000,hu=3000,au=8,pd=3000,du=60000,fu=3,Vi=`ttheme/${ie.version} (+${ie.homepage})`,wd=["orig","tile","thumb","cut"],mu=new Map,bd=Nd(process.env.TTHEME_FIND_HOSTS),$d=Fd(process.env.TTHEME_FIND_CUTOUTS);ud(pd);function lu(t){try{return od(t)}catch{return[]}}function Gr(t){return t.startsWith("//")?`https:${t}`:t}function xn(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Qn(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function kd(t){let e=t.trim(),r=(e?JSON.parse(e):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function Xi(t,e,n){let r=Gr(String(t??""));return{file:r,width:Number(e)||0,height:Number(n)||0,ext:xn(r)}}function pu(t,e){let n=Gr(String(e.preview??""));if(!e.file||!n||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:e.file,preview:n,ext:e.ext,owner:String(e.owner??""),artist:e.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(e.md5??""),source:String(t.source??""),tags:e.tags.split(/\s+/).filter(Boolean),solo:e.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:e.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function Ed(t){let e=kd(t);return Qn(t).flatMap((n)=>{let r=Gr(String(n.file_url??"")),i=String(n.tags??"");return pu(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||xn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((o)=>e.get(o)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[Xi(n.jpeg_url,n.jpeg_width,n.jpeg_height),Xi(n.sample_url,n.sample_width,n.sample_height)]})})}function yd(t){return Qn(t).flatMap((e)=>{let n=Gr(String(e.file_url??"")),r=String(e.tag_string??""),i=e.media_asset??{};return pu(e,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??e.preview_file_url,file:n,ext:String(e.file_ext||xn(n)).toLowerCase(),owner:"",artist:String(e.tag_string_artist??"").split(/\s+/)[0]??"",md5:e.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>Xi(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function Md(t){return Qn(t).flatMap((e)=>{let n=String(e.value??"");return n?[{value:n,count:Number(e.post_count)||0}]:[]})}function vd(t){return Qn(t).flatMap((e)=>{let n=String(e.name??"");return n?[{value:n,count:Number(e.count)||0}]:[]})}function Sd(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function Id(t){let e=t.trim()?JSON.parse(t):{};return Number(e.counts?.posts)||0}function Fd(t){let e=new Map;for(let n of(t??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)e.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return e}function Nd(t){let e=new Map;for(let n of(t??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let o=new URL(n.slice(r+1));if(i&&o.protocol==="https:")e.set(i,o.origin)}catch{}}return e}function wu(t,e,n,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=e.filter((s)=>i.includes(s));return o.length>0?o:[...n]}function Lr(t){return wu(t,Wn,["safe"])}function Tr(t){return wu(t,Te,Te,"none")}function bu(t,e,n){return{safe:new Set(t),questionable:new Set(e),explicit:new Set(n)}}function $u(t){let e=bd.get(t.key),n=$d.get(t.key);return{...t,origin:e??t.origin,moved:e!==void 0&&e!==t.origin,cutouts:n??t.cutouts,vouched:t.vouched&&n===void 0}}function ku(t){return t.length<2?t.join(""):t.map((e)=>`~${e}`).join(" ")}function gu(t){let e=$u(t),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...e,cutouts:ku(e.cutouts),ratings:bu([Kn.safe],[Kn.questionable],[Kn.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Kn[i]}`;let o=Wn.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${Kn[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${e.origin}/post.json?${n({limit:String(Le),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${e.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/post/show/${r}`,parse:Ed,count:Sd}}function Rd(t){let e=$u(t),n=bu(["g"],["s","q"],["e"]);return{...e,cutouts:ku(e.cutouts),ratings:n,rate:(r)=>r.length===Wn.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${e.origin}/posts.json?${new URLSearchParams({limit:String(Le),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${e.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/posts/${r}`,parse:yd,count:Id}}function Od(t){return gt.find((e)=>e.key===t||e.name===t||new URL(e.origin).host===t)}function Yi(t){return t.split(/\s+/).filter((e)=>e&&!e.startsWith("rating:")).length}function Ar(t,e){let n=t.trim();if(/^\d+$/.test(n))return{site:e,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let c=gt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let o=Od(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 gt=[Rd({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),gu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),gu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],me=134217728;function se(t,e){let n=gt.indexOf(t);return(n===-1?gt.length:n)*me+e}function zi(t){let e;try{e=new URL(t).hostname}catch{return""}return e.split(".").slice(-2).join(".")}function Eu(){return gt.filter((t)=>!t.tunneled).map((t)=>zi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function yu(t,e=Te){return t.tags.filter((n)=>e.some((r)=>ld[r].has(n)))}function Mu(t,e,n=["safe"]){return n.some((r)=>t.ratings[r].has(e.rating))}function Zn(t){return[t,...t.smaller].find((e)=>e.width*e.height<=Ae)}function vu(t){let e=new Map;for(let[n,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;e.set(r,[...e.get(r)??[],n])}return e}function Ur(){return Jn(process.env.XDG_CACHE_HOME??Jn(hd(),".cache"),"ttheme")}function Ie(t){return Jn(Ur(),t.key)}function Su(t=fd,e=Ur()){let n=[],r=0;for(let i of lu(e))for(let o of wd){let s=Jn(e,i,o);for(let c of lu(s)){let u=Jn(s,c);try{let{size:h,mtimeMs:a}=cd(u);n.push({path:u,size:h,at:a}),r+=h}catch{}}}n.sort((i,o)=>i.at-o.at);for(let i of n){if(r<=t)return;try{sd(i.path,{force:!0}),r-=i.size}catch{}}}function Hd(t,e){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let n=t===null?Number.NaN:Date.parse(t);return Number.isNaN(n)?du:Math.max(0,n-e)}function ve(t){return mu.get(t.key)??0}function jd(t){for(let e=t;e instanceof Error;e=e.cause)if(e.code==="ECONNRESET")return!0;return!1}function Pd(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function Se(t,e,n,r={},i=dd){for(let o=1;;o++){let s=ve(t)-Date.now();if(s>0)await ad(s,void 0,{signal:n});let c;try{c=await fetch(e,{headers:{"User-Agent":Vi,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(u){if(o<fu&&!n.aborted&&jd(u))continue;throw u}if(c.status===429&&o<fu){await c.body?.cancel();let u=Hd(c.headers.get("retry-after"),Date.now());if(u>du)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);mu.set(t.key,Math.max(ve(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Pd(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function Iu(t,e,n,r){return t.parse(await(await Se(t,t.postsUrl(e,n),r)).text())}async function Fu(t,e,n){return t.count(await(await Se(t,t.countUrl(e),n)).text())}async function Bi(t,e,n){let[r]=t.parse(await(await Se(t,t.postUrl(e),n)).text());return r}function Gd(t){let e=gt.find((r)=>r.key==="danbooru"),n=new URLSearchParams({limit:String(2*Le),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${e.origin}/posts.json?${n}`}function Ld(t){return new Map(Qn(t).flatMap((e)=>{let n=String(e.md5??"");return n?[[n,String(e.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Nu(t,e){for(let n of t){let r=e.get(n.md5);if(r)n.tags=[...new Set([...n.tags,...r])],n.solo=r.includes("solo")}}async function Ru(t,e){let n=gt.find((i)=>i.key==="danbooru"),r=new Map;if(ve(n)>Date.now())return r;for(let i=0;i<t.length;i+=Le){let o=await(await Se(n,Gd(t.slice(i,i+Le)),e,{},md)).text();for(let[s,c]of Ld(o))r.set(s,c)}return r}async function Ou(t,e){let n=gt.find((o)=>o.key==="danbooru");if(ve(n)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(au)}),s=`${n.origin}/autocomplete.json?${o}`;return Md(await(await Se(n,s,e,{},hu)).text())}catch(o){if(e.aborted)throw o}let r=gt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(au)});return vd(await(await Se(r,`${r.origin}/tag.json?${i}`,e,{},hu)).text())}async function Hu(t,e,n){let r=await Se(t,e,n,{Range:`bytes=0-${gd}`});return An(new Uint8Array(await r.arrayBuffer()))}async function ju(t,e,n,r){let i=await Se(t,e,n,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:f,value:l}=await s.read();if(f)break;c.push(l),u+=l.length,r?.(u,o)}let h=new Uint8Array(u),a=0;for(let f of c)h.set(f,a),a+=f.length;return h}var pe="_groups.toml",Pu=3,Tu=["background","foreground","cursor","selection"];function It(t,e){throw Error(`${t}: ${e}`)}function Ue(t,e,n){if(typeof n!=="string"||!ds(n))It(t,`${e} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Fe(t,e,n){if(typeof n!=="string"||n.length===0)It(t,`${e} must be a non-empty string`);return n}function qn(t){return t&&typeof t==="object"?t:{}}function Ud(t,e,n){if(e===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(e)?e:[e];if(r.length===0)It(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Ue(t,`ghostty.icon_screen[${o}]`,i))}function Kd(t,e,n){let r=qn(e);return{iconGhost:r.icon_ghost===void 0?n.cursor:Ue(t,"ghostty.icon_ghost",r.icon_ghost),iconScreen:Ud(t,r.icon_screen,n)}}function Jd(t){return new Map([...Tu.map((e)=>[e,t[e]]),...t.ansi.map((e,n)=>[`ansi${n}`,e])])}function Wd(t,e,n){if(!Array.isArray(e)||e.length!==Pu)It(t,`meta.signature must name exactly ${Pu} palette slots`);let r=Jd(n),i=[],o=[];for(let[s,c]of e.entries()){let u=`meta.signature[${s}]`,h=Fe(t,u,c),a=r.get(h);if(a===void 0)It(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${Tu.join(", ")} or ansi0-ansi15`);i.push(h),o.push(a)}if(new Set(o).size!==o.length)It(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function xd(t,e,n){if(e===void 0)return;if(!n)It(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!e||typeof e!=="object"||Array.isArray(e))It(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(e)){let s=gt.find((u)=>u.key===i);if(!s)It(t,`meta.booru_sites.${i} is not a find site — use ${gt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))It(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))It(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function Qd(t){let n=Bun.TOML.parse(Gu(Lu(t,pe),"utf8")).group;if(!Array.isArray(n)||n.length===0)It(pe,"needs at least one [[group]] table");return n.map((r)=>{let i=qn(r);return{name:Fe(pe,"group.name",i.name),native:i.native===void 0?void 0:Fe(pe,"group.native",i.native),lead:Fe(pe,"group.lead",i.lead)}})}function Zd(t,e,n){let r=Bun.TOML.parse(e),i=qn(r.meta),o=qn(r.colors),s=qn(r.contrast),c=o.ansi;if(!Array.isArray(c)||c.length!==16)It(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let u=Fe(t,"meta.name",i.name);if(u!==Ad(t,".toml"))It(t,`meta.name "${u}" does not match the filename`);if(u.startsWith("-"))It(t,`meta.name "${u}" would be read as a flag by the ttheme CLI`);let h=i.role;if(h!==void 0&&h!=="default")It(t,`meta.role must be "default", got ${JSON.stringify(h)}`);let a=Fe(t,"meta.group",i.group),f=n.get(a);if(!f)It(t,`meta.group "${a}" has no [[group]] table in ${pe}`);let l=Ue(t,"colors.background",o.background),p=Ue(t,"colors.foreground",o.foreground),b=Ue(t,"colors.cursor",o.cursor),g=Ue(t,"colors.selection_background",o.selection_background),$=c.map((d,j)=>Ue(t,`colors.ansi[${j}]`,d)),y=Wd(t,i.signature,{background:l,foreground:p,cursor:b,selection:g,ansi:$}),F=i.booru===void 0?void 0:Fe(t,"meta.booru",i.booru);if(F!==void 0&&/\s/.test(F))It(t,`meta.booru must be a single booru tag, got ${JSON.stringify(F)}`);let E=xd(t,i.booru_sites,F),v=Array.isArray(s.waive)?s.waive.map(String):[];if(v.length>0&&typeof s.reason!=="string")It(t,"contrast.waive needs a contrast.reason explaining why");return{name:u,group:a,native:f.native,lead:f.lead===u,order:Number(i.order),role:h,ansiSource:Fe(t,"meta.ansi_source",i.ansi_source),...F?{booru:F}:{},...E?{booruSites:E}:{},background:l,foreground:p,cursor:b,selectionBackground:g,ansi:$,signature:y.colors,signatureSlots:y.names,ghostty:Kd(t,r.ghostty,{background:l,cursor:b,selectionBackground:g}),waive:v,waiveReason:typeof s.reason==="string"?s.reason:void 0}}function Au(t){let e=Qd(t),n=new Map(e.map((o)=>[o.name,o]));if(n.size!==e.length)It(pe,"group.name must be unique");let r=Td(t).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>Zd(o,Gu(Lu(t,o),"utf8"),n)).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of e){let s=r.filter((c)=>c.group===o.name);if(s.length===0)It(pe,`group "${o.name}" has no themes`);if(!s.some((c)=>c.name===o.lead))It(pe,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function Uu(t){return t.filter((e)=>e.role===void 0)}function _n(t){let e=(n,r)=>n<r?-1:n>r?1:0;return[...t].sort((n,r)=>e(n.group.toLowerCase(),r.group.toLowerCase())||e(n.name,r.name))}var qd=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Kr=[{name:"use",args:["<palette>"],about:"paint this tab — a unique prefix works: ttheme use ho",section:"tab",shell:!0},{name:"preview",args:[],about:"browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",shell:!0},{name:"next",args:[],about:"advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"make a palette the one new tabs open with",section:"tab"},{name:"on",args:[],about:"wear the default palette in new tabs again",section:"tab"},{name:"off",args:[],about:"take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"tab"},{name:"pin",args:[],about:"pick a palette for this directory — cd into it repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:[],about:"drop the palette pinned to this directory",section:"tab",shell:!0},{name:"config",args:[],about:"edit settings in $EDITOR — they apply in new tabs",section:"tab",shell:!0},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",section:"catalog"},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"print the matches as JSON: name, group, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh the catalog from the registry",section:"catalog"},{name:"init",args:[],about:"install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"accept every default without prompting"}}},{name:"uninstall",args:[],about:"take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"remove without asking"}}},{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:qd,about:"rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",section:"setup",hidden:!0}];var Jr=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],xu="# ttheme begin",Qu="# ttheme end",Cn=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Xn(t,e){let n=`${xu}
15
- ${e}
16
- ${Qu}
17
- `;if(Cn.test(t))return t.replace(Cn,n);if(t==="")return n;return`${t.replace(/\n*$/,`
2
+ import{createRequire as ld}from"node:module";var od=Object.create;var{getPrototypeOf:sd,defineProperty:xu,getOwnPropertyNames:ud}=Object;var cd=Object.prototype.hasOwnProperty;function ad(e){return this[e]}var hd,fd,ki=(e,n,t)=>{var r=e!=null&&typeof e==="object";if(r){var i=n?hd??=new WeakMap:fd??=new WeakMap,o=i.get(e);if(o)return o}t=e!=null?od(sd(e)):{};let s=n||!e||!e.__esModule?xu(t,"default",{value:e,enumerable:!0}):t;for(let u of ud(e))if(!cd.call(s,u))xu(s,u,{get:ad.bind(e,u),enumerable:!0});if(r)i.set(e,s);return s};var ye=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var Je=ld(import.meta.url);var mc=ye((ok,Pi)=>{var dc=dc||function(e){return Buffer.from(e).toString("base64")};function yd(e){var n=this,t=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),u=Array(64),c,a,h,f,l=Array(65535),g=Array(65535),m=Array(64),d=Array(64),$=[],y=0,N=7,E=Array(64),v=Array(64),p=Array(64),H=Array(256),S=Array(2048),R,I=[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],P=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],X=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],j=[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],Pe=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],K=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Me=[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 be(w){var T=[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 C=0;C<64;C++){var U=r((T[C]*w+50)/100);if(U<1)U=1;else if(U>255)U=255;i[I[C]]=U}var q=[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 Z=0;Z<64;Z++){var ue=r((q[Z]*w+50)/100);if(ue<1)ue=1;else if(ue>255)ue=255;o[I[Z]]=ue}var ce=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ne=0;for(var Se=0;Se<8;Se++)for(var M=0;M<8;M++)s[Ne]=1/(i[I[Ne]]*ce[Se]*ce[M]*8),u[Ne]=1/(o[I[Ne]]*ce[Se]*ce[M]*8),Ne++}function ee(w,T){var C=0,U=0,q=[];for(var Z=1;Z<=16;Z++){for(var ue=1;ue<=w[Z];ue++)q[T[U]]=[],q[T[U]][0]=C,q[T[U]][1]=Z,U++,C++;C*=2}return q}function Le(){c=ee(P,A),a=ee(Pe,K),h=ee(X,j),f=ee(D,Me)}function he(){var w=1,T=2;for(var C=1;C<=15;C++){for(var U=w;U<T;U++)g[32767+U]=C,l[32767+U]=[],l[32767+U][1]=C,l[32767+U][0]=U;for(var q=-(T-1);q<=-w;q++)g[32767+q]=C,l[32767+q]=[],l[32767+q][1]=C,l[32767+q][0]=T-1+q;w<<=1,T<<=1}}function te(){for(var w=0;w<256;w++)S[w]=19595*w,S[w+256>>0]=38470*w,S[w+512>>0]=7471*w+32768,S[w+768>>0]=-11059*w,S[w+1024>>0]=-21709*w,S[w+1280>>0]=32768*w+8421375,S[w+1536>>0]=-27439*w,S[w+1792>>0]=-5329*w}function V(w){var T=w[0],C=w[1]-1;while(C>=0){if(T&1<<C)y|=1<<N;if(C--,N--,N<0){if(y==255)b(255),b(0);else b(y);N=7,y=0}}}function b(w){$.push(w)}function G(w){b(w>>8&255),b(w&255)}function de(w,T){var C,U,q,Z,ue,ce,Ne,Se,M=0,L,Q=8,Ie=64;for(L=0;L<Q;++L){C=w[M],U=w[M+1],q=w[M+2],Z=w[M+3],ue=w[M+4],ce=w[M+5],Ne=w[M+6],Se=w[M+7];var Y=C+Se,ne=C-Se,pe=U+Ne,W=U-Ne,fe=q+ce,Ge=q-ce,ve=Z+ue,tn=Z-ue,kn=Y+ve,rt=Y-ve,Ot=pe+fe,Rt=pe-fe;w[M]=kn+Ot,w[M+4]=kn-Ot;var hr=(Rt+rt)*0.707106781;w[M+2]=rt+hr,w[M+6]=rt-hr,kn=tn+Ge,Ot=Ge+W,Rt=W+ne;var fr=(kn-Rt)*0.382683433,pi=0.5411961*kn+fr,lr=1.306562965*Rt+fr,gr=Ot*0.707106781,dr=ne+gr,mr=ne-gr;w[M+5]=mr+pi,w[M+3]=mr-pi,w[M+1]=dr+lr,w[M+7]=dr-lr,M+=8}M=0;for(L=0;L<Q;++L){C=w[M],U=w[M+8],q=w[M+16],Z=w[M+24],ue=w[M+32],ce=w[M+40],Ne=w[M+48],Se=w[M+56];var Ku=C+Se,Co=C-Se,Cu=U+Ne,Wu=U-Ne,_u=q+ce,Qu=q-ce,qu=Z+ue,id=Z-ue,pr=Ku+qu,Wo=Ku-qu,wi=Cu+_u,bi=Cu-_u;w[M]=pr+wi,w[M+32]=pr-wi;var Zu=(bi+Wo)*0.707106781;w[M+16]=Wo+Zu,w[M+48]=Wo-Zu,pr=id+Qu,wi=Qu+Wu,bi=Wu+Co;var Yu=(pr-bi)*0.382683433,Xu=0.5411961*pr+Yu,Vu=1.306562965*bi+Yu,zu=wi*0.707106781,Bu=Co+zu,Du=Co-zu;w[M+40]=Du+Xu,w[M+24]=Du-Xu,w[M+8]=Bu+Vu,w[M+56]=Bu-Vu,M++}var $i;for(L=0;L<Ie;++L)$i=w[L]*T[L],m[L]=$i>0?$i+0.5|0:$i-0.5|0;return m}function me(){G(65504),G(16),b(74),b(70),b(73),b(70),b(0),b(1),b(1),b(0),G(1),G(1),b(0),b(0)}function re(w){if(!w)return;if(G(65505),w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102)G(w.length+2);else G(w.length+5+2),b(69),b(120),b(105),b(102),b(0);for(var T=0;T<w.length;T++)b(w[T])}function ie(w,T){G(65472),G(17),b(8),G(T),G(w),b(3),b(1),b(17),b(0),b(2),b(17),b(1),b(3),b(17),b(1)}function z(){G(65499),G(132),b(0);for(var w=0;w<64;w++)b(i[w]);b(1);for(var T=0;T<64;T++)b(o[T])}function F(){G(65476),G(418),b(0);for(var w=0;w<16;w++)b(P[w+1]);for(var T=0;T<=11;T++)b(A[T]);b(16);for(var C=0;C<16;C++)b(X[C+1]);for(var U=0;U<=161;U++)b(j[U]);b(1);for(var q=0;q<16;q++)b(Pe[q+1]);for(var Z=0;Z<=11;Z++)b(K[Z]);b(17);for(var ue=0;ue<16;ue++)b(D[ue+1]);for(var ce=0;ce<=161;ce++)b(Me[ce])}function O(w){if(typeof w>"u"||w.constructor!==Array)return;w.forEach((T)=>{if(typeof T!=="string")return;G(65534);var C=T.length;G(C+2);var U;for(U=0;U<C;U++)b(T.charCodeAt(U))})}function Ee(){G(65498),G(12),b(3),b(1),b(0),b(2),b(17),b(3),b(17),b(0),b(63),b(0)}function _(w,T,C,U,q){var Z=q[0],ue=q[240],ce,Ne=16,Se=63,M=64,L=de(w,T);for(var Q=0;Q<M;++Q)d[I[Q]]=L[Q];var Ie=d[0]-C;if(C=d[0],Ie==0)V(U[0]);else ce=32767+Ie,V(U[g[ce]]),V(l[ce]);var Y=63;for(;Y>0&&d[Y]==0;Y--);if(Y==0)return V(Z),C;var ne=1,pe;while(ne<=Y){var W=ne;for(;d[ne]==0&&ne<=Y;++ne);var fe=ne-W;if(fe>=Ne){pe=fe>>4;for(var Ge=1;Ge<=pe;++Ge)V(ue);fe=fe&15}ce=32767+d[ne],V(q[(fe<<4)+g[ce]]),V(l[ce]),ne++}if(Y!=Se)V(Z);return C}function B(){var w=String.fromCharCode;for(var T=0;T<256;T++)H[T]=w(T)}this.encode=function(w,T){var C=new Date().getTime();if(T)nn(T);$=[],y=0,N=7,G(65496),me(),O(w.comments),re(w.exifBuffer),z(),ie(w.width,w.height),F(),Ee();var U=0,q=0,Z=0;y=0,N=7,this.encode.displayName="_encode_";var{data:ue,width:ce,height:Ne}=w,Se=ce*4,M=ce*3,L,Q=0,Ie,Y,ne,pe,W,fe,Ge,ve;while(Q<Ne){L=0;while(L<Se){pe=Se*Q+L,W=pe,fe=-1,Ge=0;for(ve=0;ve<64;ve++){if(Ge=ve>>3,fe=(ve&7)*4,W=pe+Ge*Se+fe,Q+Ge>=Ne)W-=Se*(Q+1+Ge-Ne);if(L+fe>=Se)W-=L+fe-Se+4;Ie=ue[W++],Y=ue[W++],ne=ue[W++],E[ve]=(S[Ie]+S[Y+256>>0]+S[ne+512>>0]>>16)-128,v[ve]=(S[Ie+768>>0]+S[Y+1024>>0]+S[ne+1280>>0]>>16)-128,p[ve]=(S[Ie+1280>>0]+S[Y+1536>>0]+S[ne+1792>>0]>>16)-128}U=_(E,s,U,c,h),q=_(v,u,q,a,f),Z=_(p,u,Z,a,f),L+=32}Q+=8}if(N>=0){var tn=[];tn[1]=N+1,tn[0]=(1<<N+1)-1,V(tn)}if(G(65497),typeof Pi>"u")return new Uint8Array($);return Buffer.from($);var kn,rt};function nn(w){if(w<=0)w=1;if(w>100)w=100;if(R==w)return;var T=0;if(w<50)T=Math.floor(5000/w);else T=Math.floor(200-w*2);be(T),R=w}function an(){var w=new Date().getTime();if(!e)e=50;B(),Le(),he(),te(),nn(e);var T=new Date().getTime()-w}an()}if(typeof Pi<"u")Pi.exports=gc;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=gc;function gc(e,n){if(typeof n>"u")n=50;var t=new yd(n),r=t.encode(e,n);return{data:r,width:e.width,height:e.height}}});var wc=ye((sk,Bo)=>{var zo=function(){var n=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,r=799,i=3406,o=2276,s=1567,u=3784,c=5793,a=2896;function h(){}function f(N,E){var v=0,p=[],H,S,R=16;while(R>0&&!N[R-1])R--;p.push({children:[],index:0});var I=p[0],P;for(H=0;H<R;H++){for(S=0;S<N[H];S++){I=p.pop(),I.children[I.index]=E[v];while(I.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");I=p.pop()}I.index++,p.push(I);while(p.length<=H)p.push(P={children:[],index:0}),I.children[I.index]=P.children,I=P;v++}if(H+1<R)p.push(P={children:[],index:0}),I.children[I.index]=P.children,I=P}return p[0].children}function l(N,E,v,p,H,S,R,I,P,A){var{precision:X,samplesPerLine:j,scanLines:Pe,mcusPerLine:K,progressive:D,maxH:Me,maxV:be}=v,ee=E,Le=0,he=0;function te(){if(he>0)return he--,Le>>he&1;if(Le=N[E++],Le==255){var M=N[E++];if(M)throw Error("unexpected marker: "+(Le<<8|M).toString(16))}return he=7,Le>>>7}function V(M){var L=M,Q;while((Q=te())!==null){if(L=L[Q],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function b(M){var L=0;while(M>0){var Q=te();if(Q===null)return;L=L<<1|Q,M--}return L}function G(M){var L=b(M);if(L>=1<<M-1)return L;return L+(-1<<M)+1}function de(M,L){var Q=V(M.huffmanTableDC),Ie=Q===0?0:G(Q);L[0]=M.pred+=Ie;var Y=1;while(Y<64){var ne=V(M.huffmanTableAC),pe=ne&15,W=ne>>4;if(pe===0){if(W<15)break;Y+=16;continue}Y+=W;var fe=n[Y];L[fe]=G(pe),Y++}}function me(M,L){var Q=V(M.huffmanTableDC),Ie=Q===0?0:G(Q)<<P;L[0]=M.pred+=Ie}function re(M,L){L[0]|=te()<<P}var ie=0;function z(M,L){if(ie>0){ie--;return}var Q=S,Ie=R;while(Q<=Ie){var Y=V(M.huffmanTableAC),ne=Y&15,pe=Y>>4;if(ne===0){if(pe<15){ie=b(pe)+(1<<pe)-1;break}Q+=16;continue}Q+=pe;var W=n[Q];L[W]=G(ne)*(1<<P),Q++}}var F=0,O;function Ee(M,L){var Q=S,Ie=R,Y=0;while(Q<=Ie){var ne=n[Q],pe=L[ne]<0?-1:1;switch(F){case 0:var W=V(M.huffmanTableAC),fe=W&15,Y=W>>4;if(fe===0)if(Y<15)ie=b(Y)+(1<<Y),F=4;else Y=16,F=1;else{if(fe!==1)throw Error("invalid ACn encoding");O=G(fe),F=Y?2:3}continue;case 1:case 2:if(L[ne])L[ne]+=(te()<<P)*pe;else if(Y--,Y===0)F=F==2?3:0;break;case 3:if(L[ne])L[ne]+=(te()<<P)*pe;else L[ne]=O<<P,F=0;break;case 4:if(L[ne])L[ne]+=(te()<<P)*pe;break}Q++}if(F===4){if(ie--,ie===0)F=0}}function _(M,L,Q,Ie,Y){var ne=Q/K|0,pe=Q%K,W=ne*M.v+Ie,fe=pe*M.h+Y;if(M.blocks[W]===void 0&&A.tolerantDecoding)return;L(M,M.blocks[W][fe])}function B(M,L,Q){var Ie=Q/M.blocksPerLine|0,Y=Q%M.blocksPerLine;if(M.blocks[Ie]===void 0&&A.tolerantDecoding)return;L(M,M.blocks[Ie][Y])}var nn=p.length,an,w,T,C,U,q;if(D)if(S===0)q=I===0?me:re;else q=I===0?z:Ee;else q=de;var Z=0,ue,ce;if(nn==1)ce=p[0].blocksPerLine*p[0].blocksPerColumn;else ce=K*v.mcusPerColumn;if(!H)H=ce;var Ne,Se;while(Z<ce){for(w=0;w<nn;w++)p[w].pred=0;if(ie=0,nn==1){an=p[0];for(U=0;U<H;U++)B(an,q,Z),Z++}else for(U=0;U<H;U++){for(w=0;w<nn;w++){an=p[w],Ne=an.h,Se=an.v;for(T=0;T<Se;T++)for(C=0;C<Ne;C++)_(an,q,Z,T,C)}if(Z++,Z===ce)break}if(Z===ce)do{if(N[E]===255){if(N[E+1]!==0)break}E+=1}while(E<N.length-2);if(he=0,ue=N[E]<<8|N[E+1],ue<65280)throw Error("marker was not found");if(ue>=65488&&ue<=65495)E+=2;else break}return E-ee}function g(N,E){var v=[],p=E.blocksPerLine,H=E.blocksPerColumn,S=p<<3,R=new Int32Array(64),I=new Uint8Array(64);function P(ee,Le,he){var te=E.quantizationTable,V,b,G,de,me,re,ie,z,F,O=he,Ee;for(Ee=0;Ee<64;Ee++)O[Ee]=ee[Ee]*te[Ee];for(Ee=0;Ee<8;++Ee){var _=8*Ee;if(O[1+_]==0&&O[2+_]==0&&O[3+_]==0&&O[4+_]==0&&O[5+_]==0&&O[6+_]==0&&O[7+_]==0){F=c*O[0+_]+512>>10,O[0+_]=F,O[1+_]=F,O[2+_]=F,O[3+_]=F,O[4+_]=F,O[5+_]=F,O[6+_]=F,O[7+_]=F;continue}V=c*O[0+_]+128>>8,b=c*O[4+_]+128>>8,G=O[2+_],de=O[6+_],me=a*(O[1+_]-O[7+_])+128>>8,z=a*(O[1+_]+O[7+_])+128>>8,re=O[3+_]<<4,ie=O[5+_]<<4,F=V-b+1>>1,V=V+b+1>>1,b=F,F=G*u+de*s+128>>8,G=G*s-de*u+128>>8,de=F,F=me-ie+1>>1,me=me+ie+1>>1,ie=F,F=z+re+1>>1,re=z-re+1>>1,z=F,F=V-de+1>>1,V=V+de+1>>1,de=F,F=b-G+1>>1,b=b+G+1>>1,G=F,F=me*o+z*i+2048>>12,me=me*i-z*o+2048>>12,z=F,F=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=F,O[0+_]=V+z,O[7+_]=V-z,O[1+_]=b+ie,O[6+_]=b-ie,O[2+_]=G+re,O[5+_]=G-re,O[3+_]=de+me,O[4+_]=de-me}for(Ee=0;Ee<8;++Ee){var B=Ee;if(O[8+B]==0&&O[16+B]==0&&O[24+B]==0&&O[32+B]==0&&O[40+B]==0&&O[48+B]==0&&O[56+B]==0){F=c*he[Ee+0]+8192>>14,O[0+B]=F,O[8+B]=F,O[16+B]=F,O[24+B]=F,O[32+B]=F,O[40+B]=F,O[48+B]=F,O[56+B]=F;continue}V=c*O[0+B]+2048>>12,b=c*O[32+B]+2048>>12,G=O[16+B],de=O[48+B],me=a*(O[8+B]-O[56+B])+2048>>12,z=a*(O[8+B]+O[56+B])+2048>>12,re=O[24+B],ie=O[40+B],F=V-b+1>>1,V=V+b+1>>1,b=F,F=G*u+de*s+2048>>12,G=G*s-de*u+2048>>12,de=F,F=me-ie+1>>1,me=me+ie+1>>1,ie=F,F=z+re+1>>1,re=z-re+1>>1,z=F,F=V-de+1>>1,V=V+de+1>>1,de=F,F=b-G+1>>1,b=b+G+1>>1,G=F,F=me*o+z*i+2048>>12,me=me*i-z*o+2048>>12,z=F,F=re*r+ie*t+2048>>12,re=re*t-ie*r+2048>>12,ie=F,O[0+B]=V+z,O[56+B]=V-z,O[8+B]=b+ie,O[48+B]=b-ie,O[16+B]=G+re,O[40+B]=G-re,O[24+B]=de+me,O[32+B]=de-me}for(Ee=0;Ee<64;++Ee){var nn=128+(O[Ee]+8>>4);Le[Ee]=nn<0?0:nn>255?255:nn}}y(S*H*8);var A,X;for(var j=0;j<H;j++){var Pe=j<<3;for(A=0;A<8;A++)v.push(new Uint8Array(S));for(var K=0;K<p;K++){P(E.blocks[j][K],I,R);var D=0,Me=K<<3;for(X=0;X<8;X++){var be=v[Pe+X];for(A=0;A<8;A++)be[Me+A]=I[D++]}}}return v}function m(N){return N<0?0:N>255?255:N}h.prototype={load:function(E){var v=new XMLHttpRequest;v.open("GET",E,!0),v.responseType="arraybuffer",v.onload=function(){var p=new Uint8Array(v.response||v.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),v.send(null)},parse:function(E){var v=this.opts.maxResolutionInMP*1000*1000,p=0,H=E.length;function S(){var W=E[p]<<8|E[p+1];return p+=2,W}function R(){var W=S(),fe=E.subarray(p,p+W-2);return p+=fe.length,fe}function I(W){var fe=1,Ge=1,ve,tn;for(tn in W.components)if(W.components.hasOwnProperty(tn)){if(ve=W.components[tn],fe<ve.h)fe=ve.h;if(Ge<ve.v)Ge=ve.v}var kn=Math.ceil(W.samplesPerLine/8/fe),rt=Math.ceil(W.scanLines/8/Ge);for(tn in W.components)if(W.components.hasOwnProperty(tn)){ve=W.components[tn];var Ot=Math.ceil(Math.ceil(W.samplesPerLine/8)*ve.h/fe),Rt=Math.ceil(Math.ceil(W.scanLines/8)*ve.v/Ge),hr=kn*ve.h,fr=rt*ve.v,pi=fr*hr,lr=[];y(pi*256);for(var gr=0;gr<fr;gr++){var dr=[];for(var mr=0;mr<hr;mr++)dr.push(new Int32Array(64));lr.push(dr)}ve.blocksPerLine=Ot,ve.blocksPerColumn=Rt,ve.blocks=lr}W.maxH=fe,W.maxV=Ge,W.mcusPerLine=kn,W.mcusPerColumn=rt}var P=null,A=null,X=null,j,Pe,K=[],D=[],Me=[],be=[],ee=S(),Le=-1;if(this.comments=[],ee!=65496)throw Error("SOI not found");ee=S();while(ee!=65497){var he,te,V;switch(ee){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 b=R();if(ee===65534){var G=String.fromCharCode.apply(null,b);this.comments.push(G)}if(ee===65504){if(b[0]===74&&b[1]===70&&b[2]===73&&b[3]===70&&b[4]===0)P={version:{major:b[5],minor:b[6]},densityUnits:b[7],xDensity:b[8]<<8|b[9],yDensity:b[10]<<8|b[11],thumbWidth:b[12],thumbHeight:b[13],thumbData:b.subarray(14,14+3*b[12]*b[13])}}if(ee===65505){if(b[0]===69&&b[1]===120&&b[2]===105&&b[3]===102&&b[4]===0)this.exifBuffer=b.subarray(5,b.length)}if(ee===65518){if(b[0]===65&&b[1]===100&&b[2]===111&&b[3]===98&&b[4]===101&&b[5]===0)A={version:b[6],flags0:b[7]<<8|b[8],flags1:b[9]<<8|b[10],transformCode:b[11]}}break;case 65499:var de=S(),me=de+p-2;while(p<me){var re=E[p++];y(256);var ie=new Int32Array(64);if(re>>4===0)for(te=0;te<64;te++){var z=n[te];ie[z]=E[p++]}else if(re>>4===1)for(te=0;te<64;te++){var z=n[te];ie[z]=S()}else throw Error("DQT: invalid table spec");K[re&15]=ie}break;case 65472:case 65473:case 65474:S(),j={},j.extended=ee===65473,j.progressive=ee===65474,j.precision=E[p++],j.scanLines=S(),j.samplesPerLine=S(),j.components={},j.componentsOrder=[];var F=j.scanLines*j.samplesPerLine;if(F>v){var O=Math.ceil((F-v)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${O}MP`)}var Ee=E[p++],_,B=0,nn=0;for(he=0;he<Ee;he++){_=E[p];var an=E[p+1]>>4,w=E[p+1]&15,T=E[p+2];if(an<=0||w<=0)throw Error("Invalid sampling factor, expected values above 0");j.componentsOrder.push(_),j.components[_]={h:an,v:w,quantizationIdx:T},p+=3}I(j),D.push(j);break;case 65476:var C=S();for(he=2;he<C;){var U=E[p++],q=new Uint8Array(16),Z=0;for(te=0;te<16;te++,p++)Z+=q[te]=E[p];y(16+Z);var ue=new Uint8Array(Z);for(te=0;te<Z;te++,p++)ue[te]=E[p];he+=17+Z,(U>>4===0?be:Me)[U&15]=f(q,ue)}break;case 65501:S(),Pe=S();break;case 65500:S(),S();break;case 65498:var ce=S(),Ne=E[p++],Se=[],M;for(he=0;he<Ne;he++){M=j.components[E[p++]];var L=E[p++];M.huffmanTableDC=be[L>>4],M.huffmanTableAC=Me[L&15],Se.push(M)}var Q=E[p++],Ie=E[p++],Y=E[p++],ne=l(E,p,j,Se,Pe,Q,Ie,Y>>4,Y&15,this.opts);p+=ne;break;case 65535:if(E[p]!==255)p--;break;default:if(E[p-3]==255&&E[p-2]>=192&&E[p-2]<=254){p-=3;break}else if(ee===224||ee==225){if(Le!==-1)throw Error(`first unknown JPEG marker at offset ${Le.toString(16)}, second unknown JPEG marker ${ee.toString(16)} at offset ${(p-1).toString(16)}`);Le=p-1;let W=S();if(E[p+W-2]===255){p+=W-2;break}}throw Error("unknown JPEG marker "+ee.toString(16))}ee=S()}if(D.length!=1)throw Error("only single frame JPEGs supported");for(var he=0;he<D.length;he++){var pe=D[he].components;for(var te in pe)pe[te].quantizationTable=K[pe[te].quantizationIdx],delete pe[te].quantizationIdx}this.width=j.samplesPerLine,this.height=j.scanLines,this.jfif=P,this.adobe=A,this.components=[];for(var he=0;he<j.componentsOrder.length;he++){var M=j.components[j.componentsOrder[he]];this.components.push({lines:g(j,M),scaleX:M.h/j.maxH,scaleY:M.v/j.maxV})}},getData:function(E,v){var p=this.width/E,H=this.height/v,S,R,I,P,A,X,j,Pe,K,D,Me=0,be,ee,Le,he,te,V,b,G,de,me,re,ie=E*v*this.components.length;y(ie);var z=new Uint8Array(ie);switch(this.components.length){case 1:S=this.components[0];for(D=0;D<v;D++){A=S.lines[0|D*S.scaleY*H];for(K=0;K<E;K++)be=A[0|K*S.scaleX*p],z[Me++]=be}break;case 2:S=this.components[0],R=this.components[1];for(D=0;D<v;D++){A=S.lines[0|D*S.scaleY*H],X=R.lines[0|D*R.scaleY*H];for(K=0;K<E;K++)be=A[0|K*S.scaleX*p],z[Me++]=be,be=X[0|K*R.scaleX*p],z[Me++]=be}break;case 3:if(re=!0,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;S=this.components[0],R=this.components[1],I=this.components[2];for(D=0;D<v;D++){A=S.lines[0|D*S.scaleY*H],X=R.lines[0|D*R.scaleY*H],j=I.lines[0|D*I.scaleY*H];for(K=0;K<E;K++){if(!re)G=A[0|K*S.scaleX*p],de=X[0|K*R.scaleX*p],me=j[0|K*I.scaleX*p];else be=A[0|K*S.scaleX*p],ee=X[0|K*R.scaleX*p],Le=j[0|K*I.scaleX*p],G=m(be+1.402*(Le-128)),de=m(be-0.3441363*(ee-128)-0.71413636*(Le-128)),me=m(be+1.772*(ee-128));z[Me++]=G,z[Me++]=de,z[Me++]=me}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(re=!1,this.adobe&&this.adobe.transformCode)re=!0;else if(typeof this.opts.colorTransform<"u")re=!!this.opts.colorTransform;S=this.components[0],R=this.components[1],I=this.components[2],P=this.components[3];for(D=0;D<v;D++){A=S.lines[0|D*S.scaleY*H],X=R.lines[0|D*R.scaleY*H],j=I.lines[0|D*I.scaleY*H],Pe=P.lines[0|D*P.scaleY*H];for(K=0;K<E;K++){if(!re)te=A[0|K*S.scaleX*p],V=X[0|K*R.scaleX*p],b=j[0|K*I.scaleX*p],he=Pe[0|K*P.scaleX*p];else be=A[0|K*S.scaleX*p],ee=X[0|K*R.scaleX*p],Le=j[0|K*I.scaleX*p],he=Pe[0|K*P.scaleX*p],te=255-m(be+1.402*(Le-128)),V=255-m(be-0.3441363*(ee-128)-0.71413636*(Le-128)),b=255-m(be+1.772*(ee-128));z[Me++]=255-te,z[Me++]=255-V,z[Me++]=255-b,z[Me++]=255-he}}break;default:throw Error("Unsupported color mode")}return z},copyToImageData:function(E,v){var{width:p,height:H,data:S}=E,R=this.getData(p,H),I=0,P=0,A,X,j,Pe,K,D,Me,be,ee;switch(this.components.length){case 1:for(X=0;X<H;X++)for(A=0;A<p;A++)if(j=R[I++],S[P++]=j,S[P++]=j,S[P++]=j,v)S[P++]=255;break;case 3:for(X=0;X<H;X++)for(A=0;A<p;A++)if(Me=R[I++],be=R[I++],ee=R[I++],S[P++]=Me,S[P++]=be,S[P++]=ee,v)S[P++]=255;break;case 4:for(X=0;X<H;X++)for(A=0;A<p;A++)if(K=R[I++],D=R[I++],j=R[I++],Pe=R[I++],Me=255-m(K*(1-Pe/255)+Pe),be=255-m(D*(1-Pe/255)+Pe),ee=255-m(j*(1-Pe/255)+Pe),S[P++]=Me,S[P++]=be,S[P++]=ee,v)S[P++]=255;break;default:throw Error("Unsupported color mode")}}};var d=0,$=0;function y(N=0){var E=d+N;if(E>$){var v=Math.ceil((E-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${v}MB`)}d=E}return h.resetMaxMemoryUsage=function(N){d=0,$=N},h.getBytesAllocated=function(){return d},h.requestMemoryAllocation=y,h}();if(typeof Bo<"u")Bo.exports=pc;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=pc;function pc(e,n={}){var t={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...t,...n},i=new Uint8Array(e),o=new zo;o.opts=r,zo.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,u=o.width*o.height*s;try{zo.requestMemoryAllocation(u);var c={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(u):Buffer.alloc(u)};if(o.comments.length>0)c.comments=o.comments}catch(a){if(a instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+u);if(a instanceof ReferenceError){if(a.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw a}return o.copyToImageData(c,r.formatAsRGBA),c}});var $c=ye((uk,bc)=>{var vd=mc(),Md=wc();bc.exports={encode:vd,decode:Md}});var Do=ye((ck,Ec)=>{var Id=Je("util"),kc=Je("stream"),ln=Ec.exports=function(){kc.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Id.inherits(ln,kc);ln.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};ln.prototype.write=function(e,n){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let t;if(Buffer.isBuffer(e))t=e;else t=Buffer.from(e,n||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};ln.prototype.end=function(e,n){if(e)this.write(e,n);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};ln.prototype.destroySoon=ln.prototype.end;ln.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};ln.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};ln.prototype._processReadAllowingLess=function(e){this._reads.shift();let n=this._buffers[0];if(n.length>e.length)this._buffered-=e.length,this._buffers[0]=n.slice(e.length),e.func.call(this,n.slice(0,e.length));else this._buffered-=n.length,this._buffers.shift(),e.func.call(this,n)};ln.prototype._processRead=function(e){this._reads.shift();let n=0,t=0,r=Buffer.alloc(e.length);while(n<e.length){let i=this._buffers[t++],o=Math.min(i.length,e.length-n);if(i.copy(r,n,0,o),n+=o,o!==i.length)this._buffers[--t]=i.slice(o)}if(t>0)this._buffers.splice(0,t);this._buffered-=e.length,e.func.call(this,r)};ln.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}if(this._buffers&&!this.writable)this._end()}catch(e){this.emit("error",e)}}});var xo=ye((Nd)=>{var Cn=[{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]}];Nd.getImagePasses=function(e,n){let t=[],r=e%8,i=n%8,o=(e-r)/8,s=(n-i)/8;for(let u=0;u<Cn.length;u++){let c=Cn[u],a=o*c.x.length,h=s*c.y.length;for(let f=0;f<c.x.length;f++)if(c.x[f]<r)a++;else break;for(let f=0;f<c.y.length;f++)if(c.y[f]<i)h++;else break;if(a>0&&h>0)t.push({width:a,height:h,index:u})}return t};Nd.getInterlaceIterator=function(e){return function(n,t,r){let i=n%Cn[r].x.length,o=(n-i)/Cn[r].x.length*8+Cn[r].x[i],s=t%Cn[r].y.length,u=(t-s)/Cn[r].y.length*8+Cn[r].y[s];return o*4+u*e*4}}});var es=ye((hk,Sc)=>{Sc.exports=function(n,t,r){let i=n+t-r,o=Math.abs(i-n),s=Math.abs(i-t),u=Math.abs(i-r);if(o<=s&&o<=u)return n;if(s<=u)return t;return r}});var ns=ye((fk,vc)=>{var Fd=xo(),Hd=es();function yc(e,n,t){let r=e*n;if(t!==8)r=Math.ceil(r/(8/t));return r}var Tt=vc.exports=function(e,n){let{width:t,height:r,interlace:i,bpp:o,depth:s}=e;if(this.read=n.read,this.write=n.write,this.complete=n.complete,this._imageIndex=0,this._images=[],i){let u=Fd.getImagePasses(t,r);for(let c=0;c<u.length;c++)this._images.push({byteWidth:yc(u[c].width,o,s),height:u[c].height,lineIndex:0})}else this._images.push({byteWidth:yc(t,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Tt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Tt.prototype._unFilterType1=function(e,n,t){let r=this._xComparison,i=r-1;for(let o=0;o<t;o++){let s=e[1+o],u=o>i?n[o-r]:0;n[o]=s+u}};Tt.prototype._unFilterType2=function(e,n,t){let r=this._lastLine;for(let i=0;i<t;i++){let o=e[1+i],s=r?r[i]:0;n[i]=o+s}};Tt.prototype._unFilterType3=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,h=Math.floor((a+c)/2);n[s]=u+h}};Tt.prototype._unFilterType4=function(e,n,t){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<t;s++){let u=e[1+s],c=o?o[s]:0,a=s>i?n[s-r]:0,h=s>i&&o?o[s-r]:0,f=Hd(a,c,h);n[s]=u+f}};Tt.prototype._reverseFilterLine=function(e){let n=e[0],t,r=this._images[this._imageIndex],i=r.byteWidth;if(n===0)t=e.slice(1,i+1);else switch(t=Buffer.alloc(i),n){case 1:this._unFilterType1(e,t,i);break;case 2:this._unFilterType2(e,t,i);break;case 3:this._unFilterType3(e,t,i);break;case 4:this._unFilterType4(e,t,i);break;default:throw Error("Unrecognised filter type - "+n)}if(this.write(t),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=t;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Nc=ye((lk,Ic)=>{var Pd=Je("util"),Mc=Do(),Ld=ns(),Ad=Ic.exports=function(e){Mc.call(this);let n=[],t=this;this._filter=new Ld(e,{read:this.read.bind(this),write:function(r){n.push(r)},complete:function(){t.emit("complete",Buffer.concat(n))}}),this._filter.start()};Pd.inherits(Ad,Mc)});var Gt=ye((gk,Oc)=>{Oc.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 is=ye((dk,Rc)=>{var ts=[];(function(){for(let e=0;e<256;e++){let n=e;for(let t=0;t<8;t++)if(n&1)n=3988292384^n>>>1;else n=n>>>1;ts[e]=n}})();var rs=Rc.exports=function(){this._crc=-1};rs.prototype.write=function(e){for(let n=0;n<e.length;n++)this._crc=ts[(this._crc^e[n])&255]^this._crc>>>8;return!0};rs.prototype.crc32=function(){return this._crc^-1};rs.crc32=function(e){let n=-1;for(let t=0;t<e.length;t++)n=ts[(n^e[t])&255]^n>>>8;return n^-1}});var os=ye((mk,Fc)=>{var Ae=Gt(),Td=is(),Te=Fc.exports=function(e,n){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ae.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ae.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ae.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ae.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ae.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ae.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=n.read,this.error=n.error,this.metadata=n.metadata,this.gamma=n.gamma,this.transColor=n.transColor,this.palette=n.palette,this.parsed=n.parsed,this.inflateData=n.inflateData,this.finished=n.finished,this.simpleTransparency=n.simpleTransparency,this.headersFinished=n.headersFinished||function(){}};Te.prototype.start=function(){this.read(Ae.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Te.prototype._parseSignature=function(e){let n=Ae.PNG_SIGNATURE;for(let t=0;t<n.length;t++)if(e[t]!==n[t]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Te.prototype._parseChunkBegin=function(e){let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(e[o]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&t!==Ae.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Td,this._crc.write(Buffer.from(r)),this._chunks[t])return this._chunks[t](n);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(n+4,this._skipChunk.bind(this))};Te.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Te.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Te.prototype._parseChunkEnd=function(e){let n=e.readInt32BE(0),t=this._crc.crc32();if(this._options.checkCRC&&t!==n){this.error(Error("Crc error - "+n+" - "+t));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Te.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Te.prototype._parseIHDR=function(e){this._crc.write(e);let n=e.readUInt32BE(0),t=e.readUInt32BE(4),r=e[8],i=e[9],o=e[10],s=e[11],u=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ae.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=Ae.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:n,height:t,depth:r,interlace:Boolean(u),palette:Boolean(i&Ae.COLORTYPE_PALETTE),color:Boolean(i&Ae.COLORTYPE_COLOR),alpha:Boolean(i&Ae.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Te.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Te.prototype._parsePLTE=function(e){this._crc.write(e);let n=Math.floor(e.length/3);for(let t=0;t<n;t++)this._palette.push([e[t*3],e[t*3+1],e[t*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Te.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Te.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ae.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let n=0;n<e.length;n++)this._palette[n][3]=e[n];this.palette(this._palette)}if(this._colorType===Ae.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ae.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Te.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Te.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ae.GAMMA_DIVISION),this._handleChunkEnd()};Te.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Te.prototype._parseIDAT=function(e,n){if(this._crc.write(n),this._colorType===Ae.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(n);let t=e-n.length;if(t>0)this._handleIDAT(t);else this._handleChunkEnd()};Te.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Te.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var ss=ye((Cd)=>{var Hc=xo(),Gd=[function(){},function(e,n,t,r){if(r===n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=255},function(e,n,t,r){if(r+1>=n.length)throw Error("Ran out of data");let i=n[r];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=n[r+1]},function(e,n,t,r){if(r+2>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=255},function(e,n,t,r){if(r+3>=n.length)throw Error("Ran out of data");e[t]=n[r],e[t+1]=n[r+1],e[t+2]=n[r+2],e[t+3]=n[r+3]}],Ud=[function(){},function(e,n,t,r){let i=n[0];e[t]=i,e[t+1]=i,e[t+2]=i,e[t+3]=r},function(e,n,t){let r=n[0];e[t]=r,e[t+1]=r,e[t+2]=r,e[t+3]=n[1]},function(e,n,t,r){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=r},function(e,n,t){e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3]}];function jd(e,n){let t=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let o=e[r];r++;let s,u,c,a,h,f,l,g;switch(n){default:throw Error("unrecognised depth");case 16:l=e[r],r++,t.push((o<<8)+l);break;case 4:l=o&15,g=o>>4,t.push(g,l);break;case 2:h=o&3,f=o>>2&3,l=o>>4&3,g=o>>6&3,t.push(g,l,f,h);break;case 1:s=o&1,u=o>>1&1,c=o>>2&1,a=o>>3&1,h=o>>4&1,f=o>>5&1,l=o>>6&1,g=o>>7&1,t.push(g,l,f,h,a,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(r!==e.length)throw Error("extra data found")}}}function Jd(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++)for(let h=0;h<s;h++){let f=t(h,a,c);Gd[r](n,i,f,o),o+=r}return o}function Kd(e,n,t,r,i,o){let{width:s,height:u,index:c}=e;for(let a=0;a<u;a++){for(let h=0;h<s;h++){let f=i.get(r),l=t(h,a,c);Ud[r](n,f,l,o)}i.resetAfterLine()}}Cd.dataToBitMap=function(e,n){let{width:t,height:r,depth:i,bpp:o,interlace:s}=n,u;if(i!==8)u=jd(e,i);let c;if(i<=8)c=Buffer.alloc(t*r*4);else c=new Uint16Array(t*r*4);let a=Math.pow(2,i)-1,h=0,f,l;if(s)f=Hc.getImagePasses(t,r),l=Hc.getInterlaceIterator(t,r);else{let g=0;l=function(){let m=g;return g+=4,m},f=[{width:t,height:r}]}for(let g=0;g<f.length;g++)if(i===8)h=Jd(f[g],c,l,o,e,h);else Kd(f[g],c,l,o,u,a);if(i===8){if(h!==e.length)throw Error("extra data found")}else u.end();return c}});var us=ye((wk,Pc)=>{function _d(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=i[e[o]];if(!c)throw Error("index "+e[o]+" not in palette");for(let a=0;a<4;a++)n[o+a]=c[a];o+=4}}function Qd(e,n,t,r,i){let o=0;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=!1;if(i.length===1){if(i[0]===e[o])c=!0}else if(i[0]===e[o]&&i[1]===e[o+1]&&i[2]===e[o+2])c=!0;if(c)for(let a=0;a<4;a++)n[o+a]=0;o+=4}}function qd(e,n,t,r,i){let o=255,s=Math.pow(2,i)-1,u=0;for(let c=0;c<r;c++)for(let a=0;a<t;a++){for(let h=0;h<4;h++)n[u+h]=Math.floor(e[u+h]*o/s+0.5);u+=4}}Pc.exports=function(e,n,t=!1){let{depth:r,width:i,height:o,colorType:s,transColor:u,palette:c}=n,a=e;if(s===3)_d(e,a,i,o,c);else{if(u)Qd(e,a,i,o,u);if(r!==8&&!t){if(r===16)a=Buffer.alloc(i*o*4);qd(e,a,i,o,r)}}return a}});var Tc=ye((bk,Ac)=>{var Zd=Je("util"),cs=Je("zlib"),Lc=Do(),Yd=Nc(),Xd=os(),Vd=ss(),zd=us(),En=Ac.exports=function(e){Lc.call(this),this._parser=new Xd(e,{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=e,this.writable=!0,this._parser.start()};Zd.inherits(En,Lc);En.prototype._handleError=function(e){if(this.emit("error",e),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};En.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=cs.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,r=Math.max(t,cs.Z_MIN_CHUNK);this._inflate=cs.createInflate({chunkSize:r});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(e)};En.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new Yd(this._bitmapInfo)};En.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};En.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};En.prototype._simpleTransparency=function(){this._metaData.alpha=!0};En.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};En.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};En.prototype._complete=function(e){if(this.errord)return;let n;try{let t=Vd.dataToBitMap(e,this._bitmapInfo);n=zd(t,this._bitmapInfo,this._options.skipRescale),t=null}catch(t){this._handleError(t);return}this.emit("parsed",n)}});var Uc=ye(($k,Gc)=>{var rn=Gt();Gc.exports=function(e,n,t,r){let i=[rn.COLORTYPE_COLOR_ALPHA,rn.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let m=function(){let d=new ArrayBuffer(2);return new DataView(d).setInt16(0,256,!0),new Int16Array(d)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&m)return e}let o=r.bitDepth!==16?e:new Uint16Array(e.buffer),s=255,u=rn.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(u===4&&!r.inputHasAlpha)u=3;let c=rn.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,c*=2;let a=Buffer.alloc(n*t*c),h=0,f=0,l=r.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 g(){let m,d,$,y=s;switch(r.inputColorType){case rn.COLORTYPE_COLOR_ALPHA:y=o[h+3],m=o[h],d=o[h+1],$=o[h+2];break;case rn.COLORTYPE_COLOR:m=o[h],d=o[h+1],$=o[h+2];break;case rn.COLORTYPE_ALPHA:y=o[h+1],m=o[h],d=m,$=m;break;case rn.COLORTYPE_GRAYSCALE:m=o[h],d=m,$=m;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,m=Math.min(Math.max(Math.round((1-y)*l.red+y*m),0),s),d=Math.min(Math.max(Math.round((1-y)*l.green+y*d),0),s),$=Math.min(Math.max(Math.round((1-y)*l.blue+y*$),0),s)}return{red:m,green:d,blue:$,alpha:y}}for(let m=0;m<t;m++)for(let d=0;d<n;d++){let $=g(o,h);switch(r.colorType){case rn.COLORTYPE_COLOR_ALPHA:case rn.COLORTYPE_COLOR:if(r.bitDepth===8){if(a[f]=$.red,a[f+1]=$.green,a[f+2]=$.blue,i)a[f+3]=$.alpha}else if(a.writeUInt16BE($.red,f),a.writeUInt16BE($.green,f+2),a.writeUInt16BE($.blue,f+4),i)a.writeUInt16BE($.alpha,f+6);break;case rn.COLORTYPE_ALPHA:case rn.COLORTYPE_GRAYSCALE:{let y=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(a[f]=y,i)a[f+1]=$.alpha}else if(a.writeUInt16BE(y,f),i)a.writeUInt16BE($.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}h+=u,f+=c}return a}});var Kc=ye((kk,Jc)=>{var jc=es();function Bd(e,n,t,r,i){for(let o=0;o<t;o++)r[i+o]=e[n+o]}function Dd(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++)r+=Math.abs(e[o]);return r}function xd(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=e[n+s]-u;r[i+s]=c}}function em(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=e[n+o]-s;i+=Math.abs(u)}return i}function nm(e,n,t,r,i){for(let o=0;o<t;o++){let s=n>0?e[n+o-t]:0,u=e[n+o]-s;r[i+o]=u}}function tm(e,n,t){let r=0,i=n+t;for(let o=n;o<i;o++){let s=n>0?e[o-t]:0,u=e[o]-s;r+=Math.abs(u)}return r}function rm(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=e[n+s]-(u+c>>1);r[i+s]=a}}function im(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=e[n+o]-(s+u>>1);i+=Math.abs(c)}return i}function om(e,n,t,r,i,o){for(let s=0;s<t;s++){let u=s>=o?e[n+s-o]:0,c=n>0?e[n+s-t]:0,a=n>0&&s>=o?e[n+s-(t+o)]:0,h=e[n+s]-jc(u,c,a);r[i+s]=h}}function sm(e,n,t,r){let i=0;for(let o=0;o<t;o++){let s=o>=r?e[n+o-r]:0,u=n>0?e[n+o-t]:0,c=n>0&&o>=r?e[n+o-(t+r)]:0,a=e[n+o]-jc(s,u,c);i+=Math.abs(a)}return i}var um={0:Bd,1:xd,2:nm,3:rm,4:om},cm={0:Dd,1:em,2:tm,3:im,4:sm};Jc.exports=function(e,n,t,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=n*i,u=0,c=0,a=Buffer.alloc((s+1)*t),h=o[0];for(let f=0;f<t;f++){if(o.length>1){let l=1/0;for(let g=0;g<o.length;g++){let m=cm[o[g]](e,c,s,i);if(m<l)h=o[g],l=m}}a[u]=h,u++,um[h](e,c,s,a,u,i),u+=s,c+=s}return a}});var as=ye((Ek,Cc)=>{var Ce=Gt(),am=is(),hm=Uc(),fm=Kc(),lm=Je("zlib"),Wn=Cc.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||lm.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:Ce.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:Ce.COLORTYPE_COLOR_ALPHA,[Ce.COLORTYPE_GRAYSCALE,Ce.COLORTYPE_COLOR,Ce.COLORTYPE_COLOR_ALPHA,Ce.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([Ce.COLORTYPE_GRAYSCALE,Ce.COLORTYPE_COLOR,Ce.COLORTYPE_COLOR_ALPHA,Ce.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw Error("option bit depth:"+e.bitDepth+" is not supported at present")};Wn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Wn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Wn.prototype.filterData=function(e,n,t){let r=hm(e,n,t,this._options),i=Ce.COLORTYPE_TO_BPP_MAP[this._options.colorType];return fm(r,n,t,this._options,i)};Wn.prototype._packChunk=function(e,n){let t=n?n.length:0,r=Buffer.alloc(t+12);if(r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),n)n.copy(r,8);return r.writeInt32BE(am.crc32(r.slice(4,r.length-4)),r.length-4),r};Wn.prototype.packGAMA=function(e){let n=Buffer.alloc(4);return n.writeUInt32BE(Math.floor(e*Ce.GAMMA_DIVISION),0),this._packChunk(Ce.TYPE_gAMA,n)};Wn.prototype.packIHDR=function(e,n){let t=Buffer.alloc(13);return t.writeUInt32BE(e,0),t.writeUInt32BE(n,4),t[8]=this._options.bitDepth,t[9]=this._options.colorType,t[10]=0,t[11]=0,t[12]=0,this._packChunk(Ce.TYPE_IHDR,t)};Wn.prototype.packIDAT=function(e){return this._packChunk(Ce.TYPE_IDAT,e)};Wn.prototype.packIEND=function(){return this._packChunk(Ce.TYPE_IEND,null)}});var qc=ye((Sk,Qc)=>{var gm=Je("util"),Wc=Je("stream"),dm=Gt(),mm=as(),_c=Qc.exports=function(e){Wc.call(this);let n=e||{};this._packer=new mm(n),this._deflate=this._packer.createDeflate(),this.readable=!0};gm.inherits(_c,Wc);_c.prototype.pack=function(e,n,t,r){if(this.emit("data",Buffer.from(dm.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(n,t)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,n,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 Bc=ye((Sr,zc)=>{var Zc=Je("assert").ok,Ut=Je("zlib"),pm=Je("util"),Yc=Je("buffer").kMaxLength;function st(e){if(!(this instanceof st))return new st(e);if(e&&e.chunkSize<Ut.Z_MIN_CHUNK)e.chunkSize=Ut.Z_MIN_CHUNK;if(Ut.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null)this._maxLength=e.maxLength}function wm(e){return new st(e)}function Xc(e,n){if(n)process.nextTick(n);if(!e._handle)return;e._handle.close(),e._handle=null}st.prototype._processChunk=function(e,n,t){if(typeof t==="function")return Ut.Inflate._processChunk.call(this,e,n,t);let r=this,i=e&&e.length,o=this._chunkSize-this._offset,s=this._maxLength,u=0,c=[],a=0,h;this.on("error",function(m){h=m});function f(m,d){if(r._hadError)return;let $=o-d;if(Zc($>=0,"have should not go down"),$>0){let y=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,y.length>s)y=y.slice(0,s);if(c.push(y),a+=y.length,s-=y.length,s===0)return!1}if(d===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(d===0)return u+=i-m,i=m,!0;return!1}Zc(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(n,e,u,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&f(l[0],l[1]));if(this._hadError)throw h;if(a>=Yc)throw Xc(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Yc.toString(16)+" bytes");let g=Buffer.concat(c,a);return Xc(this),g};pm.inherits(st,Ut.Inflate);function bm(e,n){if(typeof n==="string")n=Buffer.from(n);if(!(n instanceof Buffer))throw TypeError("Not a string or buffer");let t=e._finishFlushFlag;if(t==null)t=Ut.Z_FINISH;return e._processChunk(n,t)}function Vc(e,n){return bm(new st(n),e)}zc.exports=Sr=Vc;Sr.Inflate=st;Sr.createInflate=wm;Sr.inflateSync=Vc});var hs=ye((yk,xc)=>{var Dc=xc.exports=function(e){this._buffer=e,this._reads=[]};Dc.prototype.read=function(e,n){this._reads.push({length:Math.abs(e),allowLess:e<0,func:n})};Dc.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let n=this._buffer;this._buffer=n.slice(e.length),e.func.call(this,n.slice(0,e.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 ea=ye((Em)=>{var $m=hs(),km=ns();Em.process=function(e,n){let t=[],r=new $m(e);return new km(n,{read:r.read.bind(r),write:function(o){t.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(t)}});var ia=ye((Mk,ra)=>{var na=!0,ta=Je("zlib"),ym=Bc();if(!ta.deflateSync)na=!1;var vm=hs(),Mm=ea(),Im=os(),Nm=ss(),Om=us();ra.exports=function(e,n){if(!na)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let t;function r(v){t=v}let i;function o(v){i=v}function s(v){i.transColor=v}function u(v){i.palette=v}function c(){i.alpha=!0}let a;function h(v){a=v}let f=[];function l(v){f.push(v)}let g=new vm(e);if(new Im(n,{read:g.read.bind(g),error:r,metadata:o,gamma:h,palette:u,transColor:s,inflateData:l,simpleTransparency:c}).start(),g.process(),t)throw t;let d=Buffer.concat(f);f.length=0;let $;if(i.interlace)$=ta.inflateSync(d);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=ym(d,{chunkSize:p,maxLength:p})}if(d=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let y=Mm.process($,i);d=null;let N=Nm.dataToBitMap(y,i);y=null;let E=Om(N,i,n.skipRescale);return i.data=E,i.gamma=a||0,i}});var ca=ye((Ik,ua)=>{var oa=!0,sa=Je("zlib");if(!sa.deflateSync)oa=!1;var Rm=Gt(),Fm=as();ua.exports=function(e,n){if(!oa)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Fm(n||{}),i=[];if(i.push(Buffer.from(Rm.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let o=r.filterData(e.data,e.width,e.height),s=sa.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var aa=ye((Lm)=>{var Hm=ia(),Pm=ca();Lm.read=function(e,n){return Hm(e,n||{})};Lm.write=function(e,n){return Pm(e,n)}});var fa=ye((Km)=>{var Gm=Je("util"),ha=Je("stream"),Um=Tc(),jm=qc(),Jm=aa(),qe=Km.PNG=function(e){if(ha.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Um(e),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(n){this.data=n,this.emit("parsed",n)}.bind(this)),this._packer=new jm(e),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"))};Gm.inherits(qe,ha);qe.sync=Jm;qe.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};qe.prototype.parse=function(e,n){if(n){let t,r;t=function(i){this.removeListener("error",r),this.data=i,n(null,this)}.bind(this),r=function(i){this.removeListener("parsed",t),n(i,null)}.bind(this),this.once("parsed",t),this.once("error",r)}return this.end(e),this};qe.prototype.write=function(e){return this._parser.write(e),!0};qe.prototype.end=function(e){this._parser.end(e)};qe.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};qe.prototype._gamma=function(e){this.gamma=e};qe.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};qe.bitblt=function(e,n,t,r,i,o,s,u){if(t|=0,r|=0,i|=0,o|=0,s|=0,u|=0,t>e.width||r>e.height||t+i>e.width||r+o>e.height)throw Error("bitblt reading outside image");if(s>n.width||u>n.height||s+i>n.width||u+o>n.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)e.data.copy(n.data,(u+c)*n.width+s<<2,(r+c)*e.width+t<<2,(r+c)*e.width+t+i<<2)};qe.prototype.bitblt=function(e,n,t,r,i,o,s){return qe.bitblt(this,e,n,t,r,i,o,s),this};qe.adjustGamma=function(e){if(e.gamma){for(let n=0;n<e.height;n++)for(let t=0;t<e.width;t++){let r=e.width*n+t<<2;for(let i=0;i<3;i++){let o=e.data[r+i]/255;o=Math.pow(o,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(o*255)}}e.gamma=0}};qe.prototype.adjustGamma=function(){qe.adjustGamma(this)}});var Js=ye((rS,af)=>{var js={to(e,n){if(!n)return`\x1B[${e+1}G`;return`\x1B[${n+1};${e+1}H`},move(e,n){let t="";if(e<0)t+=`\x1B[${-e}D`;else if(e>0)t+=`\x1B[${e}C`;if(n<0)t+=`\x1B[${-n}A`;else if(n>0)t+=`\x1B[${n}B`;return t},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},F0={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},H0={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let n="";for(let t=0;t<e;t++)n+=this.line+(t<e-1?js.up():"");if(e)n+=js.left;return n}};af.exports={cursor:js,scroll:F0,erase:H0,beep:"\x07"}});import{spawnSync as S1}from"node:child_process";import{isMainThread as y1}from"node:worker_threads";import{parseArgs as w1}from"node:util";var Ke={name:"@kecan0406/ttheme",version:"1.0.42",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",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","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as Zh}from"node:fs";import{basename as d0,join as xr}from"node:path";var dd=/^#[0-9a-f]{6}$/;function Ft(e){return dd.test(e)}function Ue(e){let n=Number.parseInt(e.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function Qe(e){let[n,t,r]=Ue(e).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*n+0.7152*t+0.0722*r}function ze(e,n){let t=Qe(e),r=Qe(n);return(Math.max(t,r)+0.05)/(Math.min(t,r)+0.05)}function Ei(e,n){return Math.round(ze(e,n)*100)/100}function md(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function hn(e){let[n,t,r]=Ue(e).map(md),i=Math.cbrt(0.4122214708*n+0.5363325363*t+0.0514459929*r),o=Math.cbrt(0.2119034982*n+0.6806995451*t+0.1073969566*r),s=Math.cbrt(0.0883024619*n+0.2817188376*t+0.6299787005*r),u=1.9779984951*i-2.428592205*o+0.4505937099*s,c=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(u,c),h:(Math.atan2(c,u)*180/Math.PI+360)%360}}var jn=7,ec=3,_o=0.15,nc=1.6,qo=[1,2,3,4,5,6,9,10,11,12,13,14],tc=[7,15],Ht=[1,2,3,4,5,6],br={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},Zo=0.03,it=25,Mi=15,Ii=0.08;function Fn(e,n){let t=e.ansi[n];if(t===void 0)throw Error(`${e.name}: missing ANSI ${n}`);return t}function Qo(e,n,t){let r=e.background;return n.flatMap((i)=>{let o=Fn(e,i);return ze(o,r)<t?[`ANSI ${i} ${o} on ${r} is ${Ei(o,r)}:1, needs ${t}:1`]:[]})}function rc(e,n){return Math.min(...n.map((t)=>ze(Fn(e,t),e.background)))}var ic=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:jn,measure:({foreground:e,background:n})=>ze(e,n),check:({foreground:e,background:n})=>ze(e,n)<jn?[`foreground ${e} on ${n} is ${Ei(e,n)}:1, needs ${jn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ec,measure:(e)=>rc(e,qo),check:(e)=>Qo(e,qo,ec)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:_o,measure:(e)=>Qe(Fn(e,0)),check:(e)=>{let n=Fn(e,0);return Qe(n)>_o?[`ANSI 0 ${n} has luminance ${Qe(n).toFixed(3)}, needs <= ${_o}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:jn,measure:(e)=>rc(e,tc),check:(e)=>Qo(e,tc,jn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:nc,measure:(e)=>ze(Fn(e,8),e.background),check:(e)=>Qo(e,[8],nc)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:jn,measure:({foreground:e,selectionBackground:n})=>n===void 0?Number.NaN:ze(e,n),check:({foreground:e,selectionBackground:n})=>n!==void 0&&ze(e,n)<jn?[`foreground ${e} on selection ${n} is ${Ei(e,n)}:1, needs ${jn}:1`]:[]}];function Jn(e,n){let t=Math.abs(e-n)%360;return Math.min(t,360-t)}var Pt=(e)=>e>8?e-8:e;function Ni(e){let n=e.signatureSlots.filter((t)=>t.startsWith("ansi")).map((t)=>Number(t.slice(4)));return new Set(n.flatMap((t)=>Ht.includes(Pt(t))?[t,t>8?t-8:t+8]:[t]))}function wr(e,n){let t=hn(Fn(e,n));return t.c<Zo?void 0:t}function Si(e){let n=Ni(e);return qo.flatMap((t)=>{let r=wr(e,t),i=br[Pt(t)];if(r===void 0||i===void 0||n.has(t))return[];let o=Jn(r.h,i.center)-i.width;return o>0?[{slot:t,hue:r.h,over:o}]:[]})}function yi(e){let n=new Set(e.signatureSlots);return Ht.flatMap((t)=>{let r=wr(e,t),i=wr(e,t+8);if(r===void 0||i===void 0||n.has(`ansi${t}`)&&n.has(`ansi${t+8}`))return[];return[{normal:t,gap:Jn(r.h,i.h)}]})}function vi(e){let n=Ni(e);return[0,8].flatMap((t)=>Ht.flatMap((r)=>Ht.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[t+r,t+i],u=wr(e,o),c=wr(e,s);if(u===void 0||c===void 0||n.has(o)&&n.has(s))return[];return Jn(u.h,c.h)<Mi&&Math.abs(u.l-c.l)<Ii?[[o,s]]:[]})))}var pd=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Si(e).map((n)=>n.over)),check:(e)=>Si(e).map(({slot:n,hue:t,over:r})=>{let i=br[Pt(n)];return`ANSI ${n} ${Fn(e,n)} has hue ${t.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:it,measure:(e)=>Math.max(0,...yi(e).map((n)=>n.gap)),check:(e)=>yi(e).filter((n)=>n.gap>it).map(({normal:n,gap:t})=>`ANSI ${n+8} is ${t.toFixed(0)}° from ANSI ${n}, needs <= ${it}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>vi(e).length,check:(e)=>vi(e).map(([n,t])=>`ANSI ${n} ${Fn(e,n)} and ANSI ${t} ${Fn(e,t)} are within ${Mi}° hue and ${Ii} lightness`)}],Oi=[...ic,...pd],Yo=Oi.map((e)=>e.rule),ot=Oi.map(({rule:e,label:n,unit:t,min:r,max:i})=>({rule:e,label:n,unit:t,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Lt(e){return Oi.map((n)=>Math.round(n.measure(e)*1000)/1000)}function oc(e,n){return e.filter((t)=>!n.waive.includes(t.rule)).flatMap((t)=>t.check(n).map((r)=>({theme:n.name,rule:t.rule,detail:r})))}function At(e){return oc(Oi,e)}function sc(e){return oc(ic,e)}function uc(e){return e.flatMap(At)}import{existsSync as $p,readdirSync as Qa,readFileSync as ps}from"node:fs";import{basename as qa,join as Pr}from"node:path";/*!
3
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice, this
10
+ * list of conditions and the following disclaimer.
11
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ * this list of conditions and the following disclaimer in the
13
+ * documentation and/or other materials provided with the distribution.
14
+ * 3. Neither the name of the copyright holder nor the names of its contributors
15
+ * may be used to endorse or promote products derived from this software without
16
+ * specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ */function wd(e,n){let t=e.slice(0,n).split(/\r?\n/);return[t.length,t.pop().length+1]}function bd(e,n,t){let r=e.split(/\r?\n/),i="",o=(Math.log10(n+1)|0)+1;for(let s=n-1;s<=n+1;s++){let u=r[s-1];if(!u)continue;if(i+=s.toString().padEnd(o," "),i+=": ",i+=u,i+=`
29
+ `,s===n)i+=" ".repeat(o+t+2),i+=`^
30
+ `}return i}class J extends Error{line;column;codeblock;constructor(e,n){let[t,r]=wd(n.toml,n.ptr),i=bd(n.toml,t,r);super(`Invalid TOML document: ${e}
31
+
32
+ ${i}`,n);this.line=t,this.column=r,this.codeblock=i}static x(e,n,t){throw new J(e,{toml:n.s,ptr:t??n.p})}}/*!
33
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
34
+ * SPDX-License-Identifier: BSD-3-Clause
35
+ *
36
+ * Redistribution and use in source and binary forms, with or without
37
+ * modification, are permitted provided that the following conditions are met:
38
+ *
39
+ * 1. Redistributions of source code must retain the above copyright notice, this
40
+ * list of conditions and the following disclaimer.
41
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
42
+ * this list of conditions and the following disclaimer in the
43
+ * documentation and/or other materials provided with the distribution.
44
+ * 3. Neither the name of the copyright holder nor the names of its contributors
45
+ * may be used to endorse or promote products derived from this software without
46
+ * specific prior written permission.
47
+ *
48
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
49
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
50
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
51
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
52
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
54
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
55
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58
+ */function Ri(e){let n=e.p,t=e.s.charCodeAt(e.p++),r=t,i=t===39,o=t===e.s.charCodeAt(e.p)&&t===e.s.charCodeAt(e.p+1);if(o){if((t=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(t===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let s="",u=e.p,c=0;for(;e.p<e.s.length;e.p++)if(t=e.s.charCodeAt(e.p),o&&(t===10||t===13&&e.s.charCodeAt(e.p+1)===10))c=c&&3;else if(t<32&&t!==9||t===127)J.x("control characters are not allowed in strings",e);else if((!c||c===3)&&t===r&&(!o||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(o){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!c){let a=e.s.slice(u,e.p);s=s?s+a:a}return e.p+=o?3:1,s}else if(!c){if(!i&&t===92)s+=e.s.slice(u,u=e.p),c=1}else if(c===1)if(t===120||t===117||t===85){let a=e.p++-1,h=0,f=t===120?2:t===117?4:8;for(let l=0;l<f;l++,e.p++){let g=e.s.charCodeAt(e.p),m=g>=48&&g<=57?g-48:g>=65&&g<=70?g-65+10:g>=97&&g<=102?g-97+10:-1;if(m<0)J.x("invalid non-hex character in unicode escape",e);h=h<<4|m}if(h<0||h>1114111||h>=55296&&h<=57343)J.x("invalid unicode escape",e,a);s+=String.fromCodePoint(h),u=e.p--,c=0}else if(o&&(t===32||t===9))c=2;else{if(t===98)s+="\b";else if(t===116)s+="\t";else if(t===110)s+=`
59
+ `;else if(t===102)s+="\f";else if(t===114)s+="\r";else if(t===101)s+="\x1B";else if(t===34)s+='"';else if(t===92)s+="\\";else J.x("unrecognised escape sequence",e);u=e.p+1,c=0}else if(t!==32&&t!==9){if(c===2)J.x("invalid escape: only line-ending whitespace may be escaped",e,u);c=!i&&t===92?1:0,u=e.p}J.x("unfinished string",e,n)}/*!
60
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
61
+ * SPDX-License-Identifier: BSD-3-Clause
62
+ *
63
+ * Redistribution and use in source and binary forms, with or without
64
+ * modification, are permitted provided that the following conditions are met:
65
+ *
66
+ * 1. Redistributions of source code must retain the above copyright notice, this
67
+ * list of conditions and the following disclaimer.
68
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
69
+ * this list of conditions and the following disclaimer in the
70
+ * documentation and/or other materials provided with the distribution.
71
+ * 3. Neither the name of the copyright holder nor the names of its contributors
72
+ * may be used to endorse or promote products derived from this software without
73
+ * specific prior written permission.
74
+ *
75
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
76
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
77
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
78
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
79
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
80
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
81
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
82
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
83
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
84
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
85
+ */var $d=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Kn extends Date{#n=!1;#t=!1;#e=null;constructor(e,n,t){let r=!0,i=!0,o="Z",s;if(typeof e==="string")if(n)e:{if(n<3){if(+e.slice(11,13)>23){e="";break e}if(n===2)o=null,e+="Z";else if((s=e.charCodeAt(e.length-1))!==90&&s!==122)o=e.slice(e.length-6);if(t)e=e.slice(0,10)+"T"+e.slice(11)}else if(n===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=n!==4,i=n!==3}else{let u=e.match($d);if(u){if(!u[1])r=!1,e=`0000-01-01T${e}`;if(i=!!u[2],i&&e[10]===" "&&(e=e.replace(" ","T")),u[2]&&+u[2]>23)e="";else if(o=u[3]||null,!o&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#n=r,this.#t=i,this.#e=o}isDateTime(){return this.#n&&this.#t}isLocal(){return!this.#n||!this.#t||!this.#e}isDate(){return this.#n&&!this.#t}isTime(){return this.#t&&!this.#n}isValid(){return this.#n||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let t=new Kn(e);return t.#e=n,t}static wrapAsLocalDateTime(e){let n=new Kn(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new Kn(e);return n.#t=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new Kn(e);return n.#n=!1,n.#e=null,n}}/*!
86
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
87
+ * SPDX-License-Identifier: BSD-3-Clause
88
+ *
89
+ * Redistribution and use in source and binary forms, with or without
90
+ * modification, are permitted provided that the following conditions are met:
91
+ *
92
+ * 1. Redistributions of source code must retain the above copyright notice, this
93
+ * list of conditions and the following disclaimer.
94
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
95
+ * this list of conditions and the following disclaimer in the
96
+ * documentation and/or other materials provided with the distribution.
97
+ * 3. Neither the name of the copyright holder nor the names of its contributors
98
+ * may be used to endorse or promote products derived from this software without
99
+ * specific prior written permission.
100
+ *
101
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
102
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
103
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
104
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
105
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
106
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
107
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
108
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
109
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
110
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
111
+ */function Be(e,n=10){return n===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+n}function Vo(e,n){return e===32||e===9||e===10||e===13||n&&(e===n||e===44)||e===35}function kr(e,n){let t=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x("document contains excessively nested structures. aborting.",e);let i=r===91?hc(e):ac(e);return e.d++,i}if(r===34||r===39)return Ri(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)J.x("invalid value",e,t);return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)J.x("invalid value",e,t);return e.p++,!1}if(r===43||r===45)return Fi(e,e.p,e.s.charCodeAt(++e.p),44-r,n);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return kd(e,r,n);if(e.s.charCodeAt(e.p+2)===58)return Ed(e,r,n);return Fi(e,e.p,r,0,n)}function Fi(e,n,t,r,i){let o=t,s=0,u=!1;if(o===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)J.x("invalid value",e,n);return e.p++,(r||1)/0}if(o===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)J.x("invalid value",e,n);return e.p++,NaN}if(o===48){if(++e.p>=e.s.length||Vo(o=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(o===120)return Xo(e,n,16,i);else if(o===98)return Xo(e,n,2,i);else if(o===111)return Xo(e,n,8,i)}if(o===46)s=2;else if(o===101||o===69)s=4;else J.x("illegal leading zero",e,n)}else if(!Be(o))J.x("invalid value",e,n);while(++e.p<e.s.length&&(o=e.s.charCodeAt(e.p),!Vo(o,i))){if(!s)s=1;if(o===95){if(!(s&1))J.x("illegal underscore",e);s+=11,u=!0}else if(s===1&&o===46)s=2;else if((s===1||s===3)&&(o===101||o===69))s=4;else if(s===4&&(o===43||o===45));else if(!Be(o))J.x("illegal character in numeric literal",e);else if(s>9)s-=11;else if(!(s&1))s++}if(!s){let a=(t-48)*(r||1);return e.bi===!0?BigInt(a):a}if(!(s&1))J.x("unfinished numeric value",e,n);let c=e.s.slice(n,e.p);if(u)c=c.replaceAll("_","");return s>1?parseFloat(c):cc(e,c,10,n)}function Xo(e,n,t,r){let i,o=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Vo(i,r)))if(i===95){if(o&1)J.x("illegal underscore",e);o=3}else if(!Be(i,t))J.x("illegal character in numeric literal",e);else if(o&1)o--;if(o&1)J.x("unfinished numeric value",e);let s=e.s.slice(n+2,e.p);if(o)s=s.replaceAll("_","");return cc(e,s,t,n)}function cc(e,n,t,r){if(e.bi!==!0)e:{let i=parseInt(n,t);if(!Number.isSafeInteger(i)){if(e.bi)break e;J.x("integer value cannot be represented losslessly",e,r)}return i}return t===10?BigInt(n):BigInt((t===2?"0b":t===8?"0o":"0x")+n)}function kd(e,n,t){let r=e.p++,i;if(!Be(n)||!Be(e.s.charCodeAt(e.p++))||!Be(e.s.charCodeAt(e.p++))||!Be(e.s.charCodeAt(e.p++)))return Fi(e,e.p=r,n,0,t);if(e.p+=5,!Be(e.s.charCodeAt(e.p++)))J.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((n=e.s.charCodeAt(e.p))!==32||(i=!0,!Be(e.s.charCodeAt(e.p+1))))&&n!==84&&n!==116){let s=e.s.slice(r,e.p);return $r(e,s,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)J.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(Be(e.s.charCodeAt(++e.p)));if(n=e.s.charCodeAt(e.p)){if(n===90||n===122){let s=e.s.slice(r,++e.p);return $r(e,s,1,i,r,"[+00:00]")}if(n===43||n===45){let s=e.s.slice(r,e.p+=6);return $r(e,s,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let o=e.s.slice(r,e.p);return $r(e,o,2,i,r)}function Ed(e,n,t){let r=e.p;if(!Be(n)||!Be(e.s.charCodeAt(++e.p)))return Fi(e,--e.p,n,0,t);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(Be(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return $r(e,i,4,!1,r)}function $r(e,n,t,r,i,o){if(e.ld){let s=new Kn(n,t,r);if(!s.isValid())J.x("invalid date",e,i);return s}try{if(o)n+=o;switch(t){case 1:return Temporal.ZonedDateTime.from(n);case 2:return Temporal.PlainDateTime.from(n);case 3:return Temporal.PlainDate.from(n);case 4:return Temporal.PlainTime.from(n)}}catch(s){J.x(s instanceof Error?s.message:""+s,e,i)}}/*!
112
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
113
+ * SPDX-License-Identifier: BSD-3-Clause
114
+ *
115
+ * Redistribution and use in source and binary forms, with or without
116
+ * modification, are permitted provided that the following conditions are met:
117
+ *
118
+ * 1. Redistributions of source code must retain the above copyright notice, this
119
+ * list of conditions and the following disclaimer.
120
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
121
+ * this list of conditions and the following disclaimer in the
122
+ * documentation and/or other materials provided with the distribution.
123
+ * 3. Neither the name of the copyright holder nor the names of its contributors
124
+ * may be used to endorse or promote products derived from this software without
125
+ * specific prior written permission.
126
+ *
127
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
128
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
129
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
130
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
131
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
132
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
133
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
134
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
135
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
136
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
137
+ */function Sd(e){for(;e.p<e.s.length;e.p++){let n=e.s.charCodeAt(e.p);if(n===10)break;if(n===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(n<32&&n!==9||n===127)J.x("control characters are not allowed in comments",e)}}function fn(e,n,t){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!n&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(t||r!==35)break;Sd(e)}}/*!
138
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
139
+ * SPDX-License-Identifier: BSD-3-Clause
140
+ *
141
+ * Redistribution and use in source and binary forms, with or without
142
+ * modification, are permitted provided that the following conditions are met:
143
+ *
144
+ * 1. Redistributions of source code must retain the above copyright notice, this
145
+ * list of conditions and the following disclaimer.
146
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
147
+ * this list of conditions and the following disclaimer in the
148
+ * documentation and/or other materials provided with the distribution.
149
+ * 3. Neither the name of the copyright holder nor the names of its contributors
150
+ * may be used to endorse or promote products derived from this software without
151
+ * specific prior written permission.
152
+ *
153
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
154
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
155
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
156
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
157
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
158
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
159
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
160
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
161
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
162
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
163
+ */function Hi(e,n=61){let t,r=0,i=[],o,s=e.s.charCodeAt(t=e.p);do if(s===n){if(!r)J.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(o,e.p));return e.p++,i}else if(s===46){if(!r)J.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(o,e.p));r=0}else if(!r&&(s===34||s===39)){if(s===e.s.charCodeAt(e.p+1)&&s===e.s.charCodeAt(e.p+2))J.x("illegal quoted key: multiline strings are not allowed",e);i.push(Ri(e)),r=2,e.p--}else if(s===32||s===9){if(r===1)i.push(e.s.slice(o,e.p)),r=2}else if(r===2||s<48&&s!==45||s>57&&s<65||s>90&&s<97&&s!==95||s>122)J.x("illegal character in key",e);else if(!r)r=1,o=e.p;while(s=e.s.charCodeAt(++e.p));J.x("incomplete key-value: cannot find end of key",e,t)}function ac(e){let n=e.p++,t=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(fn(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,t;let o,s=t,u=!1,c=e.p,a=Hi(e);for(let f=0;f<a.length;f++){if(f)s=u?s[o]:s[o]=Object.create(null);if(o=a[f],(u=Object.hasOwn(s,o))&&(typeof s[o]!=="object"||r.has(s[o])))J.x("trying to redefine an already defined value",e,c);let l=o==="__proto__";if(e.uk&&(l||o==="constructor")){s=e.uk!==1&&J.x("document contains an unsafe property",e,c);break}if(!u&&l)Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(u)J.x("trying to redefine an already defined value",e,c);fn(e,!0,!0);let h=kr(e,125);if(s&&typeof(s[o]=h)==="object")r.add(h);if(fn(e),(i=e.s.charCodeAt(e.p++))===125)return t;if(i!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished table",e,n)}function hc(e){let n=e.p++,t=[],r;while(e.p<e.s.length){if(fn(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,t;if(t.push(kr(e,93)),fn(e),(r=e.s.charCodeAt(e.p++))===93)return t;if(r!==44)J.x("expected comma or end of structure",e,e.p-1)}J.x("unfinished array",e,n)}/*!
164
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
165
+ * SPDX-License-Identifier: BSD-3-Clause
166
+ *
167
+ * Redistribution and use in source and binary forms, with or without
168
+ * modification, are permitted provided that the following conditions are met:
169
+ *
170
+ * 1. Redistributions of source code must retain the above copyright notice, this
171
+ * list of conditions and the following disclaimer.
172
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
173
+ * this list of conditions and the following disclaimer in the
174
+ * documentation and/or other materials provided with the distribution.
175
+ * 3. Neither the name of the copyright holder nor the names of its contributors
176
+ * may be used to endorse or promote products derived from this software without
177
+ * specific prior written permission.
178
+ *
179
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
180
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
181
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
182
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
183
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
184
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
185
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
186
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
187
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
188
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
189
+ */function fc(e,n,t,r,i){let o=t,s=r,u,c=!1,a;for(let h=0;h<n.length;h++){if(h){if(o=c?o[u]:o[u]=Object.create(null),s=(a=s[u]).c,i===0&&(a.t===1||a.t===2))return null;if(a.t===2){let f=o.length-1;o=o[f],s=s[f].c}}if(u=n[h],(c=Object.hasOwn(o,u))&&s[u]?.t===0&&s[u]?.d)return null;if(!c){let f=u==="__proto__";if(e.uk&&(f||u==="constructor"))return!1;if(f)Object.defineProperty(o,u,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,u,{enumerable:!0,configurable:!0,writable:!0});s[u]={t:h<n.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(a=s[u],a.t!==i&&!(i===1&&a.t===3))return null;if(i===2){if(!a.d)a.d=!0,o[u]=[];o[u].push(o=Object.create(null)),a.c[a.i++]=a={t:1,d:!1,i:0,c:Object.create(null)}}if(a.d)return null;if(a.d=!0,i===1)o=c?o[u]:o[u]=Object.create(null);else if(i===0&&c)return null;return[u,o,a.c]}function lc(e,n,t){if(n===null||e.uk===2)J.x(n===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,t)}function Er(e,n={}){let t={s:e,p:0,d:n.maxDepth??1000,bi:n.integersAsBigInt??!1,ld:n.useLegacyDate??!0,uk:n.unsafeKeyBehaviour==="throw"?2:n.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),o,s=!1,u=r,c=i;if(e.charCodeAt(0)===65279)t.p++;fn(t);while(t.p<e.length){if(e.charCodeAt(t.p)===91){let a=e.charCodeAt(++t.p)===91;o=t.p+=+a,s=!1;let h=Hi(t,93);if(a){if(e.charCodeAt(t.p)!==93)J.x("expected end of table array declaration",t);t.p++}let f=fc(t,h,r,i,a?2:1);if(!f)lc(t,f,o),s=!0;else c=f[2],u=f[1]}else{o=t.p;let a=Hi(t),h=fc(t,a,u,c,0);if(!h&&!s)lc(t,h,o);fn(t,!0,!0);let f=kr(t,void 0);if(h&&!s)h[1][h[0]]=f}if(fn(t,!0),t.p<e.length&&(o=e.charCodeAt(t.p))!==10&&(o!==13||e.charCodeAt(t.p+1)!==10))J.x("each key-value declaration must be followed by an end-of-line",t);fn(t)}return r}/*!
190
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
191
+ * SPDX-License-Identifier: BSD-3-Clause
192
+ *
193
+ * Redistribution and use in source and binary forms, with or without
194
+ * modification, are permitted provided that the following conditions are met:
195
+ *
196
+ * 1. Redistributions of source code must retain the above copyright notice, this
197
+ * list of conditions and the following disclaimer.
198
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
199
+ * this list of conditions and the following disclaimer in the
200
+ * documentation and/or other materials provided with the distribution.
201
+ * 3. Neither the name of the copyright holder nor the names of its contributors
202
+ * may be used to endorse or promote products derived from this software without
203
+ * specific prior written permission.
204
+ *
205
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
206
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
207
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
208
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
209
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
210
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
211
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
212
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
213
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
214
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
215
+ */var B1=!!"".isWellFormed;/*!
216
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
217
+ * SPDX-License-Identifier: BSD-3-Clause
218
+ *
219
+ * Redistribution and use in source and binary forms, with or without
220
+ * modification, are permitted provided that the following conditions are met:
221
+ *
222
+ * 1. Redistributions of source code must retain the above copyright notice, this
223
+ * list of conditions and the following disclaimer.
224
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
225
+ * this list of conditions and the following disclaimer in the
226
+ * documentation and/or other materials provided with the distribution.
227
+ * 3. Neither the name of the copyright holder nor the names of its contributors
228
+ * may be used to endorse or promote products derived from this software without
229
+ * specific prior written permission.
230
+ *
231
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
232
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
233
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
234
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
235
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
236
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
237
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
238
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
239
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
240
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
241
+ */import{readdirSync as Wm,rmSync as _m,statSync as Qm}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as qm}from"node:net";import{homedir as Zm}from"node:os";import{join as Nr}from"node:path";import{setTimeout as Ym}from"node:timers/promises";var da=ki($c(),1),Li=ki(fa(),1),la=[137,80,78,71,13,10,26,10],ma=13;function yr(e){return e.length>=la.length&&la.every((n,t)=>e[t]===n)}function fs(e){let n=Li.PNG.sync.read(Buffer.from(e));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function vr(e,n){if(yr(e)){let t=Mr(e);if(t&&t.width*t.height>n)throw Error(`${t.width}×${t.height} is over ${n/1e6} megapixels`);return fs(e)}if(e[0]===255&&e[1]===216){let t=da.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:n/1e6,maxMemoryUsageInMB:1024});return{width:t.width,height:t.height,data:t.data}}throw Error("not a PNG or JPEG image")}function ut(e){let n=new Li.PNG({width:e.width,height:e.height});return n.data=Buffer.from(e.data),Li.PNG.sync.write(n)}function ga(e,n){for(let t=0;t+n.length<=e.length;t++){let r=!0;for(let i=0;i<n.length&&r;i++)r=e[t+i]===n.charCodeAt(i);if(r)return t}return-1}function Mr(e){if(e.length<33||!yr(e))return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength),t=n.getUint32(16),r=n.getUint32(20);if(e[25]===4||e[25]===6)return{width:t,height:r,alpha:!0};let i=ga(e,"IDAT");return{width:t,height:r,alpha:ga(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function pa(e,n=ma){let{width:t,height:r}=e,i=-1,o=-1;for(let s=0;s<e.height;s++)for(let u=0;u<e.width;u++)if((e.data[(s*e.width+u)*4+3]??0)>=n)t=Math.min(t,u),i=Math.max(i,u),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:t,y:r,w:i-t+1,h:o-r+1}}function _n(e,n={x:0,y:0,w:e.width,h:e.height}){let t=0;for(let r=n.y;r<n.y+n.h;r++)for(let i=n.x;i<n.x+n.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<ma)t++;return Math.round(t*100/(n.w*n.h))}function Cm(e,n){if(n<=1)return e;let t=Math.max(1,Math.floor(e.width/n)),r=Math.max(1,Math.floor(e.height/n)),i=new Uint8Array(t*r*4),o=e.data;for(let s=0;s<r;s++)for(let u=0;u<t;u++){let c=0,a=0,h=0,f=0;for(let g=0;g<n;g++)for(let m=0;m<n;m++){let d=((s*n+g)*e.width+u*n+m)*4,$=o[d+3]??0;c+=(o[d]??0)*$,a+=(o[d+1]??0)*$,h+=(o[d+2]??0)*$,f+=$}let l=(s*t+u)*4;if(f>0)i[l]=Math.round(c/f),i[l+1]=Math.round(a/f),i[l+2]=Math.round(h/f);i[l+3]=Math.round(f/(n*n))}return{width:t,height:r,data:i}}function wa(e,n,t){let r=Math.min(n/e.width,t/e.height),i=Math.max(1,Math.round(e.width*r)),o=Math.max(1,Math.round(e.height*r)),s=Ai(e,{x:0,y:0,w:e.width,h:e.height},i,o),u=new Uint8Array(n*t*4),c=Math.floor((n-i)/2),a=Math.floor((t-o)/2);for(let h=0;h<o;h++)u.set(s.data.subarray(h*i*4,(h+1)*i*4),((a+h)*n+c)*4);return{width:n,height:t,data:u}}function Ai(e,n,t,r){let i=Math.max(1,Math.floor(Math.min(n.w/t,n.h/r))),o=Cm(e,i),s=o.data,u=new Uint8Array(t*r*4);for(let c=0;c<r;c++){let a=Math.min(o.height-1,Math.max(0,n.y/i+(c+0.5)*n.h/i/r-0.5)),h=Math.floor(a),f=Math.min(o.height-1,h+1),l=a-h;for(let g=0;g<t;g++){let m=Math.min(o.width-1,Math.max(0,n.x/i+(g+0.5)*n.w/i/t-0.5)),d=Math.floor(m),$=Math.min(o.width-1,d+1),y=m-d,N=(h*o.width+d)*4,E=(h*o.width+$)*4,v=(f*o.width+d)*4,p=(f*o.width+$)*4,H=(s[N+3]??0)*(1-y)*(1-l),S=(s[E+3]??0)*y*(1-l),R=(s[v+3]??0)*(1-y)*l,I=(s[p+3]??0)*y*l,P=H+S+R+I,A=(c*t+g)*4;if(P>0)for(let X=0;X<3;X++){let j=(s[N+X]??0)*H+(s[E+X]??0)*S+(s[v+X]??0)*R+(s[p+X]??0)*I;u[A+X]=Math.round(j/P)}u[A+3]=Math.round(P)}}return{width:t,height:r,data:u}}var ct=100,Sn=25000000,Xm=536870912,Or=["safe","questionable","explicit"],at=["nudity","underwear"],Vm={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Ir={safe:"s",questionable:"q",explicit:"e"},zm=8191,Bm=20000,Dm=5000,ba=3000,$a=8,xm=3000,ya=60000,ka=3,gs=`ttheme/${Ke.version} (+${Ke.homepage})`,ep=["orig","tile","thumb","cut"],va=new Map,np=fp(process.env.TTHEME_FIND_HOSTS),tp=hp(process.env.TTHEME_FIND_CUTOUTS);qm(xm);function Ea(e){try{return Wm(e)}catch{return[]}}function Ti(e){return e.startsWith("//")?`https:${e}`:e}function Rr(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function Fr(e){let n=e.trim();if(!n)return[];let t=JSON.parse(n);if(Array.isArray(t))return t;let r=t.posts;return Array.isArray(r)?r:[]}function rp(e){let n=e.trim(),r=(n?JSON.parse(n):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function ls(e,n,t){let r=Ti(String(e??""));return{file:r,width:Number(n)||0,height:Number(t)||0,ext:Rr(r)}}function Ma(e,n){let t=Ti(String(n.preview??""));if(!n.file||!t||!Number(e.id))return[];let r=Number(e.width??e.image_width)||0,i=Number(e.height??e.image_height)||0;return[{id:Number(e.id),width:r,height:i,file:n.file,preview:t,ext:n.ext,owner:String(n.owner??""),artist:n.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(n.md5??""),source:String(e.source??""),tags:n.tags.split(/\s+/).filter(Boolean),solo:n.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:n.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function ip(e){let n=rp(e);return Fr(e).flatMap((t)=>{let r=Ti(String(t.file_url??"")),i=String(t.tags??"");return Ma(t,{preview:t.preview_url,file:r,ext:String(t.file_ext||Rr(r)).toLowerCase(),owner:t.author,artist:i.split(/\s+/).find((o)=>n.get(o)==="artist")??"",md5:t.md5,tags:i,solo:void 0,versions:[ls(t.jpeg_url,t.jpeg_width,t.jpeg_height),ls(t.sample_url,t.sample_width,t.sample_height)]})})}function op(e){return Fr(e).flatMap((n)=>{let t=Ti(String(n.file_url??"")),r=String(n.tag_string??""),i=n.media_asset??{};return Ma(n,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??n.preview_file_url,file:t,ext:String(n.file_ext||Rr(t)).toLowerCase(),owner:"",artist:String(n.tag_string_artist??"").split(/\s+/)[0]??"",md5:n.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>ls(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function sp(e){return Fr(e).flatMap((n)=>{let t=String(n.value??"");return t?[{value:t,count:Number(n.post_count)||0}]:[]})}function up(e){return Fr(e).flatMap((n)=>{let t=String(n.name??"");return t?[{value:t,count:Number(n.count)||0}]:[]})}function cp(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function ap(e){let n=e.trim()?JSON.parse(e):{};return Number(n.counts?.posts)||0}function hp(e){let n=new Map;for(let t of(e??"").split(/\s+/).filter(Boolean)){let r=t.indexOf("=");if(r>0)n.set(t.slice(0,r),t.slice(r+1).split(",").filter(Boolean))}return n}function fp(e){let n=new Map;for(let t of(e??"").split(/[\s,]+/).filter(Boolean)){let r=t.indexOf("="),i=t.slice(0,r);try{let o=new URL(t.slice(r+1));if(i&&o.protocol==="https:")n.set(i,o.origin)}catch{}}return n}function Ia(e,n,t,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=n.filter((s)=>i.includes(s));return o.length>0?o:[...t]}function jt(e){return Ia(e,Or,["safe"])}function Jt(e){return Ia(e,at,at,"none")}function Na(e,n,t){return{safe:new Set(e),questionable:new Set(n),explicit:new Set(t)}}function Oa(e){let n=np.get(e.key),t=tp.get(e.key);return{...e,origin:n??e.origin,moved:n!==void 0&&n!==e.origin,cutouts:t??e.cutouts,vouched:e.vouched&&t===void 0}}function Ra(e){return e.length<2?e.join(""):e.map((n)=>`~${n}`).join(" ")}function Sa(e){let n=Oa(e),t=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...n,cutouts:Ra(n.cutouts),ratings:Na([Ir.safe],[Ir.questionable],[Ir.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Ir[i]}`;let o=Or.filter((u)=>!r.includes(u)),[s]=o;return o.length===1&&s?`-rating:${Ir[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${n.origin}/post.json?${t({limit:String(ct),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${n.origin}/post.json?${t({tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/post/show/${r}`,parse:ip,count:cp}}function lp(e){let n=Oa(e),t=Na(["g"],["s","q"],["e"]);return{...n,cutouts:Ra(n.cutouts),ratings:t,rate:(r)=>r.length===Or.length?"":`rating:${r.flatMap((i)=>[...t[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${n.origin}/posts.json?${new URLSearchParams({limit:String(ct),page:String(i+1),tags:r})}`,countUrl:(r)=>`${n.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${n.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${n.origin}/posts/${r}`,parse:op,count:ap}}function gp(e){return x.find((n)=>n.key===e||n.name===e||new URL(n.origin).host===e)}function ds(e){return e.split(/\s+/).filter((n)=>n&&!n.startsWith("rating:")).length}function Gi(e,n){let t=e.trim();if(/^\d+$/.test(t))return{site:n,id:Number(t)};let r=/^([\w.]+):(\d+)$/.exec(t);if(r){let u=x.find((c)=>c.key===r[1]||c.name===r[1]);return u&&{site:u,id:Number(r[2])}}let i;try{i=new URL(t)}catch{return}let o=gp(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 x=[lp({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),Sa({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),Sa({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],Hn=134217728;function yn(e,n){let t=x.indexOf(e);return(t===-1?x.length:t)*Hn+n}function ms(e){let n;try{n=new URL(e).hostname}catch{return""}return n.split(".").slice(-2).join(".")}function Fa(){return x.filter((e)=>!e.tunneled).map((e)=>ms(e.origin)).flatMap((e)=>[e,`.${e}`]).join(",")}function Ui(e,n=at){return e.tags.filter((t)=>n.some((r)=>Vm[r].has(t)))}function ji(e,n,t=["safe"]){return t.some((r)=>e.ratings[r].has(n.rating))}function ht(e){return[e,...e.smaller].find((n)=>n.width*n.height<=Sn)}function Ha(e){let n=new Map;for(let[t,r]of[...e].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;n.set(r,[...n.get(r)??[],t])}return n}function Ji(){return Nr(process.env.XDG_CACHE_HOME??Nr(Zm(),".cache"),"ttheme")}function gn(e){return Nr(Ji(),e.key)}function Pa(e=Xm,n=Ji()){let t=[],r=0;for(let i of Ea(n))for(let o of ep){let s=Nr(n,i,o);for(let u of Ea(s)){let c=Nr(s,u);try{let{size:a,mtimeMs:h}=Qm(c);t.push({path:c,size:a,at:h}),r+=a}catch{}}}t.sort((i,o)=>i.at-o.at);for(let i of t){if(r<=e)return;try{_m(i.path,{force:!0}),r-=i.size}catch{}}}function dp(e,n){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let t=e===null?Number.NaN:Date.parse(e);return Number.isNaN(t)?ya:Math.max(0,t-n)}function Qn(e){return va.get(e.key)??0}function mp(e){for(let n=e;n instanceof Error;n=n.cause)if(n.code==="ECONNRESET")return!0;return!1}function pp(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}async function qn(e,n,t,r={},i=Bm){for(let o=1;;o++){let s=Qn(e)-Date.now();if(s>0)await Ym(s,void 0,{signal:t});let u;try{u=await fetch(n,{headers:{"User-Agent":gs,Referer:`${e.origin}/`,...r},signal:i?AbortSignal.any([t,AbortSignal.timeout(i)]):t})}catch(c){if(o<ka&&!t.aborted&&mp(c))continue;throw c}if(u.status===429&&o<ka){await u.body?.cancel();let c=dp(u.headers.get("retry-after"),Date.now());if(c>ya)throw Error(`${e.name} asks to wait ${Math.ceil(c/1000)}s`);va.set(e.key,Math.max(Qn(e),Date.now()+c));continue}if(!u.ok)throw await u.body?.cancel(),Error(pp(u)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${u.status}`);return u}}async function La(e,n,t,r){return e.parse(await(await qn(e,e.postsUrl(n,t),r)).text())}async function Aa(e,n,t){return e.count(await(await qn(e,e.countUrl(n),t)).text())}async function Hr(e,n,t){let[r]=e.parse(await(await qn(e,e.postUrl(n),t)).text());return r}function wp(e){let n=x.find((r)=>r.key==="danbooru"),t=new URLSearchParams({limit:String(2*ct),only:"md5,tag_string",tags:`md5:${e.join(",")}`});return`${n.origin}/posts.json?${t}`}function bp(e){return new Map(Fr(e).flatMap((n)=>{let t=String(n.md5??"");return t?[[t,String(n.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Ta(e,n){for(let t of e){let r=n.get(t.md5);if(r)t.tags=[...new Set([...t.tags,...r])],t.solo=r.includes("solo")}}async function Ga(e,n){let t=x.find((i)=>i.key==="danbooru"),r=new Map;if(Qn(t)>Date.now())return r;for(let i=0;i<e.length;i+=ct){let o=await(await qn(t,wp(e.slice(i,i+ct)),n,{},Dm)).text();for(let[s,u]of bp(o))r.set(s,u)}return r}async function Ua(e,n){let t=x.find((o)=>o.key==="danbooru");if(Qn(t)<=Date.now())try{let o=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String($a)}),s=`${t.origin}/autocomplete.json?${o}`;return sp(await(await qn(t,s,n,{},ba)).text())}catch(o){if(n.aborted)throw o}let r=x.find((o)=>o.key==="yande"),i=new URLSearchParams({name:e,order:"count",limit:String($a)});return up(await(await qn(r,`${r.origin}/tag.json?${i}`,n,{},ba)).text())}async function ja(e,n,t){let r=await qn(e,n,t,{Range:`bytes=0-${zm}`});return Mr(new Uint8Array(await r.arrayBuffer()))}async function Ki(e,n,t,r){let i=await qn(e,n,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:f,value:l}=await s.read();if(f)break;u.push(l),c+=l.length,r?.(c,o)}let a=new Uint8Array(c),h=0;for(let f of u)a.set(f,h),h+=f.length;return a}var lt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Lr="Original",Ar="community",kp=1e6,vn="_groups.toml",Ja=3,Ka=8,Ca="[a-z0-9]+(?:-[a-z0-9]+)*",Ep=new RegExp(`^(?:(${Ca})/)?(${Ca})$`),Za=["background","foreground","cursor","selection"];function ae(e,n){throw Error(`${e}: ${n}`)}function ft(e,n,t){if(typeof t!=="string"||!Ft(t))ae(e,`${n} must be "#rrggbb" (lowercase), got ${JSON.stringify(t)}`);return t}function Tr(e,n,t){if(typeof t!=="string"||t.length===0)ae(e,`${n} must be a non-empty string`);return t}function Zn(e){return e.replace("/","--")}function Xe(e){let n=e.indexOf("/");return n<0?void 0:e.slice(0,n)}function Yn(e){let n=Ep.exec(e);if(!n)return"takes lowercase letters, digits and single hyphens, as <palette> or <author>/<palette>";if((n[1]?.length??0)>39)return"has an author longer than a GitHub handle can be";return(n[2]?.length??0)>40?"is longer than 40 characters":void 0}function ws(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function Ci(e,n,t){let r=Tr(e,n,t),i=ws(r);if(i)ae(e,`${n} ${JSON.stringify(r)} ${i}`);return r}function Wa(e,n,t){let r=Tr(e,n,t),i=Yn(r);if(i)ae(e,`${n} "${r}" ${i}`);return r}function Kt(e){return e&&typeof e==="object"?e:{}}function Sp(e,n,t){if(n===void 0)return[t.cursor,t.selectionBackground,t.background];let r=Array.isArray(n)?n:[n];if(r.length===0)ae(e,"ghostty.icon_screen must not be empty");return r.map((i,o)=>ft(e,`ghostty.icon_screen[${o}]`,i))}function yp(e,n,t){let r=Kt(n);return{iconGhost:r.icon_ghost===void 0?t.cursor:ft(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:Sp(e,r.icon_screen,t)}}function vp(e){return new Map([...Za.map((n)=>[n,e[n]]),...e.ansi.map((n,t)=>[`ansi${t}`,n])])}function Mp(e,n,t){if(!Array.isArray(n)||n.length!==Ja)ae(e,`meta.signature must name exactly ${Ja} palette slots`);let r=vp(t),i=[],o=[];for(let[s,u]of n.entries()){let c=`meta.signature[${s}]`,a=Tr(e,c,u),h=r.get(a);if(h===void 0)ae(e,`${c} ${JSON.stringify(u)} is not a palette slot — use ${Za.join(", ")} or ansi0-ansi15`);i.push(a),o.push(h)}if(new Set(o).size!==o.length)ae(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Ip(e,n,t){if(n===void 0)return;if(!t)ae(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!n||typeof n!=="object"||Array.isArray(n))ae(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(n)){let s=x.find((c)=>c.key===i);if(!s)ae(e,`meta.booru_sites.${i} is not a find site — use ${x.map((c)=>c.key).join(", ")}`);let u=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!u||u.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))ae(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(u.length>1&&Number.isFinite(s.tagBudget))ae(e,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=u}return r}function Np(e,n){if(n===void 0)return;if(!Array.isArray(n)||n.length===0||n.length>Ka)ae(e,`[[picture]] holds 1 to ${Ka} pictures`);return n.map((t,r)=>{let i=Kt(t),o=`picture[${r}]`,s=x.find((h)=>h.key===i.site);if(!s)ae(e,`${o}.site must be one of ${x.map((h)=>h.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ae(e,`${o}.id must be the post's number on ${s.name}`);let{size:u,position:c,opacity:a}=i;if(u!==void 0&&u!=="fill"&&!(Number.isInteger(u)&&Number(u)>=20&&Number(u)<=999))ae(e,`${o}.size must be "fill" or a percentage from 20 to 999`);if(c!==void 0&&!lt.includes(c))ae(e,`${o}.position must be one of ${lt.join(", ")}`);if(a!==void 0&&!(typeof a==="number"&&a>=0&&a<=1))ae(e,`${o}.opacity must be a number from 0 to 1`);return{site:s.key,id:i.id,...u!==void 0?{size:u}:{},...c!==void 0?{position:c}:{},...a!==void 0?{opacity:a}:{}}})}function Ya(e,n){try{return Er(n)}catch(t){ae(e,`is not valid TOML — ${(t instanceof Error?t.message:String(t)).split(`
242
+ `)[0]}`)}}function Op(e){let t=Ya(vn,ps(Pr(e,vn),"utf8")).group;if(!Array.isArray(t)||t.length===0)ae(vn,"needs at least one [[group]] table");return t.map((r)=>{let i=Kt(r);return{name:Ci(vn,"group.name",i.name),native:i.native===void 0?void 0:Ci(vn,"group.native",i.native),lead:Tr(vn,"group.lead",i.lead)}})}function Wi(e,n,t){let r=Ya(e,n),i=Kt(r.meta),o=Kt(r.colors),s=Kt(r.contrast),u=o.ansi;if(!Array.isArray(u)||u.length!==16)ae(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(u)?u.length:typeof u}`);let c=Wa(e,"meta.name",i.name);if(c!==t.name)ae(e,`meta.name "${c}" does not match its file — it lives at ${t.name}`);let a=Xe(c)!==void 0;for(let I of["order","role"])if(a&&i[I]!==void 0)ae(e,`meta.${I} is for the official palettes — a shared palette follows its base`);let h=i.role;if(h!==void 0&&h!=="default")ae(e,`meta.role must be "default", got ${JSON.stringify(h)}`);let f=i.base===void 0?void 0:Wa(e,"meta.base",i.base);if(f!==void 0&&!a)ae(e,"meta.base is for shared palettes");if(f!==void 0&&!t.open&&t.bases&&!t.bases.has(f))ae(e,`meta.base "${f}" is not an official palette`);let l=f===void 0?void 0:t.bases?.get(f),g=a&&i.group===void 0?l?.group??Lr:Ci(e,"meta.group",i.group),m=t.groups.get(g);if(!m&&!(a&&(g===Lr||t.open)))ae(e,`meta.group "${g}" has no [[group]] table in ${vn}`);let d=ft(e,"colors.background",o.background),$=ft(e,"colors.foreground",o.foreground),y=ft(e,"colors.cursor",o.cursor),N=ft(e,"colors.selection_background",o.selection_background),E=u.map((I,P)=>ft(e,`colors.ansi[${P}]`,I)),v=Mp(e,i.signature,{background:d,foreground:$,cursor:y,selection:N,ansi:E}),p=i.booru===void 0?void 0:Tr(e,"meta.booru",i.booru);if(p!==void 0&&/[\s\p{Cc}]/u.test(p))ae(e,`meta.booru must be a single booru tag, got ${JSON.stringify(p)}`);let H=Ip(e,i.booru_sites,p),S=Array.isArray(s.waive)?s.waive.map(String):[];if(S.length>0&&typeof s.reason!=="string")ae(e,"contrast.waive needs a contrast.reason explaining why");let R=Np(e,r.picture);return{name:c,...f?{base:f}:{},group:g,native:m?.native,lead:m?.lead===c,order:a?l?.order??kp:Number(i.order),role:h,ansiSource:a&&i.ansi_source===void 0?f??"original":Ci(e,"meta.ansi_source",i.ansi_source),...p?{booru:p}:{},...H?{booruSites:H}:{},background:d,foreground:$,cursor:y,selectionBackground:N,ansi:E,signature:v.colors,signatureSlots:v.names,ghostty:yp(e,r.ghostty,{background:d,cursor:y,selectionBackground:N}),waive:S,waiveReason:typeof s.reason==="string"?s.reason:void 0,...R?{pictures:R}:{}}}function _a(e){return $p(e)?Qa(e).sort():[]}function Rp(e,n){return _a(e).flatMap((t)=>_a(Pr(e,t)).filter((r)=>r.endsWith(".toml")).map((r)=>{let i=`${Ar}/${t}/${r}`;return Wi(i,ps(Pr(e,t,r),"utf8"),{...n,name:`${t}/${qa(r,".toml")}`})}))}function Fp(e,n){let t=[];for(let r of e)t.push(r,...n.filter((i)=>i.base===r.name));for(let r of n.filter((i)=>i.base===void 0||!e.some((o)=>o.name===i.base))){let i=t.findLastIndex((o)=>o.group===r.group);t.splice(i<0?t.length:i+1,0,r)}return t}function _i(e){let n=Op(e),t=new Map(n.map((s)=>[s.name,s]));if(t.size!==n.length)ae(vn,"group.name must be unique");let r=Qa(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Wi(s,ps(Pr(e,s),"utf8"),{name:qa(s,".toml"),groups:t})).sort((s,u)=>s.order-u.order);if(new Set(r.map((s)=>s.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let s of n){let u=r.filter((c)=>c.group===s.name);if(u.length===0)ae(vn,`group "${s.name}" has no themes`);if(!u.some((c)=>c.name===s.lead))ae(vn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}let o=new Map(r.filter((s)=>s.role===void 0).map((s)=>[s.name,s]));return Fp(r,Rp(Pr(e,Ar),{groups:t,bases:o}))}function Xa(e){return e.filter((n)=>n.role===void 0)}function Gr(e){let n=(r,i)=>r<i?-1:r>i?1:0,t=(r)=>r.base??r.name;return[...e].sort((r,i)=>n(r.group.toLowerCase(),i.group.toLowerCase())||n(t(r),t(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||n(r.name,i.name))}var Hp=["black","red","green","yellow","blue","magenta","cyan","white"];function Va(e,n){return[e,...Hp.map((t,r)=>`${t} = '${n[r]}'`),""].join(`
243
+ `)}var Ur={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let n=[...Ct(e),"","[colors.primary]",`background = '${e.background}'`,`foreground = '${e.foreground}'`,"","[colors.cursor]",`cursor = '${e.cursor}'`,`text = '${e.background}'`,"","[colors.selection]",`background = '${e.selectionBackground}'`,`text = '${e.foreground}'`,"",Va("[colors.normal]",e.ansi.slice(0,8)),Va("[colors.bright]",e.ansi.slice(8,16))].join(`
244
+ `);return[{path:`alacritty/themes/${le(e.name)}.toml`,content:n}]}};var jr={id:"ghostty",emit(e){let n=[...Ct(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((t,r)=>`palette = ${r}=${t}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
245
+ `);return[{path:`ghostty/themes/${le(e.name)}`,content:n}]}};function Xn(e){let[n,t,r]=Ue(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":t/255,"Red Component":n/255}}function za(e){return{...Object.fromEntries(e.ansi.map((n,t)=>[`Ansi ${t} Color`,Xn(n)])),"Background Color":Xn(e.background),"Bold Color":Xn(e.foreground),"Cursor Color":Xn(e.cursor),"Cursor Text Color":Xn(e.background),"Foreground Color":Xn(e.foreground),"Selected Text Color":Xn(e.foreground),"Selection Color":Xn(e.selectionBackground)}}function Pp(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Ba(e,n,t,r){let i=(s,u)=>({Name:`ttheme · ${u}`,Guid:`ttheme-${u}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...Pp(n.get(s.name)),...za(s)}),o=[...t?[i(t,"default")]:[],...e.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
246
+ `}function Lp(e,n){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(n).flatMap(([t,r])=>[` <key>${t}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
247
+ `)}var Jr={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let n=['<?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(za(e)).map(([t,r])=>Lp(t,r)),"</dict>","</plist>",""].join(`
248
+ `);return[{path:`iterm2/${le(e.name)}.itermcolors`,content:n}]}};var Kr={id:"kitty",emit(e){let n=[...Ct(e),`background ${e.background}`,`foreground ${e.foreground}`,`cursor ${e.cursor}`,`cursor_text_color ${e.background}`,`selection_background ${e.selectionBackground}`,`selection_foreground ${e.foreground}`,...e.ansi.map((t,r)=>`color${r} ${t}`),""].join(`
249
+ `);return[{path:`kitty/themes/${le(e.name)}.conf`,content:n}]}};function Da(e){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(e.themes)}`,`BACKGROUNDS = ${JSON.stringify(e.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette.replace('/', '--', 1) + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, 'ttheme-' + palette.replace('/', '--', 1) + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
250
+ `)}import{createHash as _p}from"node:crypto";import{existsSync as uh,mkdirSync as Qp,readdirSync as qp,readFileSync as ch,renameSync as ah,rmSync as _t}from"node:fs";import{basename as hh,isAbsolute as Zp,join as oe}from"node:path";import{chmodSync as Ap,copyFileSync as Tp,existsSync as Wt,mkdirSync as Gp,readFileSync as bs,realpathSync as Up,renameSync as jp,rmSync as xa,statSync as Jp,writeFileSync as Kp}from"node:fs";import{dirname as Cp}from"node:path";function eh(e){return`${e}.ttheme.bak`}var Wp=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function $s(e){let n=eh(e);if(Wt(e)&&!Wt(n)&&!Wp.test(bs(e,"utf8")))Tp(e,n)}function Oe(e,n){let t=Wt(e)?Up(e):e;Gp(Cp(t),{recursive:!0});let r=`${t}.ttheme-${process.pid}`;if(Kp(r,n),Wt(t))Ap(r,Jp(t).mode&4095);jp(r,t)}function Cr(e,n){if((Wt(e)?bs(e,"utf8"):void 0)===n)return!1;return $s(e),Oe(e,n),!0}function nh(e,n){let t=eh(e),r=Wt(t)?bs(t,"utf8"):void 0;if(n===""&&r===void 0)return xa(e,{force:!0}),"removed";if(Oe(e,n),r===void 0||r===n)return xa(t,{force:!0}),"restored";return"kept backup"}var ks={width:2560,height:1550},Yp=2560,Xp=0.1,Pn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Vp=Qe(Ss("#19161e","#9b86c8",0.2)),zp="shelf",Qi="originals",Bp="images.json",Es=1;function Ss(e,n,t){let r=Ue(e),i=Ue(n);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*t).toString(16).padStart(2,"0")).join("")}`}function Dp(e,n){if(n==="background"||n==="foreground"||n==="cursor")return e[n];if(n==="selection"&&e.selection)return e.selection;let t=/^ansi(\d|1[0-5])$/.exec(n),r=t?e.ansi[Number(t[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${n}`);return r}function th(e){if(e(1))return 1;let n=0,t=1;for(let r=0;r<40;r++){let i=(n+t)/2;if(e(i))n=i;else t=i}return n}function rh(e,n){let t=Dp(e,n),i=th((a)=>sc({name:e.name,background:Ss(e.background,t,a),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),o=th((a)=>Qe(Ss(e.background,t,a))<=Vp),s=Math.floor(Math.min(i,o)*1000)/1000,u=Ue(e.background),c=Math.hypot(...Ue(t).map((a,h)=>(a-(u[h]??0))*s));return{slot:n,color:t,cap:i,matched:o,opacity:s,reach:c}}function Qt(e,n){let t=rh(e,"cursor");if(t.opacity>=Xp)return t;return n.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>rh(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,t)}function ys(e,n,t){let r=Ue(n),i=Ue(t),o=e.data;for(let s=0;s<o.length;s+=4){let u=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let c=0;c<3;c++)o[s+c]=Math.round((r[c]??0)+((i[c]??0)-(r[c]??0))*u)}return e}function xp(e,n,t){let r=Ue(n),i=e.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let u=(i[s+3]??0)/255*t;for(let c=0;c<3;c++)o[s+c]=Math.round((r[c]??0)*(1-u)+(i[s+c]??0)*u);o[s+3]=255}return{width:e.width,height:e.height,data:o}}function fh(e){return pa(e)??{x:0,y:0,w:e.width,h:e.height}}function e0(e,n){if(e<=0||n<=0)return ks;let t=Math.min(1,ks.width/Math.max(e,n));return{width:Math.round(e*t),height:Math.round(n*t)}}function n0(e,n){let t=Math.min(1,Yp/Math.max(n.w,n.h));return Ai(e,n,Math.round(n.w*t),Math.round(n.h*t))}function lh(e,n,t,r){if(r<Pn.stands){let c=e.w*t>e.h*n?{x:e.x+(e.w-e.h*n/t)/2,y:e.y,w:e.h*n/t,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*t/n};return{crop:c,at:{x:0,y:0,w:n,h:t},focus:(c.y-e.y+c.h/2)/e.h}}let i=Math.max(Pn.tall*t,Pn.reach*n*e.h/e.w),o=i*e.w/e.h;if(o>Pn.widest*n)o=Pn.widest*n,i=o*e.h/e.w;let s=Pn.headroom*t,u=Math.min(1,(t-s)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*u},at:{x:n*(1-Pn.margin)-o,y:s,w:o,h:i*u},focus:Math.min(1,(t/2-s)/i)}}function Is(e,n,t,r){let i=Math.max(1,Math.round(n.at.w)),o=Math.max(1,Math.round(n.at.h)),s=Ai(e,n.crop,i,o),u=new Uint8Array(t*r*4),c=Math.round(n.at.x),a=Math.round(n.at.y);for(let h=0;h<o;h++){let f=a+h,l=Math.max(0,-c),g=Math.min(i,t-c);if(f<0||f>=r||g<=l)continue;u.set(s.data.subarray((h*i+l)*4,(h*i+g)*4),(f*t+c+l)*4)}return{width:t,height:r,data:u}}function gh(e,n,t,r,i){let o=fh(e),s=Is(e,lh(o,r,i,_n(e,o)),r,i);return xp(ys(s,n.background,t.color),n.background,t.opacity)}function Ze(e){return oe(e,"ttheme","backgrounds")}function vs(e){return oe(e,Bp)}function Wr(e){try{return ch(e,"utf8")}catch{return}}function Vn(e){try{return qp(e)}catch{return[]}}function Mn(e){let n=Wr(vs(e));if(n===void 0)return r0(e);let t=JSON.parse(n);if(t.version!==Es)throw Error(`${vs(e)} is version ${t.version} — this ttheme reads version ${Es}`);return t}function t0(e,n){let t=n.pictures.findIndex((i)=>i.key===n.active),r=n.pictures[t];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${t+1}/${n.pictures.length}`,`background-image = ${oe(e,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
251
+ `)}function _r(e,n,t){Oe(vs(e),`${JSON.stringify(n,null,2)}
252
+ `);for(let r of t){let i=n.palettes[r],o=oe(e,`${Zn(r)}.conf`);if(i)Oe(o,t0(e,i));else _t(o,{force:!0})}}function dh(e,n){for(let t of Vn(e))if(t.startsWith(`${n.stem}.`)||t.startsWith(`${n.stem}@`))_t(oe(e,t),{force:!0});if(n.original)_t(oe(e,n.original),{force:!0})}function ih(e,n,t,r){let i=hh(/^background-image\s*=\s*(.*?)\s*$/m.exec(n??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let o=i.slice(0,i.indexOf("@")),s=r??/^# image (\S+)$/m.exec(n??"")?.[1]??`picture_${o.slice(e.length+1)}`,u=/^# from (.+)$/m.exec(n??"")?.[1],c=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(n??"")?.[1]??1),a=t.find((h)=>h.startsWith(`${e}-${s}.`));return{key:s,stem:o,fill:i,opacity:Number.isFinite(c)?c:1,...u?{from:u}:{},...a?{original:oe(Qi,a)}:{}}}function oh(e,n){if(uh(e))ah(e,n)}function r0(e){let n={version:Es,palettes:{}};if(!uh(e))return n;let t=Vn(oe(e,Qi)),r=Vn(e).filter((o)=>o.endsWith(".conf")&&o!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(o)).map((o)=>o.slice(0,-5)),i=oe(e,zp);for(let o of new Set([...r,...Vn(i)])){let s=[],u=ih(o,Wr(oe(e,`${o}.conf`)),t);if(u)oh(oe(e,`${o}.tune.conf`),oe(e,`${u.stem}.tune.conf`)),oh(oe(e,`${o}.off.conf`),oe(e,`${u.stem}.off.conf`)),s.push(u);for(let c of Vn(oe(i,o))){let a=oe(i,o,c),h=ih(o,Wr(oe(a,".conf")),t,c);if(!h)continue;for(let f of Vn(a)){let l=f===".tune.conf"||f===".off.conf"?`${h.stem}${f}`:`${o}${f}`;if(f!==".conf")ah(oe(a,f),oe(e,l))}_t(a,{recursive:!0}),s.push(h)}if(Vn(oe(i,o)).length===0)_t(oe(i,o),{recursive:!0,force:!0});if(s.length>0)s.sort((c,a)=>c.key<a.key?-1:c.key>a.key?1:0),n.palettes[o]={active:(u??s[0]).key,pictures:s}}if(Vn(i).length===0)_t(i,{recursive:!0,force:!0});return _r(e,n,Object.keys(n.palettes)),n}function sh(e,n,t){return n.startsWith("~/")?oe(t,n.slice(2)):Zp(n)?n:oe(e,n)}function mh(e,n,t){let r=new Map,i=(u,c)=>{let a=Wr(u);if(a===void 0)return!1;for(let h of a.split(`
253
+ `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(h);if(f?.[1]==="config-file"&&c<4)i(sh(e,f[2].replace(/^\?/,""),t),c+1);else if(f&&/^background-image(?:-fit|-opacity)?$/.test(f[1]))r.set(f[1],f[2])}return!0};if(!i(oe(e,`${Zn(n)}.conf`),0))return;let o=r.get("background-image")??"";if(o==="")return;let s=Number(r.get("background-image-opacity")??1);return{image:sh(e,o,t),opacity:Number.isFinite(s)?s:1,cover:r.get("background-image-fit")==="cover"}}function gt(e){return`${e.site}_${e.id}`}function ph(e,n,t){let r=Ze(e),i=Mn(r),o=i.palettes[n];if(!o||o.pictures.length<2)throw Error(`${n} has no other image`);let s=o.pictures.length,u=(o.pictures.findIndex((c)=>c.key===o.active)+t+s)%s;return o.active=o.pictures[u].key,_r(r,i,[n]),{key:o.active,at:u+1,of:s}}function wh(e,n){let t=Ze(e),r=Mn(t),i=r.palettes[n];if(!i)throw Error(`${n} has no image`);let o=i.pictures.findIndex((c)=>c.key===i.active),[s]=i.pictures.splice(o,1);dh(t,s);let u=i.pictures[o%Math.max(i.pictures.length,1)];if(u)i.active=u.key;else delete r.palettes[n];return _r(t,r,[n]),{key:s.key,left:i.pictures.length}}function qi(e,n,t,r,i,o){let s=Ze(e),u=n.name,c=gt(i),a=Mn(s),h=a.palettes[u]??{active:c,pictures:[]},f=fh(r),{width:l,height:g}=e0(o.width,o.height),m=lh(f,l,g,_n(r,f)),d=ut(ys(n0(r,f),n.background,t.color)),$=ut(ys(Is(r,m,l,g),n.background,t.color)),y=`${Zn(u)}.${_p("sha1").update(d).update($).digest("hex").slice(0,8)}`,N={key:c,stem:y,fill:`${y}@fill-${Math.round(m.focus*100)}.png`,opacity:t.opacity,...i.from?{from:i.from}:{},original:oe(Qi,`${Zn(u)}-${c}.${i.ext}`)},E=h.pictures.find((p)=>p.key===c);if(E)dh(s,E);let v=[oe(s,`${y}.png`),oe(s,N.fill),oe(s,N.original)];return Qp(oe(s,Qi),{recursive:!0}),Oe(v[0],d),Oe(v[1],$),Oe(v[2],i.bytes),h.pictures=E?h.pictures.map((p)=>p===E?N:p):[...h.pictures,N],h.active=c,a.palettes[u]=h,_r(s,a,[u]),[...v,oe(s,`${Zn(u)}.conf`)]}function bh(e,n,t){let r=Ze(e),i=Mn(r),o=i.palettes[n];if(o?.pictures.some((s)=>s.key===t)&&o.active!==t)o.active=t,_r(r,i,[n])}function Ns(e,n){let t=Mn(Ze(e)).palettes[n];if(!t)return[];return[...t.pictures.filter((i)=>i.key===t.active),...t.pictures.filter((i)=>i.key!==t.active)]}var Ms="top-right";function i0(e,n,t,r,i,o,s,u=-1){let c=Math.trunc,a=(o-1)%3,h=c((o-1)/3),f=t*n>=r*e!==!s,l=f?c(i*t/100):c(i*r*e/(100*n)),g=f?c(i*t*n/(100*e)):c(i*r/100),m=c(a*(t-l)/2),d=c(h*(r-g)/2);if(u>=0){if(l>t)m=c((t-l)/2);if(g>r)d=Math.max(r-g,Math.min(0,c(r/2)-c(u*g/100)))}return{x:m,y:d,w:l,h:g}}function $h(e,n){let t=Wr(oe(e,`${n.stem}.tune.conf`));if(t===void 0)return{};let r=(a)=>new RegExp(`^${a}\\s*=\\s*(.*?)\\s*$`,"m").exec(t)?.[1]??"",i=hh(r("background-image")),o=/@(\d+)-/.exec(i)?.[1],s=/@fill-\d+\.png$/.test(i)?"fill":o?Number(o):r("background-image-fit")==="cover"?"fill":100,u=r("background-image-position").replace("center-center","center")||"center",c=Number(r("background-image-opacity")||1);return{...s!=="fill"?{size:s}:{},...u!==Ms?{position:u}:{},...Number.isFinite(c)&&c!==n.opacity?{opacity:c}:{}}}function kh(e,n,t,r,i){let o=t.size??"fill",s=t.position??Ms,u=t.opacity??n.opacity;if(o==="fill"&&s===Ms&&u===n.opacity)return;let c=lt.indexOf(s)+1,a=oe(e,`${n.stem}.png`),h=oe(e,n.fill),f=!0,l=typeof o==="number"&&(o>100||!r&&s!=="center");if(o===100&&!l)h=a,f=!1;else if(typeof o==="number"){let m=fs(new Uint8Array(ch(a))),{width:d,height:$}=l?ks:m,y=l?Number(/@fill-(\d+)\.png$/.exec(n.fill)?.[1]??50):-1,N=i0(m.width,m.height,d,$,o,c,!1,y);h=oe(e,`${n.stem}@${o}-${s}${l?`-${d}x${$}`:""}.png`);let E=Is(m,{crop:{x:0,y:0,w:m.width,h:m.height},at:N,focus:y},d,$);Oe(h,ut(E)),f=l}let g=oe(e,`${n.stem}.tune.conf`);return Oe(g,[`background-image = ${h.startsWith(`${i}/`)?`~${h.slice(i.length)}`:h}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${s}`,`background-image-opacity = ${u}`,""].join(`
254
+ `)),g}function Eh(e){let n=new Map;for(let[t,r]of Object.entries(Mn(Ze(e)).palettes)){let[,i,o]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&o)n.set(t,{site:i,id:Number(o)})}return n}function on(e){let{slot:n,color:t,opacity:r}=Qt({name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi,waived:e.waive},e.signatureSlots);return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.lead?{lead:!0}:{},order:e.order,ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},...e.role==="default"?{default:!0}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,signature:e.signature,signatureSlots:e.signatureSlots,ansi:e.ansi,gate:Lt(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:n,color:t,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function sn(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},lead:e.lead===!0,order:e.order,...e.default?{role:"default"}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selectionBackground:e.selection,ansi:e.ansi,signature:e.signature,signatureSlots:e.signatureSlots,ghostty:{iconGhost:e.cursor,iconScreen:[e.cursor,e.selection,e.background]},waive:e.waived??[],...e.pictures?{pictures:e.pictures}:{}}}function dt(e){return e.filter((n)=>n.default!==!0)}function o0(e){let[n]=e;if(!n)throw Error("manifest needs at least one theme");return{version:Ke.version,gate:ot,placement:Pn,palettes:e.map(on)}}var Os={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(o0(e),null,2)}
255
+ `}]}};var s0=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Zi=[{name:"use",args:["<palette>"],about:"paint this tab — a unique prefix works: ttheme use ho",section:"tab",shell:!0},{name:"preview",args:[],about:"browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",shell:!0},{name:"next",args:[],about:"advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"make a palette the one new tabs open with",section:"tab"},{name:"on",args:[],about:"wear the default palette in new tabs again",section:"tab"},{name:"off",args:[],about:"take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"tab"},{name:"pin",args:[],about:"pick a palette for this directory — cd into it repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:[],about:"drop the palette pinned to this directory",section:"tab",shell:!0},{name:"config",args:[],about:"edit settings in $EDITOR — they apply in new tabs",section:"tab",shell:!0},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",section:"catalog"},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"print the matches as JSON: name, group, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh the catalog from the registry",section:"catalog"},{name:"new",args:["<name>"],about:"make a palette of your own, <you>/<name>, from another one — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"the palette to start from — the default one when left out"}}},{name:"edit",args:["<palette>"],about:"change one of your palettes in $EDITOR — checked against the gate before it is kept",section:"own"},{name:"check",args:["<palette>"],about:"measure a palette against the contrast gate and suggest colors that pass",section:"own",flags:{fix:{type:"boolean",about:"write the suggested colors into your palette"}}},{name:"share",args:["<palette>"],about:"print a share code — ttheme add <code> installs it anywhere, pictures included",section:"own"},{name:"submit",args:["<palette>"],about:"offer one of your palettes to the catalog, through a GitHub issue",section:"own"},{name:"init",args:[],about:"install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"accept every default without prompting"}}},{name:"uninstall",args:[],about:"take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"remove without asking"}}},{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:s0,about:"rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"intake",args:["<issue-body-file>","<login>"],about:"turn a palette issue into a community palette file — the submission bot's step, from a checkout",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",section:"setup",hidden:!0}];var Yi=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Mh="# ttheme begin",Ih="# ttheme end",Qr=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function qr(e,n){let t=`${Mh}
256
+ ${n}
257
+ ${Ih}
258
+ `;if(Qr.test(e))return e.replace(Qr,t);if(e==="")return t;return`${e.replace(/\n*$/,`
18
259
  `)}
19
- ${n}`}function Vn(t){let e=t.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(e===t)return t;return e.trim()===""?"":e.replace(/\n*$/,`
20
- `)}function Ke(t,e){let n=t.replace(Cn,"");return new RegExp(String.raw`^[ \t]*${e}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Wr(t){if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}function Zu(t,e,n=""){let r=[];if(!Ke(n,"command")){if(r.push(`command = ${t}/launch-tab.zsh`),!Ke(n,"shell-integration"))r.push("shell-integration = zsh")}if(e)r.push(`theme = ${ut(e)}`);return r.push(`config-file = ?${t}/backgrounds/shown.conf`),r.join(`
21
- `)}function qu(t){return`source ${t}/ttheme.zsh`}var _d="# ttheme settings — uncomment a line to change it; exported variables win over this file",Yn={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 Di(t,e){let n=`: \${${t}:=${e}}`;return Yn[t]?.default===e?`# ${n}`:n}function _u(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function Cd(t,e){if(_u(e).test(t))return t;let n=Yn[e];return`${t.replace(/\n*$/,`
260
+ ${t}`}function Zr(e){let n=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(n===e)return e;return n.trim()===""?"":n.replace(/\n*$/,`
261
+ `)}function mt(e,n){let t=e.replace(Qr,"");return new RegExp(String.raw`^[ \t]*${n}(?:[ \t]*=|[ \t]+\S)`,"m").test(t)}function Xi(e){if(e.TERM_PROGRAM==="WarpTerminal")return"warp";if(e.GHOSTTY_RESOURCES_DIR||e.TERM_PROGRAM==="ghostty")return"ghostty";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.ALACRITTY_WINDOW_ID)return"alacritty";if(e.ITERM_SESSION_ID||e.TERM_PROGRAM==="iTerm.app")return"iterm2";if(e.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(e.WT_SESSION&&!e.TERM_PROGRAM)return"windows-terminal";if(e.TERM?.startsWith("foot"))return"foot";return"unknown"}function Nh(e,n,t=""){let r=[];if(!mt(t,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!mt(t,"shell-integration"))r.push("shell-integration = zsh")}if(n)r.push(`theme = ${le(n)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
262
+ `)}function Oh(e){return`source ${e}/ttheme.zsh`}var u0="# ttheme settings — uncomment a line to change it; exported variables win over this file",Yr={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 Rs(e,n){let t=`: \${${e}:=${n}}`;return Yr[e]?.default===n?`# ${t}`:t}function Rh(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function c0(e,n){if(Rh(n).test(e))return e;let t=Yr[n];return`${e.replace(/\n*$/,`
22
263
  `)}
23
- ${n.doc}
24
- ${Di(e,n.default)}
25
- `}var Cu=Object.keys(Yn);function to(){let t=Object.entries(Yn).map(([e,n])=>`${n.doc}
26
- ${Di(e,n.default)}`);return`${[_d,...t].join(`
264
+ ${t.doc}
265
+ ${Rs(n,t.default)}
266
+ `}var Fh=Object.keys(Yr);function Fs(){let e=Object.entries(Yr).map(([n,t])=>`${t.doc}
267
+ ${Rs(n,t.default)}`);return`${[u0,...e].join(`
27
268
 
28
269
  `)}
29
- `}function Xu(t,e,n){let r=Di(e,n),i=_u(e);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
270
+ `}function Hh(e,n,t){let r=Rs(n,t),i=Rh(n);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
30
271
  `)}
31
272
  ${r}
32
- `}function Vu(t){if(t==="")return to();return Object.keys(Yn).reduce(Cd,t)}function Yu(t,e,n=""){return[...t?[`include themes/${ut(t)}.conf`]:[],`watcher ${e}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!Ke(n,r.split(" ")[0]))].join(`
33
- `)}function zu(t){let e=t.replace(Cn,"");return/^[ \t]*\[colors[\].]/m.test(e)||/^[ \t]*colors[ \t]*[.=]/m.test(e)}var Xd=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Ku=/^[ \t]*\[/m,Ju=/^[ \t]*import[ \t]*=/m,Vd=/^[ \t]*general[ \t]*[.=]/m;function Yd(t){return t?`[general]
34
- import = ["${t}"]`:""}function zn(t,e){let n=t.replace(Cn,""),r=Xd.exec(n);if(!r){let u=n.search(Ku),h=u<0?n:n.slice(0,u);if(Vd.test(n)||Ju.test(h))return;return Xn(t,Yd(e))}let i=r.index+r[0].length,o=n.slice(i),s=o.search(Ku);if(Ju.test(s<0?o:o.slice(0,s)))return;let c=e?`import = ["${e}"]
35
- `:"";return`${n.slice(0,i)}
36
- ${xu}
37
- ${c}${Qu}${o}`}var Wu=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,zd=/^return config[ \t]*$/gm;function Bu(t){return`dofile(${JSON.stringify(t)})(config)`}var Du=`local wezterm = require 'wezterm'
273
+ `}function Ph(e){if(e==="")return Fs();return Object.keys(Yr).reduce(c0,e)}function Lh(e,n,t=""){return[...e?[`include themes/${le(e)}.conf`]:[],`watcher ${n}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!mt(t,r.split(" ")[0]))].join(`
274
+ `)}function Ah(e){let n=e.replace(Qr,"");return/^[ \t]*\[colors[\].]/m.test(n)||/^[ \t]*colors[ \t]*[.=]/m.test(n)}var a0=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Sh=/^[ \t]*\[/m,yh=/^[ \t]*import[ \t]*=/m,h0=/^[ \t]*general[ \t]*[.=]/m;function f0(e){return e?`[general]
275
+ import = ["${e}"]`:""}function Xr(e,n){let t=e.replace(Qr,""),r=a0.exec(t);if(!r){let c=t.search(Sh),a=c<0?t:t.slice(0,c);if(h0.test(t)||yh.test(a))return;return qr(e,f0(n))}let i=r.index+r[0].length,o=t.slice(i),s=o.search(Sh);if(yh.test(s<0?o:o.slice(0,s)))return;let u=n?`import = ["${n}"]
276
+ `:"";return`${t.slice(0,i)}
277
+ ${Mh}
278
+ ${u}${Ih}${o}`}var vh=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,l0=/^return config[ \t]*$/gm;function Th(e){return`dofile(${JSON.stringify(e)})(config)`}var Gh=`local wezterm = require 'wezterm'
38
279
  local config = wezterm.config_builder()
39
280
 
40
- `;function th(t){let e=t.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return e===`${Du}return config
41
- `?"":e}function Bn(t,e){let n=`-- ttheme begin
42
- ${e}
281
+ `;function Uh(e){let n=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return n===`${Gh}return config
282
+ `?"":n}function Vr(e,n){let t=`-- ttheme begin
283
+ ${n}
43
284
  -- ttheme end
44
- `;if(Wu.test(t))return t.replace(Wu,n);if(t==="")return`${Du}${n}
285
+ `;if(vh.test(e))return e.replace(vh,t);if(e==="")return`${Gh}${t}
45
286
  return config
46
- `;let r=[...t.matchAll(zd)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${n}
47
- ${t.slice(r.index)}`}var eh="[appearance.themes]";function nh(t){let e=t.findIndex((r)=>r.trim()===eh);if(e<0)return;let n=t.findIndex((r,i)=>i>e&&r.trimStart().startsWith("["));return[e,n<0?t.length:n]}function xr(t){let e=t.split(`
48
- `),n=nh(e);if(!n)return;return e.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function rh(t){return`{ custom = { name = "${t}", path = "${ut(t)}.yaml" } }`}function Qr(t,e){let n=t.split(`
49
- `),r=nh(n);if(!r)return e===void 0?t:`${t.replace(/\n*$/,`
287
+ `;let r=[...e.matchAll(l0)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${t}
288
+ ${e.slice(r.index)}`}var jh="[appearance.themes]";function Jh(e){let n=e.findIndex((r)=>r.trim()===jh);if(n<0)return;let t=e.findIndex((r,i)=>i>n&&r.trimStart().startsWith("["));return[n,t<0?e.length:t]}function Vi(e){let n=e.split(`
289
+ `),t=Jh(n);if(!t)return;return n.slice(t[0]+1,t[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Kh(e){return`{ custom = { name = "${e}", path = "${le(e)}.yaml" } }`}function zi(e,n){let t=e.split(`
290
+ `),r=Jh(t);if(!r)return n===void 0?e:`${e.replace(/\n*$/,`
50
291
  `)}
51
- ${eh}
52
- theme = ${e}
53
- `;let i=n.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)n.splice(i,1,...e===void 0?[]:[`theme = ${e}`]);else if(e!==void 0)n.splice(r[0]+1,0,`theme = ${e}`);return n.join(`
54
- `)}function eo(t,e,n=[]){for(let a of t)for(let f of[a.name,a.group,a.native??"",a.ansiSource])if(/["$`\\]/.test(f))throw Error(`${a.name}: "${f}" contains a character that breaks zsh quoting`);let r=Math.max(0,...t.map((a)=>a.name.length)),i=(a,f)=>` ${a.name.padEnd(r)} "${f}"`,o=(a)=>a.map((f)=>f.name).join(" "),s=Ge(t),c=(a)=>`'${a.replaceAll("'","'\\''")}'`,u=Kr.filter((a)=>a.section!=="setup"&&!a.hidden),h=u.flatMap((a,f)=>f>0&&u[f-1]?.section!==a.section?["-",a.name]:[a.name]);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${ie.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${e??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${h.join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((a)=>a.shell).map((a)=>a.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((a)=>` ${a.name} ${c(a.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((a)=>` ${a.name} ${c(a.about)}`),")","","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Cu.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${to().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((a)=>i(a,[a.background,a.foreground,a.cursor,a.selection,...a.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(_n(s))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((a)=>i(a,a.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((a)=>a.native).map((a)=>i(a,a.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((a)=>i(a,a.ansiSource)),")",""].join(`
55
- `)}var no={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:eo(t.map(_i))}]}};var Bd=["black","red","green","yellow","blue","magenta","cyan","white"];function ih(t,e){return[` ${t}:`,...Bd.map((n,r)=>` ${n}: "${e[r]}"`)]}var Dn={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(t){let e=[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${Bt(t.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...ih("normal",t.ansi.slice(0,8)),...ih("bright",t.ansi.slice(8,16)),""].join(`
56
- `);return[{path:`warp/themes/${ut(t.name)}.yaml`,content:e}]}};var oh=(t)=>`[${t.map((e)=>`"${e}"`).join(", ")}]`,tr={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(t){let e=["[metadata]",`name = "${ut(t.name)}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${oh(t.ansi.slice(0,8))}`,`brights = ${oh(t.ansi.slice(8,16))}`,""].join(`
57
- `);return[{path:`wezterm/colors/${ut(t.name)}.toml`,content:e}]}},nn=(t)=>JSON.stringify(t);function sh(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${nn(t.path)}`,`local COLORS = ${nn(t.colors)}`,`local BACKGROUNDS = ${nn(t.backgrounds)}`,`local STARTUP = ${t.startup?nn(ut(t.startup)):"nil"}`,"local PALETTES = {",...t.palettes.map((e)=>` [${nn(e.name)}] = ${nn(e.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
58
- `)}var ch=["black","red","green","yellow","blue","purple","cyan","white"];function uh(t){return{name:ut(t.name),background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(ch.map((e,n)=>[e,t.ansi[n]])),...Object.fromEntries(ch.map((e,n)=>[`bright${e[0]?.toUpperCase()}${e.slice(1)}`,t.ansi[n+8]]))}}function ro(t,e,n){let r={...e&&n?{profiles:[{updates:e,colorScheme:ut(n)}]}:{},schemes:t.map(uh)};return`${JSON.stringify(r,null,2)}
59
- `}var er={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${ut(t.name)}.json`,content:`${JSON.stringify(uh(t),null,2)}
60
- `}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:ro(t)}]}};function ut(t){return`ttheme-${t}`}function Xe(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var ah=nr(import.meta.dirname,".."),tm=nr(ah,"themes"),io=nr(ah,"dist"),Zr=[Hn,Pn,On,tr,jn,er,Dn],em=[no,Ci],M$=Zr.map((t)=>t.id);async function qr({only:t}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let e=t&&t.length>0?Zr.filter((o)=>t.includes(o.id)):Zr,n=Au(tm),r=Hs(n);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(e.length===Zr.length)hh(io,{recursive:!0,force:!0});else for(let o of e)hh(nr(io,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...e,...em]){let s=n.flatMap((h)=>o.emit?.(h)??[]),c=o.emitShared?.(n)??[];for(let h of[...s,...c])await Bun.write(nr(io,h.path),h.content),i++;let u=s.length>0?`${n.length} themes${o.limits?` (${o.limits})`:""}`:c.map((h)=>Dd(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${u}`)}console.log(`
61
- ${n.length} themes (${Uu(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Fa}from"node:child_process";import{createHash as Na}from"node:crypto";import{existsSync as an,mkdirSync as fr,mkdtempSync as Rp,readFileSync as Ra,rmSync as Io,statSync as Op,writeFileSync as lr}from"node:fs";import{tmpdir as Hp}from"node:os";import{dirname as ci,join as ae}from"node:path";import{pathToFileURL as jp}from"node:url";import{execFile as nm}from"node:child_process";import{createHash as dh}from"node:crypto";import{existsSync as rm,mkdtempSync as im,readFileSync as Vr,rmSync as om,statSync as mh,writeFileSync as ph}from"node:fs";import{homedir as sm,tmpdir as cm}from"node:os";import{join as _r}from"node:path";import{fileURLToPath as um}from"node:url";import{promisify as hm}from"node:util";var ce=hm(nm),Cr=67108864,am=4096,co=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],fm=["text/uri-list","text/plain;charset=utf-8","text/plain"],oo=[...co,"text/uri-list","text/plain"];function lm(t){try{return mh(t).isFile()}catch{return!1}}function gm(t){let e=[],n="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else n+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))n+=t[++o];else n+=s;else if(s==="\\"&&o+1<t.length)n+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)e.push(n);n="",i=!1}else n+=s,i=!0}if(i)e.push(n);return e}function fh(t){if(/^file:\/\//i.test(t))try{return um(t)}catch{return}if(t.startsWith("~/"))return _r(sm(),t.slice(2));return t.startsWith("/")?t:void 0}function Yr(t,e=lm){let n=[];for(let r of t.replace(/\r\n?/g,`
292
+ ${jh}
293
+ theme = ${n}
294
+ `;let i=t.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)t.splice(i,1,...n===void 0?[]:[`theme = ${n}`]);else if(n!==void 0)t.splice(r[0]+1,0,`theme = ${n}`);return t.join(`
295
+ `)}function Hs(e,n,t=[]){for(let h of e)for(let f of[h.name,h.group,h.native??"",h.ansiSource])if(/["$`\\]/.test(f))throw Error(`${h.name}: "${f}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((h)=>h.name.length)),i=(h,f)=>` ${h.name.padEnd(r)} "${f}"`,o=(h)=>h.map((f)=>f.name).join(" "),s=dt(e),u=(h)=>`'${h.replaceAll("'","'\\''")}'`,c=Zi.filter((h)=>h.section!=="setup"&&!h.hidden),a=c.flatMap((h,f)=>f>0&&c[f-1]?.section!==h.section?["-",h.name]:[h.name]);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Ke.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${n??""}`,"","# 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(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${a.join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${c.filter((h)=>h.shell).map((h)=>h.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...c.map((h)=>` ${h.name} ${u(h.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...c.map((h)=>` ${h.name} ${u(h.about)}`),")","","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Fh.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Fs().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((h)=>i(h,[h.background,h.foreground,h.cursor,h.selection,...h.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Gr(s))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((h)=>i(h,h.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((h)=>h.native).map((h)=>i(h,h.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((h)=>i(h,h.ansiSource)),")",""].join(`
296
+ `)}var Ps={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Hs(e.map(on))}]}};var g0=["black","red","green","yellow","blue","magenta","cyan","white"];function Ch(e,n){return[` ${e}:`,...g0.map((t,r)=>` ${t}: "${n[r]}"`)]}var zr={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let n=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Qe(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...Ch("normal",e.ansi.slice(0,8)),...Ch("bright",e.ansi.slice(8,16)),""].join(`
297
+ `);return[{path:`warp/themes/${le(e.name)}.yaml`,content:n}]}};var Wh=(e)=>`[${e.map((n)=>`"${n}"`).join(", ")}]`,Br={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let n=["[metadata]",`name = "${le(e.name)}"`,`origin_url = "${e.ansiSource}"`,"","[colors]",`foreground = "${e.foreground}"`,`background = "${e.background}"`,`cursor_bg = "${e.cursor}"`,`cursor_border = "${e.cursor}"`,`cursor_fg = "${e.background}"`,`selection_bg = "${e.selectionBackground}"`,`selection_fg = "${e.foreground}"`,"",`ansi = ${Wh(e.ansi.slice(0,8))}`,`brights = ${Wh(e.ansi.slice(8,16))}`,""].join(`
298
+ `);return[{path:`wezterm/colors/${le(e.name)}.toml`,content:n}]}},qt=(e)=>JSON.stringify(e);function _h(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${qt(e.path)}`,`local COLORS = ${qt(e.colors)}`,`local BACKGROUNDS = ${qt(e.backgrounds)}`,`local STARTUP = ${e.startup?qt(le(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((n)=>` [${qt(n.name)}] = ${qt(n.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. (palette:gsub('/', '--', 1)) .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
299
+ `)}var Qh=["black","red","green","yellow","blue","purple","cyan","white"];function qh(e){return{name:le(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Qh.map((n,t)=>[n,e.ansi[t]])),...Object.fromEntries(Qh.map((n,t)=>[`bright${n[0]?.toUpperCase()}${n.slice(1)}`,e.ansi[t+8]]))}}function Ls(e,n,t){let r={...n&&t?{profiles:[{updates:n,colorScheme:le(t)}]}:{},schemes:e.map(qh)};return`${JSON.stringify(r,null,2)}
300
+ `}var Dr={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${le(e.name)}.json`,content:`${JSON.stringify(qh(e),null,2)}
301
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Ls(e)}]}};function le(e){return`ttheme-${Zn(e)}`}function Ct(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var Yh=xr(import.meta.dirname,".."),m0=xr(Yh,"themes"),As=xr(Yh,"dist"),Bi=[jr,Kr,Ur,Br,Jr,Dr,zr],p0=[Ps,Os],XE=Bi.map((e)=>e.id);async function Di({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let n=e&&e.length>0?Bi.filter((o)=>e.includes(o.id)):Bi,t=_i(m0),r=uc(t);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(n.length===Bi.length)Zh(As,{recursive:!0,force:!0});else for(let o of n)Zh(xr(As,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...n,...p0]){let s=t.flatMap((a)=>o.emit?.(a)??[]),u=o.emitShared?.(t)??[];for(let a of[...s,...u])await Bun.write(xr(As,a.path),a.content),i++;let c=s.length>0?`${t.length} themes${o.limits?` (${o.limits})`:""}`:u.map((a)=>d0(a.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
302
+ ${t.length} themes (${Xa(t).length} in the new-tab rotation) -> ${i} files in dist/`)}import{execFileSync as xw,spawn as eb,spawnSync as nb}from"node:child_process";import{existsSync as er,mkdirSync as al,readFileSync as xt,writeFileSync as tb}from"node:fs";import{dirname as hl}from"node:path";import{styleText as ro}from"node:util";import{stdout as lf,stdin as P0}from"node:process";import L0 from"node:readline";var Xh=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(n)=>{let t=0;e.lastIndex=0;while(e.test(n))t+=1;return n.length-t}})(),Vh=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},zh=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var w0=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,b0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Bh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,$0=/\t{1,1000}/y,Dh=/[\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,k0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,E0=/\p{M}+/gu,S0={limit:1/0,ellipsis:""},xh=(e,n={},t={})=>{let r=n.limit??1/0,i=n.ellipsis??"",o=n?.ellipsisWidth??(i?xh(i,S0,t).width:0),s=0,u=t.controlWidth??0,c=t.tabWidth??8,a=t.emojiWidth??2,h=2,f=t.regularWidth??1,l=t.wideWidth??2,g=[[k0,f],[w0,0],[b0,u],[$0,c],[Dh,a],[Bh,l]],m=0,d=0,$=e.length,y=0,N=!1,E=$,v=Math.max(0,r-o),p=0,H=0,S=0,R=0;e:while(!0){if(H>p||d>=$&&d>m){let I=e.slice(p,H)||e.slice(m,d);y=0;for(let P of I.replaceAll(E0,"")){let A=P.codePointAt(0)||0;if(Vh(A))R=2;else if(zh(A))R=l;else R=f;if(S+R>v)E=Math.min(E,Math.max(p,m)+y);if(S+R>r){N=!0;break e}y+=P.length,S+=R}p=H=0}if(d>=$)break e;for(let I=0,P=g.length;I<P;I++){let[A,X]=g[I];if(A.lastIndex=d,A.test(e)){if(y=A===Bh?Xh(e.slice(d,A.lastIndex)):A===Dh?1:A.lastIndex-d,R=y*X,S+R>v)E=Math.min(E,d+Math.floor((v-S)/X));if(S+R>r){N=!0;break e}S+=R,p=m,H=d,d=m=A.lastIndex;continue e}}d+=1}return{width:N?v:S,index:N?E:$,truncated:N,ellipsed:N&&r>=o}},ef=xh;var y0={limit:1/0,ellipsis:"",ellipsisWidth:0},v0=(e,n={})=>{return ef(e,y0,n).width},Ye=v0;var xi="\x1B",sf="›",M0=39,Gs="\x07",uf="[",I0="]",cf="m",Us=`${I0}8;;`,nf=new RegExp(`(?:\\${uf}(?<code>\\d+)m|\\${Us}(?<uri>.*)${Gs})`,"y"),tf=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},rf=(e)=>`${xi}${uf}${e}${cf}`,of=(e)=>`${xi}${Us}${e}${Gs}`,Ts=(e,n,t)=>{let r=n[Symbol.iterator](),i=!1,o=!1,s=e.at(-1),u=s===void 0?0:Ye(s),c=r.next(),a=r.next(),h=0;while(!c.done){let f=c.value,l=Ye(f);if(u+l<=t)e[e.length-1]+=f;else e.push(f),u=0;if(f===xi||f===sf)i=!0,o=n.startsWith(Us,h+1);if(i){if(o){if(f===Gs)i=!1,o=!1}else if(f===cf)i=!1}else if(u+=l,u===t&&!a.done)e.push(""),u=0;c=a,a=r.next(),h+=f.length}if(s=e.at(-1),!u&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},N0=(e)=>{let n=e.split(" "),t=n.length;while(t){if(Ye(n[t-1]))break;t--}if(t===n.length)return e;return n.slice(0,t).join(" ")+n.slice(t).join("")},O0=(e,n,t={})=>{if(t.trim!==!1&&e.trim()==="")return"";let r="",i,o,s=e.split(" "),u=[""],c=0;for(let f=0;f<s.length;f++){let l=s[f];if(t.trim!==!1){let m=u.at(-1)??"",d=m.trimStart();if(m.length!==d.length)u[u.length-1]=d,c=Ye(d)}if(f!==0){if(c>=n&&(t.wordWrap===!1||t.trim===!1))u.push(""),c=0;if(c||t.trim===!1)u[u.length-1]+=" ",c++}let g=Ye(l);if(t.hard&&g>n){let m=n-c,d=1+Math.floor((g-m-1)/n);if(Math.floor((g-1)/n)<d)u.push("");Ts(u,l,n),c=Ye(u.at(-1)??"");continue}if(c+g>n&&c&&g){if(t.wordWrap===!1&&c<n){Ts(u,l,n),c=Ye(u.at(-1)??"");continue}u.push(""),c=0}if(c+g>n&&t.wordWrap===!1){Ts(u,l,n),c=Ye(u.at(-1)??"");continue}u[u.length-1]+=l,c+=g}if(t.trim!==!1)u=u.map((f)=>N0(f));let a=u.join(`
303
+ `),h=!1;for(let f=0;f<a.length;f++){let l=a[f];if(r+=l,!h){if(h=l>="\uD800"&&l<="\uDBFF",h)continue}else h=!1;if(l===xi||l===sf){nf.lastIndex=f+1;let m=nf.exec(a)?.groups;if(m?.code!==void 0){let d=Number.parseFloat(m.code);i=d===M0?void 0:d}else if(m?.uri!==void 0)o=m.uri.length===0?void 0:m.uri}if(a[f+1]===`
304
+ `){if(o)r+=of("");let g=i?tf(i):void 0;if(i&&g)r+=rf(g)}else if(l===`
305
+ `){if(i&&tf(i))r+=rf(i);if(o)r+=of(o)}}return r},R0=/\r?\n/;function zn(e,n,t){return String(e).normalize().split(R0).map((r)=>O0(r,n,t)).join(`
306
+ `)}var De=ki(Js(),1);function Ln(e,n,t){if(!t.some((s)=>!s.disabled))return e;let r=e+n,i=Math.max(t.length-1,0),o=r<0?i:r>i?0:r;return t[o]?.disabled?Ln(o,n<0?-1:1,t):o}function eo(e,n,t,r){let i=r.split(`
307
+ `),o=0,s=e;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+t)),s=Math.min(s,i[o].length)+n;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let u=0;for(let c=0;c<o;c++)u+=i[c].length+1;return u+s}var A0=["up","down","left","right","space","enter","cancel"],T0=["January","February","March","April","May","June","July","August","September","October","November","December"],We={actions:new Set(A0),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:[...T0],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,n)=>`There are only ${e} days in ${n}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function gf(e,n){if(typeof e=="string")return We.aliases.get(e)===n;for(let t of e)if(t!==void 0&&gf(t,n))return!0;return!1}function G0(e,n){if(e===n)return;let t=e.split(`
308
+ `),r=n.split(`
309
+ `),i=Math.max(t.length,r.length),o=[];for(let s=0;s<i;s++)t[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:t.length,numLinesAfter:r.length,numLines:i}}var cS=globalThis.process.platform.startsWith("win"),Cs=Symbol("clack:cancel");function dn(e){return e===Cs}function no(e,n){let t=e;t.isTTY&&t.setRawMode(n)}var io=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,_s=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Bn(e,n,t,r=t,i=t,o){let s=io(e??lf);return zn(n,s-t.length,{hard:!0,trim:!1}).split(`
310
+ `).map((u,c,a)=>{let h=o?o(u,c):u;return c===0?`${r}${h}`:c===a.length-1?`${i}${h}`:`${t}${h}`}).join(`
311
+ `)}function df(e,n){if("~standard"in e){let t=e["~standard"].validate(n);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 e(n)}class mn{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,n=!0){let{input:t=P0,output:r=lf,render:i,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=n,this._abortSignal=o,this.input=t,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let t=this._subscribers.get(e)??[];t.push(n),this._subscribers.set(e,t)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let t=this._subscribers.get(e)??[],r=[];for(let i of t)i.cb(...n),i.once&&r.push(()=>t.splice(t.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Cs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=L0.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),no(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(De.cursor.show),this.output.off("resize",this.render),no(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(De.cursor.show),this.output.off("resize",this.render),no(this.input,!1),e(Cs)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&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(e,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&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"),n?.name&&(!this._track&&We.aliases.has(n.name)&&this.emit("cursor",We.aliases.get(n.name)),We.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let t=df(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")}gf([e,n?.name,n?.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(`
312
+ `),no(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=zn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
313
+ `).length-1;this.output.write(De.cursor.move(-999,e*-1))}render(){let e=zn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(De.cursor.hide);else{let n=G0(this._prevFrame,e),t=_s(this.output);if(this.restoreCursor(),n){let r=Math.max(0,n.numLinesAfter-t),i=Math.max(0,n.numLinesBefore-t),o=n.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(De.cursor.move(0,o-i)),this.output.write(De.erase.lines(1));let s=e.split(`
314
+ `);this.output.write(s[o]),this._prevFrame=e,this.output.write(De.cursor.move(0,s.length-o-1));return}else if(n.lines.length>1){if(r<i)o=r;else{let u=o-i;u>0&&this.output.write(De.cursor.move(0,u))}this.output.write(De.erase.down());let s=e.split(`
315
+ `).slice(o);this.output.write(s.join(`
316
+ `)),this._prevFrame=e;return}}this.output.write(De.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function U0(e,n){if(e===void 0||n.length===0)return 0;let t=n.findIndex((r)=>r.value===e);return t!==-1?t:0}function j0(e,n){return(n.label??String(n.value)).toLowerCase().includes(e.toLowerCase())}function J0(e,n){if(n)return e?n:n[0]}var K0=class extends mn{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#t="";#e;#o;#u;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return ro(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let n=this.userInput.slice(0,this.cursor),t=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${n}${ro("inverse",t)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(n){super(n),this.#o=n.options,this.#u=n.placeholder;let t=this.options;this.filteredOptions=[...t],this.multiple=n.multiple===!0,this.#e=typeof n.options=="function"?n.filter:n.filter??j0;let r;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?r=n.initialValue:r=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=t.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#n=o)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,o)=>this.#r(i,o)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(n,t){return n==="\t"||this.multiple&&this.isNavigating&&t.name==="space"&&n!==void 0&&n!==""}#r(n,t){let r=t.name==="up",i=t.name==="down",o=t.name==="return",s=this.userInput===""||this.userInput==="\t",u=this.#u,c=this.options,a=u!==void 0&&u!==""&&c.some((h)=>!h.disabled&&(this.#e?this.#e(u,h):!0));if(t.name==="tab"&&s&&a){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(u,!0),this.isNavigating=!1;return}r||i?(this.#n=Ln(this.#n,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=J0(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(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((t)=>t!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#i(n){if(n!==this.#t){this.#t=n;let t=this.options;n&&this.#e?this.filteredOptions=t.filter((o)=>this.#e?.(n,o)):this.filteredOptions=[...t];let r=U0(this.focusedValue,this.filteredOptions);this.#n=Ln(r,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Qs extends mn{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(De.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var C0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function hf(e){return[...e].map((n)=>C0[n])}function W0(e){let n=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),t=[],r="/";for(let i of n)i.type==="literal"?r=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:r}}function Ks(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function to(e){return{year:Ks(e.year),month:Ks(e.month),day:Ks(e.day)}}function Ws(e,n){return new Date(e||2001,n||1,0).getDate()}function mf(e){let{year:n,month:t,day:r}=to(e);if(!n||n<0||n>9999||!t||t<1||t>12||!r||r<1)return;let i=new Date(Date.UTC(n,t-1,r));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==t-1||i.getUTCDate()!==r))return{year:n,month:t,day:r}}function ff(e){let n=mf(e);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function _0(e,n,t,r){let i=t?{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:o?.year??9999}:e==="month"?{min:i&&n.year===i.year?i.month:1,max:o&&n.year===o.year?o.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:o&&n.year===o.year&&n.month===o.month?o.day:Ws(n.year,n.month)}}class pf extends mn{#n;#t;#e;#o;#u;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#n}get separator(){return this.#t}get formattedValue(){return this.#f(this.#e)}#f(e){return this.#n.map((n)=>e[n.type]).join(this.#t)}#c(){this._setUserInput(this.#f(this.#e)),this._setValue(ff(this.#e)??void 0)}constructor(e){let n=e.format?{segments:hf(e.format),separator:e.separator??"/"}:W0(e.locale),t=e.separator??n.separator,r=e.format?hf(e.format):n.segments,i=e.initialValue??e.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=r.map((u)=>o[u.type]).join(t);super({...e,initialUserInput:s},!1),this.#n=r,this.#t=t,this.#e=o,this.#o=e.minDate,this.#u=e.maxDate,this.#c(),this.on("cursor",(u)=>this.#d(u)),this.on("key",(u,c)=>this.#m(u,c)),this.on("finalize",()=>this.#p(e))}#a(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#n.length-1)),n=this.#n[e];if(n)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,n.len-1)),{segment:n,index:e}}#h(e){this.inlineError="",this.#s=null;let n=this.#a();n&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#l(e){let n=this.#a();if(!n)return;let{segment:t}=n,r=this.#e[t.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=_0(t.type,to(this.#e),this.#o,this.#u),u;i?u=e===1?s.min:s.max:u=Math.max(Math.min(s.max,o+e),s.min),this.#e={...this.#e,[t.type]:u.toString().padStart(t.len,"0")},this.#i=!0,this.#s=null,this.#c()}#d(e){if(e)switch(e){case"right":return this.#h(1);case"left":return this.#h(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(e,n){if(n?.name==="backspace"||n?.sequence===""||n?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let t=this.#a();if(!t)return;if(!this.#e[t.segment.type].replace(/_/g,"")){this.#h(-1);return}this.#e[t.segment.type]="_".repeat(t.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let t=this.#a();if(!t)return;let r=n.shift?-1:1,i=t.index+r;i>=0&&i<this.#n.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let t=this.#a();if(!t)return;let{segment:r}=t,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!i){let l=this.#s+e,g={...this.#e,[r.type]:l},m=this.#g(g,r);if(m){this.inlineError=m,this.#s=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=l,this.#s=null,this.#i=!1,this.#c(),t.index<this.#n.length-1&&(this.#r.segmentIndex=t.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#r.positionInSegment=0),this.#i=!1,this.#s=null;let o=this.#e[r.type],s=o.indexOf("_"),u=s>=0?s:Math.min(this.#r.positionInSegment,r.len-1);if(u<0||u>=r.len)return;let c=o.slice(0,u)+e+o.slice(u+1),a=!1;if(u===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(e,10);c=`0${e}`,a=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(c=(o.replace(/_/g,"")+e).padStart(r.len,"_")),!c.includes("_")){let l={...this.#e,[r.type]:c},g=this.#g(l,r);if(g){this.inlineError=g;return}}this.inlineError="",this.#e[r.type]=c;let h=c.includes("_")?void 0:mf(this.#e);if(h){let{year:l,month:g}=h,m=Ws(l,g);this.#e={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,g))).padStart(2,"0"),day:String(Math.max(1,Math.min(m,h.day))).padStart(2,"0")}}this.#c();let f=c.indexOf("_");a?(this.#i=!0,this.#s=e):f>=0?this.#r.positionInSegment=f:s>=0&&t.index<this.#n.length-1?(this.#r.segmentIndex=t.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(u+1,r.len-1)}}#g(e,n){let{month:t,day:r}=to(e);if(n.type==="month"&&(t<0||t>12))return We.date.messages.invalidMonth;if(n.type==="day"&&(r<0||r>31))return We.date.messages.invalidDay(31,"any month")}#p(e){let{year:n,month:t,day:r}=to(this.#e);if(n&&t&&r){let i=Ws(n,t);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=ff(this.#e)??e.defaultValue??void 0}}var Q0=class extends mn{options;cursor=0;#n;getGroupItems(n){return this.options.filter((t)=>t.group===n)}isGroupSelected(n){let t=this.getGroupItems(n),r=this.value;return r===void 0?!1:t.every((i)=>r.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let t=n.value,r=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let t=this.value.includes(n.value);this.value=t?this.value.filter((r)=>r!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:t}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(t).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===n.cursorAt),this.#n?0:1),this.on("cursor",(r)=>{switch(r){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.#n&&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.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},q0=new Set(["up","down","left","right"]);class wf extends mn{#n=!1;#t;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return t===`
317
+ `?`${n}█
318
+ ${r}`:`${n}${ro("inverse",t)}${r}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#o(e){let n=this.value??"";switch(e){case"up":this._cursor=eo(this._cursor,0,-1,n);return;case"down":this._cursor=eo(this._cursor,0,1,n);return;case"left":this._cursor=eo(this._cursor,-1,0,n);return;case"right":this._cursor=eo(this._cursor,1,0,n);return}}_shouldSubmit(e,n){if(this.#t)return this.focused==="submit"?!0:(this.#e(`
319
+ `),this._cursor++,!1);let t=this.#n;return this.#n=!0,t&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
320
+ `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
321
+ `),this._cursor++,!1)}constructor(e){let n=e.initialUserInput??e.initialValue;super({...e,initialUserInput:n},!1),n!==void 0&&(this._cursor=n.length),this.#t=e.showSubmit??!1,this.on("key",(t,r)=>{if(r?.name&&q0.has(r.name)){this.#n=!1,this.#o(r.name);return}if(t==="\t"&&this.#t){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#n=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}t&&(this.#t&&this.focused==="submit"&&(this.focused="editor"),this.#e(t??""),this._cursor++)}}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class qs extends mn{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,n=this.value!==void 0&&this.value.length===e.length;this.value=n?[]:e.map((t)=>t.value)}toggleInvert(){let e=this.value;if(!e)return;let n=this._enabledOptions.filter((t)=>!e.includes(t.value));this.value=n.map((t)=>t.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((n)=>n!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let n=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[n]?.disabled?Ln(n,1,this.options):n,this.on("key",(t,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(t)=>{switch(t){case"left":case"up":this.cursor=Ln(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ln(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var bf=class extends mn{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let n=this._selectedValue;this.value=n===void 0?void 0:n.value}constructor(n){super(n,!1),this.options=n.options;let t=this.options.findIndex(({value:i})=>i===n.initialValue),r=t===-1?0:t;this.cursor=this.options[r]?.disabled?Ln(r,1,this.options):r,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=Ln(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ln(this.cursor,1,this.options);break}this.changeValue()})}};class Zs extends mn{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let n=e.slice(0,this.cursor),t=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${n}${ro("inverse",t)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as k,stripVTControlCharacters as pS}from"node:util";import un from"node:process";var yf=ki(Js(),1);function Z0(){if(un.platform!=="win32")return un.env.TERM!=="linux";return Boolean(un.env.CI)||Boolean(un.env.WT_SESSION)||Boolean(un.env.TERMINUS_SUBLIME)||un.env.ConEmuTask==="{cmd::Cmder}"||un.env.TERM_PROGRAM==="Terminus-Sublime"||un.env.TERM_PROGRAM==="vscode"||un.env.TERM==="xterm-256color"||un.env.TERM==="alacritty"||un.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Y0=Z0();var we=(e,n)=>Y0?e:n,X0=we("◆","*"),V0=we("■","x"),z0=we("▲","x"),vf=we("◇","o"),B0=we("┌","T"),se=we("│","|"),An=we("└","—"),kS=we("┐","T"),ES=we("┘","—"),Ys=we("●",">"),so=we("○"," "),D0=we("◻","[•]"),$f=we("◼","[+]"),kf=we("◻","[ ]"),SS=we("▪","•"),Ef=we("─","-"),x0=we("╮","+"),ew=we("├","+"),nw=we("╯","+"),tw=we("╰","+"),yS=we("╭","+"),vS=we("●","•"),MS=we("◆","*"),IS=we("▲","!"),NS=we("■","x"),uo=(e)=>{switch(e){case"initial":case"active":return k("cyan",X0);case"cancel":return k("red",V0);case"error":return k("yellow",z0);case"submit":return k("green",vf)}},Mf=(e)=>{switch(e){case"initial":case"active":return k("cyan",se);case"cancel":return k("red",se);case"error":return k("yellow",se);case"submit":return k("green",se)}};function If(e,n){let t=[`${n?`${k("cyan",se)} `:""}${e.join(" • ")}`];return n&&t.push(k("cyan",An)),t}var Sf=(e,n,t,r,i,o=!1)=>{let s=n,u=0;if(o)for(let c=r-1;c>=t;c--){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}else for(let c=t;c<r;c++){let a=e[c];if(a&&(s-=a.length),u++,s<=i)break}return{lineCount:s,removals:u}},Xs=({cursor:e,options:n,style:t,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let u=io(r)-o,c=_s(r),a=k("dim","..."),h=Math.max(c-s,0),f=Math.max(Math.min(i,h),5),l=0;e>=f-3&&(l=Math.max(Math.min(e-f+3,n.length-f),0));let g=f<n.length&&l>0,m=f<n.length&&l+f<n.length,d=Math.min(l+f,n.length),$=[],y=0;g&&y++,m&&y++;let N=l+(g?1:0),E=d-(m?1:0);for(let p=N;p<E;p++){let H=n[p],S=H?t(H,p===e):"",R=zn(S,u,{hard:!0,trim:!1}).split(`
322
+ `);$.push(R),y+=R.length}if(y>h){let p=0,H=0,S=y,R=e-N,I=h,P=()=>Sf($,S,0,R,I),A=()=>Sf($,S,R+1,$.length,I,!0);g?({lineCount:S,removals:p}=P(),S>I&&(m||(I-=1),{lineCount:S,removals:H}=A())):(m||(I-=1),{lineCount:S,removals:H}=A(),S>I&&(I-=1,{lineCount:S,removals:p}=P())),p>0&&(g=!0,$.splice(0,p)),H>0&&(m=!0,$.splice($.length-H,H))}let v=[];g&&v.push(a);for(let p of $)for(let H of p)v.push(H);return m&&v.push(a),v};var Zt=(e)=>{let n=e.active??"Yes",t=e.inactive??"No";return new Qs({active:n,inactive:t,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??We.withGuide,i=`${uo(this.state)} `,o=r?`${k("gray",se)} `:"",s=Bn(e.output,e.message,o,i),u=`${r?`${k("gray",se)}
323
+ `:""}${s}
324
+ `,c=this.value?n:t;switch(this.state){case"submit":{let a=r?`${k("gray",se)} `:"";return`${u}${a}${k("dim",c)}`}case"cancel":{let a=r?`${k("gray",se)} `:"";return`${u}${a}${k(["strikethrough","dim"],c)}${r?`
325
+ ${k("gray",se)}`:""}`}default:{let a=r?`${k("cyan",se)} `:"",h=r?k("cyan",An):"";return`${u}${a}${this.value?`${k("green",Ys)} ${n}`:`${k("dim",so)} ${k("dim",n)}`}${e.vertical?r?`
326
+ ${k("cyan",se)} `:`
327
+ `:` ${k("dim","/")} `}${this.value?`${k("dim",so)} ${k("dim",t)}`:`${k("green",Ys)} ${t}`}
328
+ ${h}
329
+ `}}}}).prompt()};var rw=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Space:")} select`,`${k("dim","Enter:")} confirm`],ei=(e,n)=>e.split(`
330
+ `).map((t)=>n(t)).join(`
331
+ `),Nf=(e)=>{let n=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${k("gray",kf)} ${ei(s,(u)=>k(["strikethrough","gray"],u))}${i.hint?` ${k("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${k("cyan",D0)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${k("green",$f)} ${ei(s,(u)=>k("dim",u))}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${ei(s,(u)=>k(["strikethrough","dim"],u))}`:o==="active-selected"?`${k("green",$f)} ${s}${i.hint?` ${k("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${ei(s,(u)=>k("dim",u))}`:`${k("dim",kf)} ${ei(s,(u)=>k("dim",u))}`},t=e.required??!0,r=e.showInstructions??!0;return new qs({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:t,cursorAt:e.cursorAt,validate(i){if(t&&(i===void 0||i.length===0))return`Please select at least one option.
332
+ ${k("reset",k("dim",`Press ${k(["gray","bgWhite","inverse"]," space ")} to select, ${k("gray",k("bgWhite",k("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??We.withGuide,o=Bn(e.output,e.message,i?`${Mf(this.state)} `:"",`${uo(this.state)} `),s=`${i?`${k("gray",se)}
333
+ `:""}${o}
334
+ `,u=this.value??[],c=(a,h)=>{if(a.disabled)return n(a,"disabled");let f=u.includes(a.value);return h&&f?n(a,"active-selected"):f?n(a,"selected"):n(a,h?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>u.includes(f)).map((f)=>n(f,"submitted")).join(k("dim",", "))||k("dim","none"),h=Bn(e.output,a,i?`${k("gray",se)} `:"");return`${s}${h}`}case"cancel":{let a=this.options.filter(({value:f})=>u.includes(f)).map((f)=>n(f,"cancelled")).join(k("dim",", "));if(a.trim()==="")return`${s}${k("gray",se)}`;let h=Bn(e.output,a,i?`${k("gray",se)} `:"");return`${s}${h}${i?`
335
+ ${k("gray",se)}`:""}`}case"error":{let a=i?`${k("yellow",se)} `:"",h=this.error.split(`
336
+ `).map((g,m)=>m===0?`${i?`${k("yellow",An)} `:""}${k("yellow",g)}`:` ${g}`).join(`
337
+ `),f=s.split(`
338
+ `).length,l=h.split(`
339
+ `).length+1;return`${s}${a}${Xs({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+l,style:c}).join(`
340
+ ${a}`)}
341
+ ${h}
342
+ `}default:{let a=i?`${k("cyan",se)} `:"",h=s.split(`
343
+ `).length,f=r?If(rw,i):i?[k("cyan",An)]:[],l=f.join(`
344
+ `),g=f.length+1;return`${s}${a}${Xs({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:h+g,style:c}).join(`
345
+ ${a}`)}
346
+ ${l}
347
+ `}}}}).prompt()};var Yt=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??We.withGuide?`${k("gray",An)} `:"";t.write(`${r}${k("red",e)}
348
+
349
+ `)},co=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??We.withGuide?`${k("gray",B0)} `:"";t.write(`${r}${e}
350
+ `)},Vs=(e="",n)=>{let t=n?.output??process.stdout,r=n?.withGuide??We.withGuide?`${k("gray",se)}
351
+ ${k("gray",An)} `:"";t.write(`${r}${e}
352
+
353
+ `)};var iw=(e)=>e,ow=(e,n,t)=>{let r={hard:!0,trim:!1},i=zn(e,n,r).split(`
354
+ `),o=i.reduce((c,a)=>Math.max(Ye(a),c),0),s=i.map(t).reduce((c,a)=>Math.max(Ye(a),c),0),u=n-(s-o);return zn(e,u,r)},pt=(e="",n="",t)=>{let r=t?.output??un.stdout,i=t?.withGuide??We.withGuide,o=t?.format??iw,s=["",...ow(e,io(r)-6,o).split(`
355
+ `).map(o),""],u=Ye(n),c=Math.max(s.reduce((l,g)=>{let m=Ye(g);return m>l?m:l},0),u)+2,a=s.map((l)=>`${k("gray",se)} ${l}${" ".repeat(c-Ye(l))}${k("gray",se)}`).join(`
356
+ `),h=i?`${k("gray",se)}
357
+ `:"",f=i?ew:tw;r.write(`${h}${k("green",vf)} ${k("reset",n)} ${k("gray",Ef.repeat(Math.max(c-u-1,1))+x0)}
358
+ ${a}
359
+ ${k("gray",f+Ef.repeat(c+2)+nw)}
360
+ `)};var OS={light:we("─","-"),heavy:we("━","="),block:we("█","#")};var sw=[`${k("dim","↑/↓")} to navigate`,`${k("dim","Enter:")} confirm`],oo=(e,n)=>e.includes(`
361
+ `)?e.split(`
362
+ `).map((t)=>n(t)).join(`
363
+ `):n(e),Of=(e)=>{let n=(r,i)=>{if(r===void 0)return"";let o=r.label??String(r.value);switch(i){case"disabled":return`${k("gray",so)} ${oo(o,(s)=>k("gray",s))}${r.hint?` ${k("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${oo(o,(s)=>k("dim",s))}`;case"active":return`${k("green",Ys)} ${o}${r.hint?` ${k("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${oo(o,(s)=>k(["strikethrough","dim"],s))}`;default:return`${k("dim",so)} ${oo(o,(s)=>k("dim",s))}`}},t=e.showInstructions??!0;return new bf({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??We.withGuide,i=`${uo(this.state)} `,o=`${Mf(this.state)} `,s=Bn(e.output,e.message,o,i),u=`${r?`${k("gray",se)}
364
+ `:""}${s}
365
+ `;switch(this.state){case"submit":{let c=r?`${k("gray",se)} `:"",a=Bn(e.output,n(this.options[this.cursor],"selected"),c);return`${u}${a}`}case"cancel":{let c=r?`${k("gray",se)} `:"",a=Bn(e.output,n(this.options[this.cursor],"cancelled"),c);return`${u}${a}${r?`
366
+ ${k("gray",se)}`:""}`}default:{let c=r?`${k("cyan",se)} `:"",a=u.split(`
367
+ `).length,h=t?If(sw,r):r?[k("cyan",An)]:[],f=h.join(`
368
+ `),l=h.length+1;return`${u}${c}${Xs({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:a+l,style:(g,m)=>n(g,g.disabled?"disabled":m?"active":"inactive")}).join(`
369
+ ${c}`)}
370
+ ${f}
371
+ `}}}}).prompt()};var RS=`${k("gray",se)} `;var Rf=(e)=>new Zs({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let n=e?.withGuide??We.withGuide,t=`${`${n?`${k("gray",se)}
372
+ `:""}${uo(this.state)} `}${e.message}
373
+ `,r=e.placeholder&&e.placeholder.length>0?k("inverse",e.placeholder[0])+k("dim",e.placeholder.slice(1)):k(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${k("yellow",this.error)}`:"",u=n?`${k("yellow",se)} `:"",c=n?k("yellow",An):"";return`${t.trim()}
374
+ ${u}${i}
375
+ ${c}${s}
376
+ `}case"submit":{let s=o?` ${k("dim",o)}`:"",u=n?k("gray",se):"";return`${t}${u}${s}`}case"cancel":{let s=o?` ${k(["strikethrough","dim"],o)}`:"",u=n?k("gray",se):"";return`${t}${u}${s}${o.trim()?`
377
+ ${u}`:""}`}default:{let s=n?`${k("cyan",se)} `:"",u=n?k("cyan",An):"";return`${t}${s}${i}
378
+ ${u}
379
+ `}}}}).prompt();import{existsSync as lw,readFileSync as Af}from"node:fs";import{join as Tf}from"node:path";import{existsSync as uw,readdirSync as cw,readFileSync as aw}from"node:fs";import{basename as hw,join as ni}from"node:path";var Dn="tt1:",Ff=["background","foreground","cursor","selection",...Array.from({length:16},(e,n)=>`ansi${n}`)];function ho(e){return ni(e,"ttheme","palettes")}function wt(e,n){let t=Xe(n);if(!t)throw Error(`${n} is an official palette — your own are named <you>/<palette>`);return ni(ho(e),t,`${n.slice(t.length+1)}.toml`)}function fw(e,n){let t=new Map;for(let i of n)if(i.group!==Lr&&!t.has(i.group)){let o=n.find((s)=>s.group===i.group&&s.lead)?.name??"";t.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:o})}let r=new Map(n.filter((i)=>!i.default&&!Xe(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:t,bases:r,open:!0}}function xn(e,n,t){return Wi(`${e}.toml`,n,fw(e,t))}function fo(e,n,t=!0){let r=ho(e),i=(o)=>uw(o)?cw(o).sort():[];return i(r).flatMap((o)=>i(ni(r,o)).filter((s)=>s.endsWith(".toml")).flatMap((s)=>{let u=`${o}/${hw(s,".toml")}`;try{return[on(xn(u,aw(ni(r,o,s),"utf8"),n))]}catch(c){if(t)process.stderr.write(`ttheme: skipping ${ni(r,o,s)} — ${c.message}
380
+ `);return[]}}))}function ti(e,n=e.name,t){return{name:n,...e.base?{base:e.base}:{},...e.group!==Lr?{group:e.group}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},signature:e.signatureSlots,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived&&e.waived.length>0?{waive:e.waived,reason:t??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var He=(e)=>JSON.stringify(e);function Xt(e){let n=["[meta]",`name = ${He(e.name)}`,...e.base?[`base = ${He(e.base)}`]:[],...e.group?[`group = ${He(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${He(e.ansiSource)}`]:[],...e.booru?[`booru = ${He(e.booru)}`]:[],`signature = [${e.signature.map(He).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([t,r])=>`${t} = [${r.map(He).join(", ")}]`)]:[],"","[colors]",`background = ${He(e.background)}`,`foreground = ${He(e.foreground)}`,`cursor = ${He(e.cursor)}`,`selection_background = ${He(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((t)=>` ${He(t)},`),"",...e.ansi.slice(8).map((t)=>` ${He(t)},`),"]"];if(e.waive&&e.waive.length>0)n.push("","[contrast]",`waive = [${e.waive.map(He).join(", ")}]`,`reason = ${He(e.reason??"")}`);for(let t of e.pictures??[]){if(n.push("","[[picture]]",`site = ${He(t.site)}`,`id = ${t.id}`),t.size!==void 0)n.push(`size = ${typeof t.size==="number"?t.size:He(t.size)}`);if(t.position!==void 0)n.push(`position = ${He(t.position)}`);if(t.opacity!==void 0)n.push(`opacity = ${t.opacity}`)}return`${n.join(`
381
+ `)}
382
+ `}class Hf{bytes=[];u8(e){this.bytes.push(e&255)}u16(e){this.u8(e>>8),this.u8(e)}u32(e){this.u16(Math.floor(e/65536)),this.u16(e%65536)}str(e=""){let n=new TextEncoder().encode(e);if(n.length>255)throw Error(`"${e}" is too long to share`);this.u8(n.length),this.bytes.push(...n)}color(e){let n=Number.parseInt(e.slice(1),16);this.u8(n>>16),this.u8(n>>8),this.u8(n)}done(){return Buffer.from(this.bytes).toString("base64url")}}class Pf{at=0;bytes;constructor(e){this.bytes=e}u8(){let e=this.bytes[this.at++];if(e===void 0)throw Error("the share code is cut short");return e}u16(){return this.u8()*256+this.u8()}u32(){return this.u16()*65536+this.u16()}str(){let e=this.u8(),n=this.bytes.subarray(this.at,this.at+e);if(n.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(n)}color(){return`#${[this.u8(),this.u8(),this.u8()].map((e)=>e.toString(16).padStart(2,"0")).join("")}`}end(){if(this.at!==this.bytes.length)throw Error("the share code has bytes left over")}}function lo(e){let n=new Hf;n.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])n.color(r);for(let r of e.signature)n.u8(Ff.indexOf(r));n.str(e.base),n.str(e.group),n.str(e.ansiSource),n.str(e.booru),n.u16((e.waive??[]).reduce((r,i)=>r|1<<Yo.indexOf(i),0)),n.str(e.waive&&e.waive.length>0?e.reason:"");let t=e.pictures??[];n.u8(t.length);for(let r of t)n.u8(x.findIndex((i)=>i.key===r.site)),n.u32(r.id),n.u16(r.size===void 0?0:r.size==="fill"?1:r.size),n.u8(r.position===void 0?0:lt.indexOf(r.position)+1),n.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${Dn}${n.done()}`}function Lf(e){if(!e.startsWith(Dn))throw Error(`a share code starts with ${Dn}`);let n=e.slice(Dn.length);if(!/^[A-Za-z0-9_-]+$/.test(n))throw Error("the share code holds characters it never uses — was it copied whole?");let t=new Pf(new Uint8Array(Buffer.from(n,"base64url"))),r=t.str(),[i,o,s,u,...c]=Array.from({length:20},()=>t.color()),a=[t.u8(),t.u8(),t.u8()].map((N)=>Ff[N]??`slot${N}`),h=t.str(),f=t.str(),l=t.str(),g=t.str(),m=t.u16(),d=t.str(),$=Yo.filter((N,E)=>m&1<<E),y=Array.from({length:t.u8()},()=>{let N=x[t.u8()]?.key??"unknown",E=t.u32(),v=t.u16(),p=t.u8(),H=t.u16();return{site:N,id:E,...v===1?{size:"fill"}:v>1?{size:v}:{},...p>0?{position:lt[p-1]??"unknown"}:{},...H>0?{opacity:(H-1)/1000}:{}}});if(t.end(),![i,o,s,u,...c].every(Ft))throw Error("the share code holds a color that is not one");return{name:r,...h?{base:h}:{},...f?{group:f}:{},...l?{ansiSource:l}:{},...g?{booru:g}:{},signature:a,background:i,foreground:o,cursor:s,selection:u,ansi:c,...$.length>0?{waive:$,reason:d}:{},...y.length>0?{pictures:y}:{}}}function zs(e,n){let t=e.indexOf("ansi = ["),r=e.indexOf("]",t);if(t<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,o=e.slice(t,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>He(n.ansi[i++]));return(e.slice(0,t)+o+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${He(n.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(s,u)=>`${u}${He(n.selectionBackground)}`)}function go(e){let n=Lt(sn(e)),t=new Set(e.waived??[]),r=Math.max(...ot.map((i)=>i.label.length));return ot.map((i,o)=>{let s=n[o],u=t.has(i.rule)||Number.isNaN(s)||(i.min===void 0||s>=i.min)&&(i.max===void 0||s<=i.max),c=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",a=Number.isNaN(s)?"—":Number.isInteger(s)?String(s):s.toFixed(2);return` ${u?"✓":"✗"} ${i.label.padEnd(r)} ${a.padStart(6)} ${c}${t.has(i.rule)?" waived":""}`})}var Gf="https://kecan0406.github.io/ttheme/manifest.json",gw=20000;function mo(e){return Tf(e,"ttheme","catalog.json")}function po(e,n){Oe(mo(e),`${JSON.stringify(n,null,2)}
383
+ `)}function _e(e){let n=mo(e);if(!lw(n))throw Error(`no catalog at ${n} — run \`ttheme init\` first`);return Uf(Af(n,"utf8"))}function Uf(e){let n;try{n=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let t=n;if(typeof t?.version!=="string"||!Array.isArray(t.palettes))throw Error("catalog has no version or palettes");for(let r of t.palettes){let i=jf(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return t}function jf(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let n=Yn(e.name)??(e.base===void 0?void 0:Yn(e.base));if(n)return n;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((t)=>typeof t==="string"&&Ft(t)))return'holds a color that is not "#rrggbb"';for(let t of[e.group,e.native??"-",e.ansiSource]){let r=typeof t==="string"?ws(t):"has a field that is not text";if(r)return r}return}function Jf(e){return Tf(e,"ttheme","kept.json")}function Kf(e,n){Oe(Jf(e),`${JSON.stringify({palettes:n},null,2)}
384
+ `)}function Bs(e){try{let{palettes:n}=JSON.parse(Af(Jf(e),"utf8"));return Array.isArray(n)?n.filter((t)=>jf(t)===void 0):[]}catch{return[]}}function je(e,n,t=!0){let r=fo(e,n.palettes,t),i=n.palettes.map((s)=>r.find((u)=>u.name===s.name)??s);for(let s of r.filter((u)=>!i.includes(u))){let u=i.findLastIndex((a)=>s.base!==void 0&&(a.name===s.base||a.base===s.base)),c=u>=0?u:i.findLastIndex((a)=>a.group===s.group);i.splice(c<0?i.length:c+1,0,s)}let o=new Set(i.map((s)=>s.name));return{...n,palettes:[...i,...Bs(e).filter((s)=>!o.has(s.name))]}}function Vt(e){return je(e,_e(e))}async function Cf(e){let n;try{n=await fetch(e,{signal:AbortSignal.timeout(gw)})}catch(t){throw Error(`cannot reach the registry at ${e} — ${t instanceof Error?t.message:String(t)}`)}if(!n.ok)throw Error(`registry at ${e} answered ${n.status}`);return Uf(await n.text())}function bt(e){let n=new Set(e.waived??[]),t=e.gate??Lt(sn(e));return ot.flatMap((r,i)=>{let o=t[i];if(n.has(r.rule)||typeof o!=="number"||Number.isNaN(o))return[];if(r.min!==void 0&&o<r.min)return[`${r.label} ${o} < ${r.min}`];if(r.max!==void 0&&o>r.max)return[`${r.label} ${o} > ${r.max}`];return[]})}function $t(e,n){let t=e.find((r)=>r.name===n);if(!t)throw Error(`no palette named ${n} in the catalog — ${Ds(e,[n])}`);return t}function Ds(e,n){let t=n.map((s)=>s.toLowerCase()),r=e.filter((s)=>t.some((u)=>s.name.includes(u))),i=e.filter((s)=>!r.includes(s)&&t.some((u)=>s.group.toLowerCase().includes(u))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function Wf(e,n){let t=n.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(t)))}function _f(e,n,t){let r=t.toLowerCase(),i=(o)=>o.name===n.name?0:o.group===n.group?1:2;return e.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Qf(e,n){return e.booruSites?.[n]??(e.booru?[e.booru]:[])}var eu=5,dw=6,qf=0.05,mw=[1,2,3,4,5,6,9,10,11,12,13,14],Zf=(e,n)=>(n-e+360)%360<=180?1:-1;function xs(e,n,t){let r=n*Math.cos(t*Math.PI/180),i=n*Math.sin(t*Math.PI/180),o=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((h)=>h**3),[s,u,c]=o,a=[4.0767416621*s-3.3077115913*u+0.2309699292*c,-1.2684380046*s+2.6097574011*u-0.3413193965*c,-0.0041960863*s-0.7034186147*u+1.707614701*c];if(a.some((h)=>h<-0.0001||h>1.0001))return;return a.map((h)=>{let f=Math.min(1,Math.max(0,h));return Math.round(255*(f<=0.0031308?12.92*f:1.055*f**0.4166666666666667-0.055))})}function wo(e,n,t){let r=0,i=n;if(xs(e,n,t)===void 0)for(let s=0;s<24;s++){let u=(r+i)/2;if(xs(e,u,t)===void 0)i=u;else r=u}else r=n;return`#${(xs(e,r,t)??[0,0,0]).map((s)=>s.toString(16).padStart(2,"0")).join("")}`}function pw(e,n){let{l:t,c:r}=hn(e);return wo(t,r,(n+360)%360)}function ww(e,n,t){let{l:r,c:i,h:o}=hn(e),s=Qe(n)<0.18,u=(h)=>wo(s?r+(1-r)*h:r*(1-h),i,o);if(ze(u(1),n)<t+qf)return u(1);let c=0,a=1;for(let h=0;h<30;h++){let f=(c+a)/2;if(ze(u(f),n)>=t+qf)a=f;else c=f}return u(a)}function bw(e,n){let{l:t,c:r,h:i}=hn(e),o=0,s=t;for(let u=0;u<30;u++){let c=(o+s)/2;if(Qe(wo(c,r,i))<=n-0.005)o=c;else s=c}return wo(o,r,i)}function $w(e,n,t){let r=br[n],[i,o]=[hn(e[n]),hn(e[n+8])],s=(h,f)=>t.has(h)?[f]:Array.from({length:2*r.width+1},(l,g)=>(r.center-r.width+g+360)%360),u=(h,f,l)=>Ht.every((g)=>{let m=(h>8?8:0)+g;if(m===h)return!0;let d=hn(e[m]);return d.c<Zo||Jn(d.h,f)>=Mi+1||Math.abs(d.l-l)>=Ii}),c,a=Number.POSITIVE_INFINITY;for(let h of s(n,i.h)){if(!t.has(n)&&!u(n,h,i.l))continue;for(let f of s(n+8,o.h)){if(Jn(h,f)>it-eu||!t.has(n+8)&&!u(n+8,f,o.l))continue;let l=Jn(h,i.h)+Jn(f,o.h);if(l<a)a=l,c=[h,f]}}return c}class Yf{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,n,t){let r=this.get(e);if(t===r)return;if(this.moves.push({slot:e,rule:n,from:r,to:t}),e==="foreground")this.theme.foreground=t;else if(e==="selection")this.theme.selectionBackground=t;else this.theme.ansi[Number(e.slice(4))]=t}get(e){if(e==="foreground")return this.theme.foreground;if(e==="selection")return this.theme.selectionBackground;return this.theme.ansi[Number(e.slice(4))]}rehue(e,n,t){this.set(`ansi${e}`,n,pw(this.theme.ansi[e],t))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:t,hue:r}of Si(this.theme)){let i=br[Pt(t)];this.rehue(t,"ansi-role",i.center+Zf(i.center,r)*(i.width-eu))}for(let{normal:t,gap:r}of yi(this.theme)){if(r<=it)continue;let[i,o]=e.has(`ansi${t+8}`)?[t+8,t]:[t,t+8],s=hn(this.theme.ansi[i]).h,u=hn(this.theme.ansi[o]).h;this.rehue(o,"bright-follows",s+Zf(s,u)*(it-eu))}let n=Ni(this.theme);for(let[t,r]of vi(this.theme)){let i=Pt(n.has(r)?t:r),o=$w(this.theme.ansi,i,n);if(o===void 0)continue;this.rehue(i,"distinct",o[0]),this.rehue(i+8,"distinct",o[1])}}readability(){let e=new Set(this.theme.waive),{background:n}=this.theme,t=(r,i,o,s=n)=>{if(e.has(r))return;for(let u of i)if(ze(this.get(u),s)<o)this.set(u,r,ww(this.get(u),s,o))};if(t("foreground",["foreground"],7),t("accents",mw.map((r)=>`ansi${r}`),3),t("light-ansi",["ansi7","ansi15"],7),t("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Qe(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",bw(this.get("ansi0"),0.15));t("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let n=this.moves.filter((i)=>i.slot===e),t=n[0].from,r=this.get(e);return t===r?[]:[{slot:e,rule:[...new Set(n.map((i)=>i.rule))].join(", "),from:t,to:r}]})}}function nu(e){let n=new Yf(e);for(let t=0;t<dw;t++)if(n.readability(),n.roles(),At(n.theme).length===0)break;return{theme:n.theme,moves:n.net(),left:At(n.theme)}}import{execFileSync as kw,spawn as Ew}from"node:child_process";import{existsSync as pn,mkdirSync as Sw,readFileSync as zt,realpathSync as yw,rmSync as tu,utimesSync as vw,writeFileSync as Mw}from"node:fs";import{homedir as Bt}from"node:os";import{dirname as Iw,join as $e}from"node:path";var Nw={ghostty:jr,kitty:Kr,alacritty:Ur,wezterm:Br,iterm2:Jr,"windows-terminal":Dr,warp:zr},Xf="ttheme-default";function Gn(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let n=(t,r)=>kw(t,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?n("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(t)=>{if(process.platform==="darwin")n("defaults",["write",e,"Default Bookmark Guid","-string",t])},running:()=>{try{return n("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function wn(e){return e.off?void 0:Un(e)}function ri(e,n){if(!e.terminals.includes("iterm2"))return e;let t=n.read();return t&&!t.startsWith("ttheme-")?{...e,itermBase:t}:e}function St(e,n){if(!e.terminals.includes("iterm2"))return!1;let t=n.read(),r=wn(e)?Xf:t===Xf?e.itermBase:void 0;if(!r||r===t)return!1;return n.write(r),!0}function Re(){return process.env.XDG_CONFIG_HOME??$e(Bt(),".config")}function ii(e){return $e(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function bo(e){return $e(e,"ttheme","installed.json")}function Fe(e){let n=bo(e);if(!pn(n))throw Error(`nothing installed yet at ${n} — run \`ttheme init\` first`);let t=JSON.parse(zt(n,"utf8"));if(!Array.isArray(t?.palettes)||!Array.isArray(t.terminals))throw Error(`${n} has no palettes or terminals`);return{terminals:t.terminals.filter((r)=>Yi.includes(r)),...t.author?{author:t.author}:{},...t.startup?{startup:t.startup}:{},...t.off?{off:!0}:{},...t.itermBase?{itermBase:t.itermBase}:{},...t.wtHome?{wtHome:t.wtHome}:{},...t.wtProfile?{wtProfile:t.wtProfile}:{},palettes:t.palettes}}function yt(e,n){Oe(bo(e),`${JSON.stringify(n,null,2)}
385
+ `)}function Vf(e,n){let t=new Map(e.palettes.map((o)=>[o.name,o])),r=n.filter((o)=>!t.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — ${Ds(dt(e.palettes),r)}`);let i=n.flatMap((o)=>{let s=bt(t.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
386
+ ${i.join(`
387
+ `)}`);return e.palettes.filter((o)=>n.includes(o.name))}function zf(e,n){let t=e==="wezterm"?"colors":"themes";return(Nw[e].emit?.(n)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===t&&o!==void 0?[{file:o,content:r.content}]:[]})}function $o(e){return process.platform==="darwin"?$e(e,".warp","themes"):$e(process.env.XDG_DATA_HOME??$e(e,".local","share"),"warp-terminal","themes")}function kt(e,n,t){if(e==="warp")return $o(t);return $e(n,e,e==="wezterm"?"colors":"themes")}function ko(e,n){return process.platform==="darwin"?$e(e,".warp","settings.toml"):$e(n,"warp-terminal","settings.toml")}var ru='"dark"';function iu(e){return $e(e,"ttheme","warp.base")}var Ow="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function Rw(e,n,t,r){let i=ko(n,e);if(!pn(i))return;let o=iu(e),s=zt(i,"utf8"),u=Vi(s),c=u?.includes(`path = "${le("")}`)===!0,a;if(t){if(!c&&!pn(o))Sw(Iw(o),{recursive:!0}),Mw(o,u??"");a=Kh(t)}else{if(!c)return;a=pn(o)&&zt(o,"utf8")||ru,tu(o,{force:!0})}let h=zi(s,a);if(h===s)return;if(r)$s(i),Ew(process.execPath,["-e",Ow,yw(i),h,s],{detached:!0,stdio:"ignore"}).unref();else Cr(i,h);return i}function Bf(e){return $e(e,"ttheme","kitty.py")}function Dt(e,n){let t=$e(n,".wezterm.lua");return pn(t)?t:$e(e,"wezterm","wezterm.lua")}function Eo(e){return $e(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function ou(e){return[$e(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),$e(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),$e(e,"Microsoft","Windows Terminal","settings.json")].filter((n)=>pn(n))}function Fw(e){for(let n of e){let t=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(zt(n,"utf8"))?.[1];if(t)return t}return}function Un(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Et(e,n){return e==="ghostty"?$e(n,"ghostty","config"):$e(n,"kitty","kitty.conf")}function Df(e,n,t,r){return e==="ghostty"?Nh($e(n,"ttheme"),t,r):Lh(t,Bf(n),r)}function Tn(e){return pn(e)?zt(e,"utf8"):""}function vt(e){return $e(e,"alacritty","alacritty.toml")}function Hw(e,n){return n?$e(e,"alacritty","themes",`${le(n)}.toml`):void 0}function xf(e,n,t,r){let i=Ze(e),o=n.map(sn),s=new Map;for(let c of o){let a=mh(i,c.name,r);if(a)s.set(c.name,a)}let u=new Set(dt(n).map((c)=>c.name));return Ba(o.filter((c)=>u.has(c.name)),s,o.find((c)=>c.name===wn(t)),t.itermBase)}function et(e,n=Bt()){let t=Fe(e);if(!t.terminals.includes("iterm2"))return;Oe(ii(n),xf(e,Vf(Vt(e),t.palettes),t,n))}function bn(e,n,t,r=Bt()){Mn(Ze(e));let i=Vf(je(e,n),t.palettes);Kf(e,i);let o=[],s=(h,f)=>{if(o.push(h),pn(h)&&zt(h,"utf8")===f)return!1;return Oe(h,f),!0},u=(h,f)=>{o.push(h),Cr(h,f)},c=wn(t);for(let h of t.terminals){if(h==="iterm2"){s(ii(r),xf(e,i,t,r));continue}if(h==="windows-terminal"){if(t.wtHome){let d=ou(t.wtHome),$=i.map(sn),y=Ls($,t.wtProfile??Fw(d),c);if(s(Eo(t.wtHome),y)){let N=new Date;for(let E of d)vw(E,N,N)}}continue}let f=c!==void 0&&h==="warp"&&!pn($e($o(r),`ttheme-${c}.yaml`)),l=h==="warp"?Rw(e,r,c,f):void 0;for(let d of i)for(let{file:$,content:y}of zf(h,sn(d)))s($e(kt(h,e,r),$),y);if(h==="warp"){if(l)o.push(l);continue}if(h==="wezterm"){let d=$e(e,"ttheme","wezterm.lua");s(d,_h({path:d,colors:kt("wezterm",e,r),backgrounds:Ze(e),...c?{startup:c}:{},palettes:i.map(sn)}));let $=Dt(e,r),y=Vr(Tn($),Th(d));if(y!==void 0)u($,y);continue}if(h==="alacritty"){let d=vt(e),$=Xr(Tn(d),Hw(e,c));if($!==void 0)u(d,$);continue}if(h==="kitty")s(Bf(e),Da({themes:kt("kitty",e,r),backgrounds:Ze(e)}));let g=Et(h,e),m=Tn(g);u(g,qr(m,Df(h,e,c,m)))}let a=$e(e,"ttheme","palettes.zsh");return Oe(a,Hs(i,c,t.terminals)),o.push(a),tu(`${a}.zwc`,{force:!0}),o}function el(e,n){return e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Pw(e){return[...new Set(e.split(`
388
+ `).map((n)=>n.split(/[ =]/)[0]))].join(", ")}function nl(e,n,t=Bt()){let r=wn(n),i=(s)=>el(s,t),o=[];for(let s of n.terminals){if(s==="iterm2"){o.push(`write ${i(ii(t))} — a "ttheme · <palette>" profile per palette`);continue}if(s==="windows-terminal"){if(n.wtHome)o.push(`write ${Eo(n.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(o.push(`write ${i(kt(s,e,t))}/${le("*")} — a theme file per palette`),s==="warp"){let a=ko(t,e);if(r&&pn(a))o.push(`edit ${i(a)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(s==="wezterm"){let a=Dt(e,t);if(Vr(Tn(a),"")!==void 0)o.push(`edit ${i(a)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(s==="alacritty"){let a=vt(e);if(Xr(Tn(a),void 0)!==void 0)o.push(`edit ${i(a)} — a ttheme block: general.import`);continue}let u=Et(s,e),c=Tn(u);o.push(`edit ${i(u)} — a ttheme block: ${Pw(Df(s,e,r,c))}`)}return o}function tl(e,n,t=Bt()){let r=[],i=(o)=>el(o,t);if(n.includes("ghostty")){let o=Et("ghostty",e);if(mt(Tn(o),"command"))r.push(`${i(o)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(n.includes("kitty")){let o=Tn(Et("kitty",e));if(mt(o,"window_logo_scale")||mt(o,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(n.includes("alacritty")){let o=vt(e);if(Ah(Tn(o)))r.push(`${i(o)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function su(e,n,t,r,i=Bt()){let o=[],s=je(e,n,!1).palettes;for(let u of t)for(let c of s.filter((a)=>r.includes(a.name)))for(let{file:a}of zf(u,sn(c))){let h=$e(kt(u,e,i),a);if(pn(h))tu(h,{force:!0}),o.push(h)}return o}function nt(e,n,t,r){let i=Gn(),o=Boolean(wn(t))!==Boolean(wn(r)),s=o?ri(r,i):r;return bn(e,n,s),yt(e,s),o&&St(s,i)&&i.running()}import{existsSync as il,mkdirSync as ol,readFileSync as sl,writeFileSync as Zw}from"node:fs";import{homedir as Yw}from"node:os";import{dirname as ul,join as cl}from"node:path";import{spawn as Lw}from"node:child_process";var Aw=30000,Tw=3,Gw=97,Uw=`ObjC.import('Vision')
389
+ ObjC.import('CoreImage')
390
+ ObjC.import('CoreGraphics')
391
+ function run(argv) {
392
+ const error = Ref()
393
+ const image = $.CIImage.imageWithContentsOfURL($.NSURL.fileURLWithPath(argv[0]))
394
+ if (!image) throw new Error('unreadable image')
395
+ const handler = $.VNImageRequestHandler.alloc.initWithCIImageOptions(image, $({}))
396
+ const request = $.VNGenerateForegroundInstanceMaskRequest.alloc.init
397
+ if (!handler.performRequestsError($([request]), error)) throw new Error('vision failed')
398
+ if (request.results.count === 0) throw new Error('no foreground')
399
+ const found = request.results.objectAtIndex(0)
400
+ const buffer = found.generateMaskedImageOfInstancesFromRequestHandlerCroppedToInstancesExtentError(
401
+ found.allInstances, handler, false, error)
402
+ if (!buffer) throw new Error('mask failed')
403
+ const written = $.CIContext.context.writePNGRepresentationOfImageToURLFormatColorSpaceOptionsError(
404
+ $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
405
+ $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
406
+ if (!written) throw new Error('write failed')
407
+ }`;function oi(){return process.platform==="darwin"}function So(e){return e>=Tw&&e<=Gw}function yo(e,n,t){return new Promise((r,i)=>{let o=Lw("osascript",["-l","JavaScript","-e",Uw,e,n],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([t,AbortSignal.timeout(Aw)])}),s="";o.stderr.on("data",(u)=>{s+=u}),o.on("error",i),o.on("close",(u)=>{if(u===0){r();return}i(Error(s.trim().split(`
408
+ `).at(-1)||`osascript exited ${u}`))})})}import{spawn as jw}from"node:child_process";import{connect as Jw,createServer as Kw}from"node:net";var Cw=20,rl=22;function uu(e){let n=new Uint8Array(e.reduce((r,i)=>r+i.length,0)),t=0;for(let r of e)n.set(r,t),t+=r.length;return n}function Ww(e,n=Cw){let t=e.subarray(5);if(e[0]!==rl||t.length<2)return[e];let r=Math.max(1,Math.min(n,t.length-1)),i=(o)=>uu([Uint8Array.from([e[0],e[1],e[2],o.length>>8,o.length&255]),o]);return[i(t.subarray(0,r)),i(t.subarray(r))]}function _w(e,n,t,r){let i=Jw(t,n,()=>{i.setNoDelay(!0),e.write(`HTTP/1.1 200 Connection Established\r
409
+ \r
410
+ `);let o=r,s=!1,u=(c)=>{if(s){i.write(c);return}if(o=uu([o,c]),o.length<5)return;let a=o[3]*256+o[4];if(o[0]!==rl){s=!0,i.write(o);return}if(o.length<5+a)return;s=!0;let[h,f]=Ww(o.subarray(0,5+a));i.write(h),setTimeout(()=>{if(f)i.write(f);i.write(o.subarray(5+a))},10)};if(e.on("data",u),o.length>0){let c=o;o=new Uint8Array(0),u(c)}i.pipe(e)});i.on("error",()=>e.destroy()),i.on("close",()=>e.destroy()),e.on("error",()=>i.destroy()),e.on("close",()=>i.destroy())}function Qw(e){e.setNoDelay(!0);let n=new Uint8Array(0),t=(r)=>{n=uu([n,r]);let i=Buffer.from(n).toString("latin1"),o=i.indexOf(`\r
411
+ \r
412
+ `);if(o===-1)return;e.off("data",t);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){e.end(`HTTP/1.1 405 Method Not Allowed\r
413
+ \r
414
+ `);return}_w(e,s[1],Number(s[2]),n.subarray(o+4))};e.on("data",t),e.on("error",()=>e.destroy())}function qw(){let e=Kw(Qw);return new Promise((n,t)=>{e.once("error",t),e.listen(0,"127.0.0.1",()=>{n({port:e.address().port,close:()=>{e.close(),e.unref()}})})})}function si(){if(process.versions.bun)return!0;let[e=0,n=0]=process.versions.node.split(".").map(Number);return e>22||e===22&&n>=21}async function ui(){if(!si())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
415
+ `),1;let e=await qw(),n=jw(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:${e.port}`,NO_PROXY:[process.env.NO_PROXY,Fa()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(e.port)}}),t=await new Promise((r)=>n.on("exit",(i)=>r(i??1)));return e.close(),t}function ci(){return process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY}var Xw=90000;function cu(e,n){let t=Ze(e),r=Ns(e,n).flatMap((i)=>{let[,o,s]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return o&&s&&x.some((u)=>u.key===o)?[{site:o,id:Number(s),...$h(t,i)}]:[]});return r.length>0?r:void 0}function Vw(e,n){let t=new Set(Mn(Ze(e)).palettes[n.name]?.pictures.map((r)=>r.key));return(n.pictures??[]).filter((r)=>!t.has(gt(r)))}function vo(e,n){let t=new Set((n??[]).map((r)=>gt(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!t.has(gt(r)))}}function zw(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}async function Bw(e,n,t,r,i){let o=x.find((g)=>g.key===t.site);if(!o)throw Error(`no site called ${t.site}`);let s=await Hr(o,t.id,i);if(!s)throw Error("the post is gone");if(!ji(o,s,jt(process.env.TTHEME_FIND_RATING))||Ui(s,Jt(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let u=ht(s);if(!u)throw Error("too large to use");let c=cl(gn(o),"orig",`${t.id}.${u.ext}`),a;if(il(c))a=new Uint8Array(sl(c));else a=await Ki(o,u.file,i),ol(ul(c),{recursive:!0}),Zw(c,a);let h=vr(a,Sn);if(_n(h)===0&&oi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let g=cl(gn(o),"cut",`${t.id}.png`);try{if(!il(g))ol(ul(g),{recursive:!0}),await yo(c,g,i);let m=vr(new Uint8Array(sl(g)),Sn);if(So(_n(m)))h=m}catch{}}let f=zw(n);qi(e,f,Qt(f,n.signatureSlots),h,{site:o.key,id:t.id,ext:u.ext,bytes:a,from:`${o.name} ${t.id} ${o.pageUrl(t.id)}`},{width:0,height:0});let l=Ns(e,n.name).find((g)=>g.key===gt(t));if(l)kh(Ze(e),l,t,r,Yw())}async function Dw(e,n,t,r){let i=0;for(let s of Vw(e,n)){let u=`${n.name} · ${x.find((c)=>c.key===s.site)?.name??s.site} ${s.id}`;try{await Bw(e,n,s,t,AbortSignal.timeout(Xw)),r(` ▣ ${u}`),i++}catch(c){r(` ▢ ${u} — ${c instanceof Error?c.message:String(c)}`)}}let[o]=n.pictures??[];if(i>0&&o)bh(e,n.name,gt(o));return i}async function Mt(e,n,t){let r=0;for(let i of n)r+=await Dw(e,i,!t.includes("iterm2"),(o)=>console.log(o));if(r>0)et(e)}var fl=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function au(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function rb(){try{let e=xw("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return fl.test(e)?e:void 0}catch{return}}async function ll(e,n){if(n.author)return n.author;let t=rb();if(!t){if(!au())throw Error("your palettes are named after your GitHub handle — log in with `gh auth login`, or run this in a terminal");let r=await Rf({message:"your GitHub handle — your palettes are named <handle>/<palette>",validate:(i)=>fl.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(dn(r))throw Error("no handle given");t=r.toLowerCase()}return yt(e,{...n,author:t}),console.log(`your palettes are named ${t}/<palette>`),t}function hu(e,n){return e.includes("/")||!n.author?e:`${n.author}/${e}`}function ib(e,n,t){let r=Fe(e),i=t.filter((o)=>!r.palettes.includes(o));if(i.length>0)nt(e,n,r,{...r,palettes:[...r.palettes,...i]});else if(t.some((o)=>r.palettes.includes(o)))bn(e,n,r);return{state:r,fresh:i}}function gl(e){let n=Math.max(0,...e.map((t)=>t.slot.length));return e.map((t)=>` ${t.slot.padEnd(n)} ${t.from} → ${t.to} ${t.rule}`)}function dl(e,n,t){let r=Lf(n),i=Xt(r),o=xn(r.name,i,t.palettes),s=bt(on(o));if(s.length>0)throw Error(`${r.name} fails the contrast gate: ${s.join(", ")}`);let u=wt(e,r.name);if(er(u)&&xt(u,"utf8")!==i)throw Error(`${r.name} is already at ${u} and differs — move it away to take this one`);if(al(hl(u),{recursive:!0}),Oe(u,i),t.palettes.some((c)=>c.name===r.name))console.log(` ${r.name} from the code stands in for the catalog's`);return r.name}async function ml(e,n){let t=Re(),r=_e(t),i=Fe(t),o=await ll(t,i),s=e.includes("/")?e:`${o}/${e}`,u=Yn(s);if(u)throw Error(`${s} ${u}`);if(Xe(s)!==o)throw Error(`your palettes are named ${o}/<palette> — ${s} is someone else's`);let c=wt(t,s);if(er(c))throw Error(`${s} already exists — \`ttheme edit ${s}\` changes it`);let a=je(t,r),h=n??Un(i);if(!h)throw Error("--from names the palette to start from");let f=$t(a.palettes,h),l=Xe(f.name)?f.base:f.default?void 0:f.name,{base:g,ansiSource:m,...d}=ti(f,s,`kept from ${f.name}`),$=cu(t,f.name)??f.pictures,y=Xt({...d,...l?{base:l}:{},...$?{pictures:$}:{}});xn(s,y,r.palettes),al(hl(c),{recursive:!0}),Oe(c,y);let{state:N}=ib(t,r,[s]);console.log(` + ${s} from ${f.name}
416
+ ${c}`),await Mt(t,je(t,r).palettes.filter((E)=>E.name===s),N.terminals),console.log(`
417
+ \`ttheme edit ${s}\` changes its colors · \`ttheme use ${s}\` wears it`)}function ob(e){let n=process.env.VISUAL||process.env.EDITOR||"vi",t=nb("sh",["-c",`${n} "$1"`,"sh",e],{stdio:"inherit"});if(t.status!==0)throw Error(`${n} exited ${t.status??t.signal}`)}function sb(e,n,t){let r;try{r=xn(e,n,t.palettes)}catch(c){return{problem:c.message}}let i=bt(on(r));if(i.length===0)return{};let{theme:o,moves:s,left:u}=nu(r);return{problem:[`it fails the contrast gate: ${i.join(", ")}`,...gl(s)].join(`
418
+ `),...u.length===0&&s.length>0?{fixed:zs(n,o)}:{}}}async function pl(e){let n=Re(),t=_e(n),r=Fe(n),i=hu(e,r),o=wt(n,i);if(!er(o)){let c=je(n,t,!1).palettes.some((a)=>a.name===i);throw Error(c?`${i} is not one of yours — \`ttheme new <name> --from ${i}\` makes your own copy`:`no palette of yours called ${i} — \`ttheme new\` makes one`)}if(!au())throw Error("edit opens your editor — run it in a terminal");let s=xt(o,"utf8");for(;;){ob(o);let c=xt(o,"utf8");if(c===s){console.log("nothing changed");return}let{problem:a,fixed:h}=sb(i,c,t);if(!a)break;console.log(`
419
+ ${a}
420
+ `);let f=await Of({message:`${i} cannot be worn like this`,options:[...h?[{value:"fix",label:"take the colors above"}]:[],{value:"again",label:"edit it again"},{value:"back",label:"put the old one back"}]});if(dn(f)||f==="back"){tb(o,s),console.log("put the old one back");return}if(f==="fix"&&h){Oe(o,h);break}}if(r.palettes.includes(i))bn(n,t,r);console.log(`saved ${i}${r.palettes.includes(i)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${i}\` installs it`}`);let u=je(n,t).palettes.find((c)=>c.name===i);if(u&&r.palettes.includes(i))await Mt(n,[vo(u,xn(i,s,t.palettes).pictures)],r.terminals)}function wl(e,n,t){return $t(e.palettes,e.palettes.some((r)=>r.name===n)?n:hu(n,t))}function bl(e,n=!1){let t=Re(),r=_e(t),i=Fe(t),o=wl(je(t,r),e,i);if(console.log(`${o.name} · ${o.group}
421
+ `),console.log(go(o).join(`
422
+ `)),bt(o).length===0)return console.log(`
423
+ passes the gate`),0;let{theme:u,moves:c,left:a}=nu(sn(o));if(c.length===0)return console.log(`
424
+ no color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
425
+ ${a.length===0?"these colors pass":"these colors come closer"}:
426
+ ${gl(c).join(`
427
+ `)}`);let h=Xe(o.name)?wt(t,o.name):void 0;if(!h||!er(h))return console.log(`
428
+ \`ttheme new <name> --from ${o.name}\` makes a copy you can fix`),1;if(!n)return console.log(`
429
+ \`ttheme check --fix ${o.name}\` writes them`),1;if(Oe(h,zs(xt(h,"utf8"),u)),i.palettes.includes(o.name))bn(t,r,i);return console.log(`
430
+ wrote ${h}`),a.length===0?0:1}function $l(e,n){let t=Xe(n.name)?wt(e,n.name):void 0,r=t&&er(t)?xn(n.name,xt(t,"utf8"),[n]).waiveReason:void 0,i=cu(e,n.name)??n.pictures,{pictures:o,...s}=ti(n,n.name,r);return{...s,...i?{pictures:i}:{}}}function kl(e){let n=Re(),t=Fe(n),r=lo($l(n,wl(je(n,_e(n)),e,t)));if(console.log(r),process.stdout.isTTY)console.error(`
431
+ anyone with ttheme wears it with: ttheme add ${Dn}…`)}function ub(e){let n=process.platform==="darwin"?"open":process.env.WSL_DISTRO_NAME?"wslview":"xdg-open";try{eb(n,[e],{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}async function El(e){let n=Re(),t=_e(n),r=Fe(n),i=await ll(n,r),o=hu(e,{...r,author:i}),s=wt(n,o);if(!er(s))throw Error(`no palette of yours called ${o} — \`ttheme new\` makes one`);if(Xe(o)!==i)throw Error(`${o} is ${Xe(o)}'s — only its author submits it`);let u=xn(o,xt(s,"utf8"),t.palettes);if(bt(on(u)).length>0)throw Error(`${o} fails the contrast gate — \`ttheme check --fix ${o}\` first`);let a=Xt($l(n,on(u))),h=t.palettes.some((l)=>l.name===o),f=`${Ke.bugs}/new?${new URLSearchParams({template:"palette.yml",title:`palette: ${o}`,palette:a})}`;if(console.log(`${h?"updates":"adds"} ${o} in the catalog — a GitHub issue carries it, and a bot turns it into a pull request`),console.log(`
432
+ ${f}
433
+ `),au())ub(f)}import{spawn as u$}from"node:child_process";import{createHash as pg}from"node:crypto";import{existsSync as tr,mkdirSync as li,mkdtempSync as c$,readFileSync as wg,rmSync as yu,statSync as a$,writeFileSync as gi}from"node:fs";import{tmpdir as h$}from"node:os";import{dirname as Ao,join as Rn}from"node:path";import{pathToFileURL as f$}from"node:url";import{execFile as cb}from"node:child_process";import{createHash as Ml}from"node:crypto";import{existsSync as ab,mkdtempSync as hb,readFileSync as Oo,rmSync as fb,statSync as Il,writeFileSync as Nl}from"node:fs";import{homedir as lb,tmpdir as gb}from"node:os";import{join as Mo}from"node:path";import{fileURLToPath as db}from"node:url";import{promisify as mb}from"node:util";var In=mb(cb),Io=67108864,pb=4096,gu=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],wb=["text/uri-list","text/plain;charset=utf-8","text/plain"],fu=[...gu,"text/uri-list","text/plain"];function bb(e){try{return Il(e).isFile()}catch{return!1}}function $b(e){let n=[],t="",r="",i=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r==="'")if(s==="'")r="";else t+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(e[o+1]??""))t+=e[++o];else t+=s;else if(s==="\\"&&o+1<e.length)t+=e[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)n.push(t);t="",i=!1}else t+=s,i=!0}if(i)n.push(t);return n}function Sl(e){if(/^file:\/\//i.test(e))try{return db(e)}catch{return}if(e.startsWith("~/"))return Mo(lb(),e.slice(2));return e.startsWith("/")?e:void 0}function Ro(e,n=bb){let t=[];for(let r of e.replace(/\r\n?/g,`
62
434
  `).split(`
63
- `)){let i=fh(r.trim());if(i&&e(i)){n.push(i);continue}for(let o of gm(r)){if(/^https?:\/\/\S+$/i.test(o)){n.push(o);continue}let s=fh(o);if(s&&e(s))n.push(s)}}return n}function dm(t){if(t[0]!==255||t[1]!==216)return null;let e=2;while(e+9<t.length){if(t[e]!==255){e++;continue}let n=t[e+1];if(n===255){e++;continue}let r=t[e+2]<<8|t[e+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:t[e+5]<<8|t[e+6],width:t[e+7]<<8|t[e+8]};e+=2+r}return null}function lh(t){let e=Tn(t)?An(t):dm(t);if(!e)return;return{ext:Tn(t)?"png":"jpg",width:e.width,height:e.height}}async function Xr(t,e){let n=lh(t);if(n&&n.width*n.height<=Ae)return{bytes:t,...n,source:e};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${Ae/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=im(_r(cm(),"ttheme-attach-"));try{let i=_r(r,"in"),o=_r(r,"out.png");ph(i,t);let s=!n||n.width*n.height>Ae?["--resampleHeightWidthMax",String(am)]:[];await ce("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let c=new Uint8Array(Vr(o)),u=lh(c);if(!u)throw Error("that is not a picture macOS can read");return{bytes:c,...u,source:e}}finally{om(r,{recursive:!0,force:!0})}}async function uo(t,e){if(/^https?:\/\//i.test(t)){let n=await fetch(t,{headers:{"User-Agent":Vi},signal:e});if(!n.ok)throw Error(`${new URL(t).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Cr)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return Xr(r,t)}if(mh(t).size>Cr)throw Error("that picture is over 64 MB");return Xr(new Uint8Array(Vr(t)),t)}var wh=new Map,zr={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>wh.get(t)??"",parse:()=>[],count:()=>0};function bh(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function $h(t,e){wh.set(t,e)}function kh(t){return Number.parseInt(dh("sha1").update(t).digest("hex").slice(0,8),16)%me}var mm=`ObjC.import('AppKit')
435
+ `)){let i=Sl(r.trim());if(i&&n(i)){t.push(i);continue}for(let o of $b(r)){if(/^https?:\/\/\S+$/i.test(o)){t.push(o);continue}let s=Sl(o);if(s&&n(s))t.push(s)}}return t}function kb(e){if(e[0]!==255||e[1]!==216)return null;let n=2;while(n+9<e.length){if(e[n]!==255){n++;continue}let t=e[n+1];if(t===255){n++;continue}let r=e[n+2]<<8|e[n+3];if(t>=192&&t<=207&&t!==196&&t!==200&&t!==204)return{height:e[n+5]<<8|e[n+6],width:e[n+7]<<8|e[n+8]};n+=2+r}return null}function yl(e){let n=yr(e)?Mr(e):kb(e);if(!n)return;return{ext:yr(e)?"png":"jpg",width:n.width,height:n.height}}async function No(e,n){let t=yl(e);if(t&&t.width*t.height<=Sn)return{bytes:e,...t,source:n};if(process.platform!=="darwin")throw Error(t?`${t.width}×${t.height} is over ${Sn/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=hb(Mo(gb(),"ttheme-attach-"));try{let i=Mo(r,"in"),o=Mo(r,"out.png");Nl(i,e);let s=!t||t.width*t.height>Sn?["--resampleHeightWidthMax",String(pb)]:[];await In("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let u=new Uint8Array(Oo(o)),c=yl(u);if(!c)throw Error("that is not a picture macOS can read");return{bytes:u,...c,source:n}}finally{fb(r,{recursive:!0,force:!0})}}async function du(e,n){if(/^https?:\/\//i.test(e)){let t=await fetch(e,{headers:{"User-Agent":gs},signal:n});if(!t.ok)throw Error(`${new URL(e).host} answered ${t.status}`);if(Number(t.headers.get("content-length")??0)>Io)throw Error("that picture is over 64 MB");let r=new Uint8Array(await t.arrayBuffer());if(/^text\/html/i.test(t.headers.get("content-type")??""))throw Error(`${new URL(e).host} sent a web page, not a picture — copy the image address instead`);return No(r,e)}if(Il(e).size>Io)throw Error("that picture is over 64 MB");return No(new Uint8Array(Oo(e)),e)}var Ol=new Map,Fo={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Ol.get(e)??"",parse:()=>[],count:()=>0};function Rl(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Fl(e,n){Ol.set(e,n)}function Hl(e){return Number.parseInt(Ml("sha1").update(e).digest("hex").slice(0,8),16)%Hn}var Eb=`ObjC.import('AppKit')
64
436
  function run(argv) {
65
437
  const pb = $.NSPasteboard.generalPasteboard
66
438
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -85,16 +457,16 @@ function run(argv) {
85
457
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
86
458
  const text = pb.stringForType('public.utf8-plain-text')
87
459
  return text && !text.isNil() ? text.js : ''
88
- }`,pm=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
460
+ }`,Sb=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
89
461
  $c = [Windows.Forms.Clipboard]
90
462
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
91
463
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
92
464
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
93
465
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
94
- $c::GetText()`;function Eh(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Vr("/proc/version","utf8"))}catch{return!1}}async function wm(t){let e=Boolean(process.env.WAYLAND_DISPLAY),n=e?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await ce(n[0],n[1])).stdout.split(`
95
- `).map((s)=>s.trim()),i=(s)=>e?ce("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:Cr}):ce("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:Cr});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=co.find((s)=>r.includes(s));if(o)return ph(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function ho(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function yh(t){if(process.platform==="darwin"){let e=(await ce("osascript",["-l","JavaScript","-e",mm,t])).stdout.trim();return e===t?{image:t}:{text:e}}if(Eh()){let e=(await ce("powershell.exe",["-NoProfile","-STA","-Command",pm])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(e.split(`
96
- `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await ce("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
97
- `)}}if(process.platform==="linux")return wm(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var bm=`ObjC.import('AppKit')
466
+ $c::GetText()`;function Pl(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Oo("/proc/version","utf8"))}catch{return!1}}async function yb(e){let n=Boolean(process.env.WAYLAND_DISPLAY),t=n?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await In(t[0],t[1])).stdout.split(`
467
+ `).map((s)=>s.trim()),i=(s)=>n?In("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:Io}):In("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:Io});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=gu.find((s)=>r.includes(s));if(o)return Nl(e,(await i(o)).stdout),{image:e};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function mu(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Ll(e){if(process.platform==="darwin"){let n=(await In("osascript",["-l","JavaScript","-e",Eb,e])).stdout.trim();return n===e?{image:e}:{text:n}}if(Pl()){let n=(await In("powershell.exe",["-NoProfile","-STA","-Command",Sb])).stdout.replace(/\r/g,"").trim(),t=await Promise.all(n.split(`
468
+ `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await In("wslpath",["-u",r])).stdout.trim():r));return t.length===1&&/ttheme-clipboard\.png$/.test(t[0]??"")?{image:t[0]}:{text:t.join(`
469
+ `)}}if(process.platform==="linux")return yb(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var vb=`ObjC.import('AppKit')
98
470
  function run() {
99
471
  const pb = $.NSPasteboard.generalPasteboard
100
472
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -106,119 +478,36 @@ function run() {
106
478
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
107
479
  }
108
480
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
109
- }`;async function Mh(){if(ho())return;if(process.platform==="darwin"){let[t="",e=""]=(await ce("osascript",["-l","JavaScript","-e",bm])).stdout.trim().split("\t");return{stamp:t,picture:e==="picture"}}if(process.platform==="linux"&&!Eh()){let e=Boolean(process.env.WAYLAND_DISPLAY)?(await ce("wl-paste",["--list-types"])).stdout:(await ce("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:e,picture:/^image\//m.test(e)}}return}function vh(t){let e=[],n="",r=0;while(r<t.length){if(t[r]!=="\x1B"){n+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:e,keys:n,pending:t.slice(r)};e.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((f)=>f!==-1);if(o.length===0)return{events:e,keys:n,pending:t.slice(r)};let s=Math.min(...o),c=t.slice(r+2,s),[u="",h="",...a]=c.split(";");e.push({kind:"osc",code:u,meta:$m(h),payload:a.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")e.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");e.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:e,keys:n,pending:t.slice(r)};n+=t[r],r++}return{events:e,keys:n,pending:""}}function $m(t){let e={};for(let n of t.split(":")){let r=n.indexOf("=");if(r>0)e[n.slice(0,r)]=n.slice(r+1)}return e}var rr=(t)=>Buffer.from(t).toString("base64"),so=(t)=>Buffer.from(t,"base64");function gh(t,e){return e.find((n)=>t.includes(n))}class ao{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=rr(dh("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,e){this.send=t,this.deliver=e}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${oo.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${rr("ttheme")}:pw=${this.pw};${rr(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,e){if(t.type!=="read")return;let n=t.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=t.mime?so(t.mime).toString("utf8"):r.mime,e)r.chunks.push(so(e));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=gh(o,[...co,...fm]);if(!s){this.deliver({kind:"text",text:""});return}let c=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:c,listing:!1},this.send(`\x1B]5522;type=read:name=${rr(u)}:pw=${c};${rr(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,e){let n=t.t??"";if(n==="m"){if(t.x==="-1"){this.offered=[];return}if(e){this.offered=e.split(" ").filter(Boolean);let c=oo.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${c.length>0?1:0};${c.join(" ")}\x1B\\`)}return}if(n==="M"){let c=e?e.split(" ").filter(Boolean):this.offered,u=gh(c,oo);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:c,index:c.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${e.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(e)r.chunks.push(so(e));if(t.m==="1"||e)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let c=i.toString("utf8"),u=o==="text/uri-list"?Yr(c).find((h)=>rm(h)):void 0;s=u?{kind:"bytes",bytes:new Uint8Array(Vr(u)),source:u}:{kind:"text",text:c}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{existsSync as km,readFileSync as Em}from"node:fs";import{join as ym}from"node:path";var Sh="https://kecan0406.github.io/ttheme/manifest.json",Mm=20000;function Br(t){return ym(t,"ttheme","catalog.json")}function Dr(t,e){Tt(Br(t),`${JSON.stringify(e,null,2)}
110
- `)}function Ut(t){let e=Br(t);if(!km(e))throw Error(`no catalog at ${e} — run \`ttheme init\` first`);return Ih(Em(e,"utf8"))}function Ih(t){let e;try{e=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let n=e;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes)if(typeof r?.name!=="string"||!Array.isArray(r.ansi)||r.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(r?.name)} is missing name or its 16 ANSI colors`);return n}async function Fh(t){let e;try{e=await fetch(t,{signal:AbortSignal.timeout(Mm)})}catch(n){throw Error(`cannot reach the registry at ${t} — ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw Error(`registry at ${t} answered ${e.status}`);return Ih(await e.text())}function Nh(t){let e=new Set(t.waived??[]);return Ir.flatMap((n,r)=>{let i=t.gate?.[r];if(e.has(n.rule)||typeof i!=="number")return[];if(n.min!==void 0&&i<n.min)return[`${n.label} ${i} < ${n.min}`];if(n.max!==void 0&&i>n.max)return[`${n.label} ${i} > ${n.max}`];return[]})}function ti(t,e){let n=t.find((r)=>r.name===e);if(!n)throw Error(`no palette named ${e} in the catalog — ${fo(t,[e])}`);return n}function fo(t,e){let n=e.map((s)=>s.toLowerCase()),r=t.filter((s)=>n.some((c)=>s.name.includes(c))),i=t.filter((s)=>!r.includes(s)&&n.some((c)=>s.group.toLowerCase().includes(c))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function Rh(t,e){let n=e.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function Oh(t,e,n){let r=n.toLowerCase(),i=(o)=>o.name===e.name?0:o.group===e.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Hh(t,e){return t.booruSites?.[e]??(t.booru?[t.booru]:[])}import{spawn as vm}from"node:child_process";var Sm=30000,Im=3,Fm=97,Nm=`ObjC.import('Vision')
111
- ObjC.import('CoreImage')
112
- ObjC.import('CoreGraphics')
113
- function run(argv) {
114
- const error = Ref()
115
- const image = $.CIImage.imageWithContentsOfURL($.NSURL.fileURLWithPath(argv[0]))
116
- if (!image) throw new Error('unreadable image')
117
- const handler = $.VNImageRequestHandler.alloc.initWithCIImageOptions(image, $({}))
118
- const request = $.VNGenerateForegroundInstanceMaskRequest.alloc.init
119
- if (!handler.performRequestsError($([request]), error)) throw new Error('vision failed')
120
- if (request.results.count === 0) throw new Error('no foreground')
121
- const found = request.results.objectAtIndex(0)
122
- const buffer = found.generateMaskedImageOfInstancesFromRequestHandlerCroppedToInstancesExtentError(
123
- found.allInstances, handler, false, error)
124
- if (!buffer) throw new Error('mask failed')
125
- const written = $.CIContext.context.writePNGRepresentationOfImageToURLFormatColorSpaceOptionsError(
126
- $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
127
- $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
128
- if (!written) throw new Error('write failed')
129
- }`;function lo(){return process.platform==="darwin"}function jh(t){return t>=Im&&t<=Fm}function Ph(t,e,n){return new Promise((r,i)=>{let o=vm("osascript",["-l","JavaScript","-e",Nm,t,e],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Sm)])}),s="";o.stderr.on("data",(c)=>{s+=c}),o.on("error",i),o.on("close",(c)=>{if(c===0){r();return}i(Error(s.trim().split(`
130
- `).at(-1)||`osascript exited ${c}`))})})}var Jt={pitch:25,cols:22,rows:9,height:13},Je={cols:25,rows:16},Rm=2147483648,Om=-1073741826,Hm=1600,jm="\x1B[0m",he="\x1B[1m",ht="\x1B[2m",ir="\x1B[31m",ue="\x1B[32m",Qt="\x1B[33m",ei="\x1B[1;34m",Pm="\x1B[35m",Gm={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn",I:"focus-in",O:"focus-out"};function Th(t){let e=[],n=0;while(n<t.length){let r=t[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(n+1));if(i){e.push(Gm[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let o=t[n+1]??"";if(/^[a-z]$/.test(o)){e.push(`alt-${o}`),n+=2;continue}e.push("esc"),n++;continue}e.push(r==="\r"||r===`
131
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return e}var Ah="\x1B]1337;ReportCellSize\x07\x1B[16t",Gh="\x1B]1337;ReportCellSize=";function po(t){let e=t.indexOf(Gh);if(e!==-1){let i=t.slice(e+Gh.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,e)+i.slice(s+(i[s]==="\x07"?1:2))}}}let n=t.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,n)+t.slice(n+1+r[0].length)}}function rn(t,e){return{perRow:Math.max(1,Math.floor((t+1)/Jt.pitch)),rowsVis:Math.max(1,Math.floor((e-4)/Jt.height))}}function Uh(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function Kh(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function Jh(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Wh(t){return`\x1B[38;2;${jt(t).join(";")}m`}function go(t){return`\x1B[48;2;${jt(t).join(";")}m`}function Vt(t){return Array.from(t).length}class ni{parts=[];cols;constructor(t){this.cols=t}put(t,e,n=""){return this.parts.push({col:t,text:e,sgr:n}),t+Vt(e)}run(t,e){let n=t;for(let[r,i]of e)n=this.put(n,r,i);return n}right(t,e){this.run(t-e.reduce((n,[r])=>n+Vt(r),0),e)}render(){let t="";for(let{col:e,text:n,sgr:r}of this.parts){if(e>=this.cols||e<0)continue;let i=Array.from(n).slice(0,this.cols-e).join("");t+=`\x1B[${e+1}G${r}${i}${r?jm:""}`}return t}}function xh(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Lm(t,e){if(!e)return xh(t);return e>=1e6?`${(t/1e6).toFixed(1)}/${(e/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(e/1000)} KB`}function Qh(t){return t.replace(/_\([^)]*\)?$/,"")}function Zh(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Hm?Qt:ht]}function or(t,e,n,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let a=[...o?[Vt(o[0])]:[],...i.map(([l,p])=>Vt(l)+1+Vt(p))];return(r.badge?Vt(r.badge)+4:0)+a.reduce((l,p)=>l+p,0)+3*Math.max(0,a.length-1)+(s?3+Vt(s[0])+1+Vt(s[1]):0)};while(c()>e)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&&c()>e){let a=Math.max(0,Vt(o[0])-(c()-e)-1);o=[`${Array.from(o[0]).slice(0,a).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...o?[[o]]:[],...i.map(([a,f])=>[[a,he],[` ${f}`,ht]])].forEach((a,f)=>{u=t.run(u+(f?3:0),a)}),s)t.right(e,[[s[0],he],[` ${s[1]}`,ht]])}function Tm(t,e,n,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let a=n;for(let b=0;b<8;b++)a=(t[e]?.put(a,"▀".repeat(h),Wh(s[b]??u)+go(s[b+8]??u))??a)+1;let f=["❯ ",ue],l=[[["~/code/demo",ei],[" on ",ht],["main",Pm],[" +2",ue],[" ~1",Qt]]];if(l.push([f,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",ue],["...",""],["origin/main",ir],[" [ahead 1]",Qt]]);if(l.push([[" M",ir],[" src/main.rs",""]]),l.push([["??",ir],[" notes.md",""]]),l.push([]),r>=44)l.push([f,["ls",""]]),l.push([["docs",ei],[" ",""],["src",ei],[" ",""],["tests",ei],[" Cargo.toml README.md",""]]),l.push([]);l.push([f,["cargo test",""]]),l.push([[" ✓",ue],[" parses config",""]]);let p=[[" ✗",ir],[" renders frame",""]];if(r>=44)p.push([" expected ",ht],["3",ue],[", received ",ht],["2",ir]);l.push(p),l.push([]),l.push([f,["echo ",""],["selected text",go(c)],[" ",""],[" ",go(u)]]),l.forEach((b,g)=>{let $=e+2+g;if($<=i)t[$]?.run(n,b)})}function Am(t,e,n,r,i,o){t[e]?.put(n,`╭${"─".repeat(i-2)}╮`,o);for(let s=e+1;s<e+r-1;s++)t[s]?.put(n,"│",o),t[s]?.put(n+i-1,"│",o);t[e+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,o)}function mo(t,e=t.site,n=t.siteAnsi){return[` ${e} `,`\x1B[7;${30+n}m`]}function Um(t){return`${gt[Math.floor(t/me)]?.name??"local"} ${t%me}`}function Km(t,e,n){let r=[{name:"all",moved:!1},...gt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===n.site?mo(n,u):[` ${u} `,ht];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Vt(c),0)<=e,o=t.run(0,i?r:[mo(n)]);if(n.asking!==void 0)t.run(o,[[` ${n.asking} was cut off — this network may block it. turn on the unblock proxy? `,Qt],["y",he],[" turn on ",ht],["n",he],[" not now",ht]])}function Jm(t,e,n,r){if(n.editing!==void 0){let c=t.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),u=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,n.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,ht);return}let i=t.run(0,[["⌕ ",r],[n.tag||"nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":ht]]),o=Te.filter((c)=>!n.block.includes(c)),s=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...n.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ht),n.total>0||!n.searching){let c=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)c.push([` of ${n.total}`,ht]);t.right(e,c)}}function Wm(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,ue]];if(t.cut==="off")return[["opaque · x cuts out",Qt]];if(t.cut==="failed")return[["opaque · no cut-out",Qt]];return[t.clear>0?[`${t.clear}% transparent`,ue]:["opaque",Qt]]}function Lh(t){return t.site==="all"?"any site":t.site}function qh(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${Um(t.installing)}`,Qt];if(t.hint)return[t.hint,ue];if(t.error)return[t.error,Qt];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Qt];if(t.fetching)return[`fetching ${t.fetching.id%me} · ${Lm(t.fetching.got,t.fetching.size)}`,Qt];if(t.cutting!==void 0)return[`cutting out ${t.cutting%me}`,Qt];if(t.preparing!==void 0)return[`preparing ${t.preparing%me}`,Qt];if(t.saved)return[t.saved,ue];if(t.note)return[t.note,ht];return}function xm(t,e,n,r,i,o){let{perRow:s,rowsVis:c}=rn(n,r);Jm(t[0],n,i,o),Km(t[1],n,i);for(let p=0;p<s*c;p++){let b=i.top*s+p,g=i.tiles[b];if(!g)break;let $=2+Math.floor(p/s)*Jt.height,y=p%s*Jt.pitch,F=b===i.focus;if(F)Am(t,$,y,Jt.height,Jt.pitch-1,o);if(g.thumb)e.push({id:g.key,path:g.thumb,row:$+1,col:y+1,cols:Jt.cols,rows:Jt.rows,z:-1});if(t[$+10]?.run(y+1,[...i.installed.includes(g.key)?[["✓ ",ue]]:[],...i.site==="all"?[["● ",`\x1B[${30+g.siteAnsi}m`]]:[],[String(g.id),F?he:""],[" ",""],Zh(g)]),g.mates.length>0)t[$+10]?.put(y+Jt.cols,"≈",o);let E=g.artist?Qh(g.artist):g.owner&&`@${g.owner}`;if(E)t[$+11]?.put(y+1,E.slice(0,Jt.cols-8),ht);let v=[];if(g.score>0)v.push([`★${g.score}`,ht]);if(g.variants>1)v.push([` ×${g.variants}`,o]);if(v.length>0)t[$+11]?.right(y+Jt.cols+1,v)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,a=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(a.length>0)t[r-2]?.put(0,a.join(" "),ht);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Lh(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Lh(i)} — tab tries ${i.nextSite}`,ht);let f=t[r-1],l=qh(i);if(i.searching&&i.tiles.length===0&&!l){or(f,n,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ht],right:["esc","back"]});return}or(f,n,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Qm(t,e,n,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[mo(i,s.site,s.siteAnsi),[" ",""],[String(s.id),he],[" ",""],Zh(s)];if(s.artist)u.push([` · ${Qh(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ht]);if(c)u.push([` · ${xh(c.bytes)}`,ht]);if(s.owner)u.push([` · ${s.owner}`,ht]);if(s.origin)u.push([` · ${s.origin}`,ht]);if(c)u.push([" ",""],...Wm(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(n,[["≈ ",o],[s.mates.join(" "),ht]]);if(Tm(t,3,2,n-4,r-2,i),i.shown)e.push({id:Rm+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:Om});let h=qh(i);or(t[r-1],n,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 Zm={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${gt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["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"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function qm(t,e,n,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),c=Math.max(...r.settings.map((l)=>l.choices.reduce((p,b)=>p+b.length+(l.multi?6:3),0))),u=Math.min(e-2,Math.max(28,s+c+8)),h=r.settings.length+4,a=Math.floor((e-u)/2),f=Math.max(2,Math.floor((n-h)/2));t[f]?.put(a,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let l=f+1;l<f+h-1;l++)t[l]?.put(a,`│${" ".repeat(u-2)}│`);r.settings.forEach((l,p)=>{let b=t[f+2+p];b.put(a+3,l.label,p===o?he:ht);let g=a+5+s,$=l.value.split(" ");l.choices.forEach((y,F)=>{let E=$.includes(y),v=l.multi&&p===o&&F===l.cursor?"4;":"",d=l.multi?` ${E?"[x]":"[ ]"} ${y} `:` ${y} `;g=b.put(g,d,E?`\x1B[${v}7;${30+r.siteAnsi}m`:v?`\x1B[4m${ht}`:ht)+1})}),t[f+h-1]?.put(a,`╰${"─".repeat(u-2)}╯`),or(t[n-1],e,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function _m(t,e,n,r,i){let o=Zm[r.mode],s=Math.min(e-2,50),c=o.length+4,u=Math.floor((e-s)/2),h=Math.max(2,Math.floor((n-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let a=h+1;a<h+c-1;a++)t[a]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([a,f],l)=>{t[h+2+l]?.put(u+3,a,he),t[h+2+l]?.put(u+13,f.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),or(t[n-1],e,i,{badge:"KEYS",right:["? esc","close"]})}function Cm(t,e,n){let r=e.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Vt(c.value))),s=Math.max(7,...i.map(Vt));r.forEach((c,u)=>{let h=u===e.pick,a=t[1+u];a?.run(0,[[h?"▸ ":" ",n],[c.value,h?he+n:""]]),a?.right(2+o+2+s,[[i[u],ht]])})}function _h(t,e,n){let r=Array.from({length:n},()=>new ni(e)),i=[],o=Wh(t.colors.cursor);if(e<Je.cols||n<Je.rows)return r[0]?.put(0,"ttheme find",he+o),r[1]?.put(0,`needs ${Je.cols}×${Je.rows} — now ${e}×${n}`),r[2]?.put(0,"esc quits",ht),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")Qm(r,i,e,n,t,o);else xm(r,i,e,n,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<n-1;s++)r[s]=new ni(e);return Cm(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<n;c++)r[c]=new ni(e);if(t.help)_m(r,e,n,t,o);else qm(r,e,n,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Xm=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Vm=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),Ym=0.04,zm=0.1,Bm=0.05,Dm=4096;function tp(t){return new Set(t.cutouts.split(/\s+/).map((e)=>e.replace(/^~/,"")).filter(Boolean))}function ep(t,e,n,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...tp(i)].some((a)=>s.has(a)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(e.w/e.h):1;return(o.solo?2:0)+([...Xm].some((a)=>s.has(a))?-3:0)+([...Vm].some((a)=>s.has(a))?-1.5:0)+2*Math.min(1,u/e.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(n>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(n):0)+2*r}function ri(t,e,n=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:ep(i,e,r.get(i.site)??0,n.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Xh(t){let e=new Map;for(let r of t)e.set(r.site,[...e.get(r.site)??[],r]);let n=[];for(let r=0;n.length<t.length;r++)for(let i of e.values()){let o=i[r];if(o)n.push(o)}return n}function wo(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function Ch(t,e,n){let[r,i,o]=[wo(t),wo(e),wo(n)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function Vh(t,e){let n=e.map((s)=>Ch(...jt(s))).filter(([,s,c])=>Math.hypot(s,c)>=Ym);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/Dm))),i=n.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,a,f]=Ch(t.data[u],t.data[u+1],t.data[u+2]);n.forEach(([l,p,b],g)=>{if(Math.hypot(h-l,a-p,f-b)<zm)i[g]=i[g]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/Bm),0)/n.length}import{execFileSync as np,spawn as rp}from"node:child_process";import{existsSync as te,mkdirSync as ip,readFileSync as on,realpathSync as op,rmSync as bo,utimesSync as sp,writeFileSync as cp}from"node:fs";import{homedir as sn}from"node:os";import{dirname as up,join as pt}from"node:path";var hp={ghostty:Hn,kitty:Pn,alacritty:On,wezterm:tr,iterm2:jn,"windows-terminal":er,warp:Dn},Yh="ttheme-default";function Ne(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let e=(n,r)=>np(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?e("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")e("defaults",["write",t,"Default Bookmark Guid","-string",n])},running:()=>{try{return e("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function ee(t){return t.off?void 0:un(t)}function cr(t,e){if(!t.terminals.includes("iterm2"))return t;let n=e.read();return n&&!n.startsWith("ttheme-")?{...t,itermBase:n}:t}function Qe(t,e){if(!t.terminals.includes("iterm2"))return!1;let n=e.read(),r=ee(t)?Yh:n===Yh?t.itermBase:void 0;if(!r||r===n)return!1;return e.write(r),!0}function Pt(){return process.env.XDG_CONFIG_HOME??pt(sn(),".config")}function ur(t){return pt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function zh(t){return pt(t,"ttheme","installed.json")}function Wt(t){let e=zh(t);if(!te(e))throw Error(`nothing installed yet at ${e} — run \`ttheme init\` first`);let n=JSON.parse(on(e,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${e} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>Jr.includes(r)),...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},palettes:n.palettes}}function hr(t,e){Tt(zh(t),`${JSON.stringify(e,null,2)}
132
- `)}function sr(t){return{name:t.name,group:t.group,...t.native?{native:t.native}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,ghostty:{iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[]}}function Bh(t,e){let n=new Map(t.palettes.map((o)=>[o.name,o])),r=e.filter((o)=>!n.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — ${fo(Ge(t.palettes),r)}`);let i=e.flatMap((o)=>{let s=Nh(n.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
133
- ${i.join(`
134
- `)}`);return t.palettes.filter((o)=>e.includes(o.name))}function Dh(t,e){let n=t==="wezterm"?"colors":"themes";return(hp[t].emit?.(e)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===n&&o!==void 0?[{file:o,content:r.content}]:[]})}function ii(t){return process.platform==="darwin"?pt(t,".warp","themes"):pt(process.env.XDG_DATA_HOME??pt(t,".local","share"),"warp-terminal","themes")}function We(t,e,n){if(t==="warp")return ii(n);return pt(e,t,t==="wezterm"?"colors":"themes")}function oi(t,e){return process.platform==="darwin"?pt(t,".warp","settings.toml"):pt(e,"warp-terminal","settings.toml")}var $o='"dark"';function ko(t){return pt(t,"ttheme","warp.base")}var ap="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function fp(t,e,n,r){let i=oi(e,t);if(!te(i))return;let o=ko(t),s=on(i,"utf8"),c=xr(s),u=c?.includes(`path = "${ut("")}`)===!0,h;if(n){if(!u&&!te(o))ip(up(o),{recursive:!0}),cp(o,c??"");h=rh(n)}else{if(!u)return;h=te(o)&&on(o,"utf8")||$o,bo(o,{force:!0})}let a=Qr(s,h);if(a===s)return;if(r)Ii(i),rp(process.execPath,["-e",ap,op(i),a,s],{detached:!0,stdio:"ignore"}).unref();else Gn(i,a);return i}function ta(t){return pt(t,"ttheme","kitty.py")}function cn(t,e){let n=pt(e,".wezterm.lua");return te(n)?n:pt(t,"wezterm","wezterm.lua")}function si(t){return pt(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Eo(t){return[pt(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),pt(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),pt(t,"Microsoft","Windows Terminal","settings.json")].filter((e)=>te(e))}function lp(t){for(let e of t){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(on(e,"utf8"))?.[1];if(n)return n}return}function un(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function xe(t,e){return t==="ghostty"?pt(e,"ghostty","config"):pt(e,"kitty","kitty.conf")}function ea(t,e,n,r){return t==="ghostty"?Zu(pt(e,"ttheme"),n,r):Yu(n,ta(e),r)}function we(t){return te(t)?on(t,"utf8"):""}function Ze(t){return pt(t,"alacritty","alacritty.toml")}function gp(t,e){return e?pt(t,"alacritty","themes",`${ut(e)}.toml`):void 0}function na(t,e,n,r){let i=de(t),o=e.map(sr),s=new Map;for(let u of o){let h=iu(i,u.name,r);if(h)s.set(u.name,h)}let c=new Set(Ge(e).map((u)=>u.name));return Gs(o.filter((u)=>c.has(u.name)),s,o.find((u)=>u.name===ee(n)),n.itermBase)}function hn(t,e=sn()){let n=Wt(t);if(!n.terminals.includes("iterm2"))return;let r=Ut(t);Tt(ur(e),na(t,Bh(r,n.palettes),n,e))}function ar(t,e,n,r=sn()){en(de(t));let i=Bh(e,n.palettes),o=[],s=(a,f)=>{if(o.push(a),te(a)&&on(a,"utf8")===f)return!1;return Tt(a,f),!0},c=(a,f)=>{o.push(a),Gn(a,f)},u=ee(n);for(let a of n.terminals){if(a==="iterm2"){s(ur(r),na(t,i,n,r));continue}if(a==="windows-terminal"){if(n.wtHome){let g=Eo(n.wtHome),$=i.map(sr),y=ro($,n.wtProfile??lp(g),u);if(s(si(n.wtHome),y)){let F=new Date;for(let E of g)sp(E,F,F)}}continue}let f=u!==void 0&&a==="warp"&&!te(pt(ii(r),`ttheme-${u}.yaml`)),l=a==="warp"?fp(t,r,u,f):void 0;for(let g of i)for(let{file:$,content:y}of Dh(a,sr(g)))s(pt(We(a,t,r),$),y);if(a==="warp"){if(l)o.push(l);continue}if(a==="wezterm"){let g=pt(t,"ttheme","wezterm.lua");s(g,sh({path:g,colors:We("wezterm",t,r),backgrounds:de(t),...u?{startup:u}:{},palettes:i.map(sr)}));let $=cn(t,r),y=Bn(we($),Bu(g));if(y!==void 0)c($,y);continue}if(a==="alacritty"){let g=Ze(t),$=zn(we(g),gp(t,u));if($!==void 0)c(g,$);continue}if(a==="kitty")s(ta(t),Ls({themes:We("kitty",t,r),backgrounds:de(t)}));let p=xe(a,t),b=we(p);c(p,Xn(b,ea(a,t,u,b)))}let h=pt(t,"ttheme","palettes.zsh");return Tt(h,eo(i,u,n.terminals)),o.push(h),bo(`${h}.zwc`,{force:!0}),o}function ra(t,e){return t.startsWith(`${e}/`)?`~${t.slice(e.length)}`:t}function dp(t){return[...new Set(t.split(`
135
- `).map((e)=>e.split(/[ =]/)[0]))].join(", ")}function ia(t,e,n=sn()){let r=ee(e),i=(s)=>ra(s,n),o=[];for(let s of e.terminals){if(s==="iterm2"){o.push(`write ${i(ur(n))} — a "ttheme · <palette>" profile per palette`);continue}if(s==="windows-terminal"){if(e.wtHome)o.push(`write ${si(e.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(o.push(`write ${i(We(s,t,n))}/${ut("*")} — a theme file per palette`),s==="warp"){let h=oi(n,t);if(r&&te(h))o.push(`edit ${i(h)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(s==="wezterm"){let h=cn(t,n);if(Bn(we(h),"")!==void 0)o.push(`edit ${i(h)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(s==="alacritty"){let h=Ze(t);if(zn(we(h),void 0)!==void 0)o.push(`edit ${i(h)} — a ttheme block: general.import`);continue}let c=xe(s,t),u=we(c);o.push(`edit ${i(c)} — a ttheme block: ${dp(ea(s,t,r,u))}`)}return o}function oa(t,e,n=sn()){let r=[],i=(o)=>ra(o,n);if(e.includes("ghostty")){let o=xe("ghostty",t);if(Ke(we(o),"command"))r.push(`${i(o)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(e.includes("kitty")){let o=we(xe("kitty",t));if(Ke(o,"window_logo_scale")||Ke(o,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(e.includes("alacritty")){let o=Ze(t);if(zu(we(o)))r.push(`${i(o)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function yo(t,e,n,r,i=sn()){let o=[];for(let s of n)for(let c of e.palettes.filter((u)=>r.includes(u.name)))for(let{file:u}of Dh(s,sr(c))){let h=pt(We(s,t,i),u);if(te(h))bo(h,{force:!0}),o.push(h)}return o}import{mkdirSync as aa,readFileSync as fa,writeFileSync as la}from"node:fs";import{dirname as ga}from"node:path";import{isMainThread as bp,parentPort as da,Worker as $p}from"node:worker_threads";var mp=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,pp=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Mo(t){let e=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...e&&t.source.includes("pximg")?[`pixiv:${e[1]}_p${e[2]}`]:[]]}function sa(t,e){let n=mp.exec(e.source)?.[1]?.toLowerCase();return[`post:${t.key}:${e.id}`,...e.md5?[`md5:${e.md5}`]:[],...n&&n!==e.md5?[`md5:${n}`]:[],...pp.flatMap(([r,i])=>{let o=r.exec(e.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...e.family?[`family:${t.key}:${e.family}`]:[]]}function ca(t,e){let n=t.owner||t.artist;return n!==""&&n===(e.owner||e.artist)&&t.width===e.width&&t.height===e.height}function ua(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),c=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let u=0;u<9;u++){let h=Math.floor(u*t.width/9),a=Math.max(h+1,Math.floor((u+1)*t.width/9)),f=0;for(let l=s;l<c;l++)for(let p=h;p<a;p++){let b=(l*t.width+p)*4,g=t.data[b+3]/255,$=0.299*t.data[b]+0.587*t.data[b+1]+0.114*t.data[b+2];f+=$*g+255*(1-g)}r.push(f/((a-h)*(c-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function wp(t,e){let n=BigInt(`0x${t}`)^BigInt(`0x${e}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function ha(t,e){if(t.width<=0||t.height<=0||e.width<=0||e.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(e.width/e.height)))<0.01&&wp(t.hash,e.hash)<=2}var kp={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Ep(t){let e=xc(new Uint8Array(fa(t.from)),Ae);if(t.job==="backdrop")return cu(t.home,t.colors,t.tone,e,{...t.origin,bytes:new Uint8Array(fa(t.source))},t),0;if(t.job==="match")return{match:Vh(e,t.colors),hash:ua(e)};if(t.job==="thumb")return aa(ga(t.to),{recursive:!0}),la(t.to,De(Zc(e,t.width,t.height))),0;let n=Un(e);return aa(ga(t.to),{recursive:!0}),la(t.to,De(nu(e,t.colors,t.tone,t.width,t.height))),n}function yp(t){t.on("message",(e)=>{try{t.postMessage({id:e.id,value:Ep(e)})}catch(n){t.postMessage({id:e.id,error:n instanceof Error?n.message:String(n)})}})}class ma{worker;next=1;waiting=new Map;send(t){let e=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(e,{ok:n,no:r}),i.ref(),i.postMessage({...t,id:e})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new $p(import.meta.filename);t.unref(),t.on("message",({id:n,value:r,error:i})=>{let o=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let e=(n)=>{if(this.worker===t)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return t.on("error",e),t.on("exit",()=>e(void 0)),this.worker=t,t}drop(t){for(let e of this.waiting.values())e.no(t);this.waiting.clear()}}class vo{lines=new Map;run(t){let e=kp[t.job],n=this.lines.get(e);if(!n)n=new ma,this.lines.set(e,n);return n.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}if(!bp&&da)yp(da);import{connect as Mp,createServer as vp}from"node:net";var Sp=20,pa=22;function So(t){let e=new Uint8Array(t.reduce((r,i)=>r+i.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Ip(t,e=Sp){let n=t.subarray(5);if(t[0]!==pa||n.length<2)return[t];let r=Math.max(1,Math.min(e,n.length-1)),i=(o)=>So([Uint8Array.from([t[0],t[1],t[2],o.length>>8,o.length&255]),o]);return[i(n.subarray(0,r)),i(n.subarray(r))]}function Fp(t,e,n,r){let i=Mp(n,e,()=>{i.setNoDelay(!0),t.write(`HTTP/1.1 200 Connection Established\r
136
- \r
137
- `);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=So([o,u]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==pa){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[a,f]=Ip(o.subarray(0,5+h));i.write(a),setTimeout(()=>{if(f)i.write(f);i.write(o.subarray(5+h))},10)};if(t.on("data",c),o.length>0){let u=o;o=new Uint8Array(0),c(u)}i.pipe(t)});i.on("error",()=>t.destroy()),i.on("close",()=>t.destroy()),t.on("error",()=>i.destroy()),t.on("close",()=>i.destroy())}function Np(t){t.setNoDelay(!0);let e=new Uint8Array(0),n=(r)=>{e=So([e,r]);let i=Buffer.from(e).toString("latin1"),o=i.indexOf(`\r
138
- \r
139
- `);if(o===-1)return;t.off("data",n);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){t.end(`HTTP/1.1 405 Method Not Allowed\r
140
- \r
141
- `);return}Fp(t,s[1],Number(s[2]),e.subarray(o+4))};t.on("data",n),t.on("error",()=>t.destroy())}function wa(){let t=vp(Np);return new Promise((e,n)=>{t.once("error",n),t.listen(0,"127.0.0.1",()=>{e({port:t.address().port,close:()=>{t.close(),t.unref()}})})})}var fn=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Wn,multi:{read:Lr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Te,multi:{read:Tr,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"]},...lo()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Pp(t,e){if(t.multi)return t.multi.read(e).join(" ")||t.multi.none;return t.choices.find((n)=>n===e)??t.choices[0]}var Gp=["fit","newest","score"];function ba(t){return Gp.find((e)=>e===t)??"fit"}function Lp(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var $a=12,Tp=4,Ap=150,ka=12,Up=2,Kp=150,Jp=30,Wp=4000,xp=8000,Ea=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,Qp=process.platform==="win32"?"alt+v":"ctrl+v",ya=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",Zp=1280,Ma=2,qp=3,_p=8;function ui(t,e){return{key:t,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:e}}function ln(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return ln(t.errors[0]);if(t.cause)return ln(t.cause);let e=t.code;if(typeof e==="string")return e;let n=(t.message||t.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function Fo(t,e){return`${t}: ${ln(e)}`}function va(t){return t.width*t.height}function Sa(t){return`${t.id}-${Na("sha1").update(t.preview).digest("hex").slice(0,8)}`}function Cp(t){let e=t.lastIndexOf("\x1B");return e!==-1&&/^\[?[0-9;]*$/.test(t.slice(e+1))}function No(t,e){try{return JSON.parse(Ra(ae(Ie(t),e),"utf8"))}catch{return{}}}function Ro(t,e,n){fr(Ie(t),{recursive:!0}),lr(ae(Ie(t),e),`${JSON.stringify(n)}
142
- `)}class Oa{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(fn.map((t)=>[t.name,Pp(t,process.env[t.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 vo;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new ao((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Rp(ae(Hp(),"ttheme-find-"));home;catalog;entry;constructor(t,e,n,r){this.home=t,this.catalog=e,this.entry=n,this.tone=jr(n,n.signatureSlots),this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:ba(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Lr(this.setting("TTHEME_FIND_RATING")),block:Tr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:fn.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:n.cursor,selection:n.selection,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=ui(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:gt[this.tab-1]}get sites(){return this.site?[this.site]:gt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Tp}get nextTabName(){let t=(this.tab+1)%(gt.length+1);return t===0?"all":gt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,e,n){return ae(Ie(t),"orig",`${e}.${n}`)}previewPath(t){return ae(Ie(t.site),"thumb",`${Sa(t.post)}.${xn(t.post.preview)}`)}tileOf(t,e){let{site:n,post:r}=t,i=se(n,r.id),o=Zn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:n===zr?bh(r.source):r.artist,score:r.score,variants:e,origin:zi(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,e=this.board;t.tiles=e.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),t.checked=e.checked,t.total=e.total,t.searching=e.searching,t.note=e.note,t.focus=Math.max(0,Math.min(e.focus,t.tiles.length-1)),t.top=e.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:e}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),e.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((s)=>{this.done=s}),r=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";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await n;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),e.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),Io(this.scratch,{recursive:!0,force:!0}),Su(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let e=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(n)=>{clearTimeout(e),this.probeWait=void 0,t(n)},this.write(Ah)})}onData=(t)=>{this.input+=t.toString("utf8");for(let n=po(this.input);n;n=po(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let e=vh(this.input);if(this.input=e.pending,this.view.editing===void 0&&e.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(e.keys))this.pasted(e.keys),e.keys="";this.typed+=e.keys;for(let n of e.events)this.inbound(n);if(clearTimeout(this.partial),Cp(this.typed)){this.partial=setTimeout(this.flushKeys,Jp);return}this.flushKeys()};flushKeys=()=>{let t=Th(this.typed);this.typed="";for(let e of t)this.key(e)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let e=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(e),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let e=this.view;if(e.editing!==void 0&&t.trim()!==""&&!this.picture(t)){e.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(e.installing!==void 0||e.asking!==void 0||e.panel!==void 0||e.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let e=t.trim();if(/^https?:\/\/\S+$/i.test(e))return!Ar(e,this.site??gt[0]);return Yr(e).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${ya}`);return}this.pasted(t.text);return}await this.bring(()=>Xr(t.bytes,t.source))}notice(t,e=Wp){let n=this.view;n.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===t)n.error=void 0,this.draw()},e),this.draw()}async peek(){let t=this.view,e;try{e=await Mh()}catch{return}if(!e||e.stamp===this.peeked)return;if(this.peeked=e.stamp,!e.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${Qp} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},xp),this.draw()}async fromClipboard(){let t=this.view;if(ho()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let e;try{e=await yh(ae(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${ln(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in e){await this.bring(async(r)=>({...await uo(e.image,r),source:"clipboard"}));return}let n=e.text.trim();if(!n){this.notice(`no picture on the clipboard — ${ya}`);return}if(this.picture(n)){await this.attach(n);return}if(t.editing===void 0)t.editing="";this.pasted(n)}async attach(t){let e=t.trim();if(/^https?:\/\//i.test(e)){let i=Ar(e,this.site??gt[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Yr(e).sort((i,o)=>Number(!Ea.test(i))-Number(!Ea.test(o)));if(!n){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>uo(n,i),r.length)}async bring(t,e=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)n.note=void 0,this.notice(ln(l),8000);return}if(r.signal.aborted)return;n.note=e>0?`the first picture of ${e+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let o=kh(i.bytes);$h(o,i.source);let s=this.origPath(zr,o,i.ext);fr(ci(s),{recursive:!0}),lr(s,i.bytes);let c=jp(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Na("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:zr,post:u},a=this.previewPath(h);fr(ci(a),{recursive:!0}),lr(a,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=ui(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,h)}single(t,e){t.searching=!1,this.posts.set(se(e.site,e.post.id),e),t.groups=[{posts:[e],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(e),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>ve(i)>ve(r)?i:r),e=Math.ceil((ve(t)-Date.now())/1000),n=e>0?e:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=t.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(t){let e=this.view;if(t==="ctrl-c"){this.finish(2);return}if(e.installing!==void 0)return;if(e.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&e.panel===void 0){this.fromClipboard();return}if(e.editing!==void 0){this.editKey(t);return}if(e.panel!==void 0){this.panelKey(t);return}if(e.help){if(t==="?"||t==="esc")e.help=!1,this.draw();return}if(this.cols<Je.cols||this.rows<Je.rows){if(t==="esc")this.finish(2);return}if(t==="?"){e.help=!0,this.draw();return}if(e.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let e=this.view,{perRow:n,rowsVis:r}=rn(this.cols,this.rows),o={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-e.focus,end:e.tiles.length}[t];if(o!==void 0){this.focus(e.focus+o);return}if(t==="enter"&&e.tiles[e.focus]){e.mode="try",e.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){e.preset=e.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(gt.length+1),this.syncSite(),this.turn();return}if(t==="/"){e.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){e.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let e=this.view,n=e.panel??0,r=e.settings[n];if(t==="up"||t==="down"){e.panel=Math.max(0,Math.min(e.settings.length-1,n+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){e.settings.forEach((i,o)=>{i.value=this.setting(fn[o]?.name??"")}),e.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")e.panel=void 0,this.adopt()}adopt(){let t=this.view,e=fn.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=fn[i];if(o)this.values.set(o.name,r.value)});let n=fn.filter((r,i)=>this.setting(r.name)!==e[i]);if(n.length===0){this.draw();return}this.save(n),t.rating=Lr(this.setting("TTHEME_FIND_RATING")),t.block=Tr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=ba(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((e)=>[e.name,this.setting(e.name)]))}store(t){let e=ae(this.home,"ttheme","config.zsh");try{let n=an(e)?Ra(e,"utf8"):"";return lr(e,t.reduce((r,[i,o])=>Xu(r,i,o),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}askKey(t){let e=this.view;if(t==="y"){if(e.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")e.asking=void 0,this.draw()}editKey(t){let e=this.view,n=e.editing??"",r=e.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=e.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;e.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(e.editing=void 0,e.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=e.pick===void 0?void 0:r[e.pick],o=i?n.replace(/\S*$/,i.value):n;if(e.editing=void 0,e.suggest=void 0,e.pick=void 0,o.trim()){this.commit(o.trim());return}if(e.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){e.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")e.editing=n+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let e=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Lp(e)){t.suggest=void 0;return}let n=[...new Map(Oh(this.catalog.palettes,this.entry,e).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,qp);t.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Ou(e,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(n.map((c)=>c.value));t.suggest=[...n.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,_p),t.pick=t.pick!==void 0&&t.pick<n.length?t.pick:void 0,this.draw()}}catch{}},Ap)}async commit(t){let e=Ar(t,this.site??gt[0]);if(e){await this.jump(e.site,e.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,e){let n=++this.gen;this.tab=gt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=ui(`${t.key}|post:${e}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Bi(t,e,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${e}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(n,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,e=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(t.focus<e+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=e;for(let i of n.posts)if(!this.thumbPath.has(se(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}e+=r}}openPage(){let t=this.view.tiles[this.view.focus],e=t&&this.posts.get(t.key);if(!e)return;let n=process.platform==="darwin"?"open":"xdg-open";try{Fa(n,[e.site.pageUrl(e.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let e=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(e.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid",e.error=void 0,this.draw()}focus(t){let e=this.view;if(e.tiles.length===0)return;let n=Math.max(0,Math.min(e.tiles.length-1,t));if(n===e.focus)return;if(e.focus=n,this.board.focus=n,this.scroll(),this.pump(),e.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:e,rowsVis:n}=rn(this.cols,this.rows),r=Math.floor(t.focus/e);if(r<t.top)t.top=r;if(r>t.top+n-1)t.top=r-n+1;this.board.top=t.top}query(t){let e=this.view,n=e.tag===this.entry.booru?Hh(this.entry,t.key):[e.tag];if(n.length===0)return;let r=n.length>1,i=e.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?n.map((h)=>`~${h}`).join(" "):n[0],t.rate(this.view.rating),o?"":i,e.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Yi([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,e=ui(this.boardKey,!0);this.board=e,this.boards.set(e.key,e),this.view.error=void 0;let n=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!n.some((s)=>s.site===o)),i=[...n.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(e.note=i.length>0?i.join(" · "):void 0,n.length===0)e.searching=!1;this.show(),this.draw(),this.tally(t,e,n);try{let o=await Promise.all(n.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;e.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Yi(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,e,n){let r=await Promise.allSettled(n.map(({site:i,tags:o})=>Fu(i,o,this.signal)));if(t===this.gen)e.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,e,n=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=Fo(n?.name??this.tabName,e),this.board.searching=!1,this.view.error=this.board.error,this.offer(n,e),this.show(),this.draw()}offer(t,e){if(t&&!this.view.unblocked&&Ha()&&ln(e)==="ECONNRESET")this.view.asking=t.name}drop(t,e,n){for(let r of t.sources)if(r.site===e)r.done=!0;t.note=[t.note,Fo(e.name,n)].filter(Boolean).join(" · "),this.offer(e,n)}wants(){let{perRow:t,rowsVis:e}=rn(this.cols,this.rows);return this.view.tiles.length<(this.board.top+e+Ma)*t}need(){let{perRow:t,rowsVis:e}=rn(this.cols,this.rows);return(e+Ma)*t}live(t){return this.boards.get(t.key)===t}page(t,e,n){let r=`${t.key}|${e}|${n}`,i=this.pages.get(r);if(!i)i=Iu(t,e,n,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let e=t.filter((n)=>n.solo===void 0&&n.md5!=="");if(e.length>0)try{Nu(e,await Ru(e.map((n)=>n.md5),this.signal))}catch{}return t}async round(t){let e=gt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),n=await Promise.all(e.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of n){if(!u)continue;c.page++,c.done=u.length<Le;let h=t.last.get(c);for(let a of u){let f=h&&ca(h.post,a)?h.set:`set:${c.site.key}:${a.id}`;h={post:a,set:f};let l=se(c.site,a.id);if(t.seen.has(l))continue;t.seen.add(l);let p={site:c.site,post:a};if(this.eligible(p))t.kin.set(p,[f,...sa(c.site,a)]),r.push(p);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=e.length>1?Xh(i):i;else{let c=ri(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...ri(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let e=t.queue.slice(0,this.need()).filter((n)=>!this.looking.has(se(n.site,n.post.id)));if(e.length===0)return;this.aheading=!0,this.looks(e).then(()=>{this.aheading=!1;for(let n of new Set(e.map((r)=>t.roundOf.get(r)??0)))this.resort(t,n);this.ahead(t)})}resort(t,e){let n=t.queue.flatMap((i,o)=>t.roundOf.get(i)===e?[o]:[]),r=ri(n.map((i)=>t.queue[i]),this.frame(),this.matched);n.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,e){let n=[];for(let r of e){let i=Mo(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);n.push(r);continue}if(t.checked++,va(r.post)<=va(o.post))continue;for(let c of[...i,...Mo(o.post)])t.same.set(c,r);let s=n.indexOf(o);if(s>=0){n[s]=r;continue}this.replace(t,o,r)}return n}replace(t,e,n){t.roundOf.set(n,t.roundOf.get(e)??0);let r=t.queue.indexOf(e);if(r>=0){t.queue[r]=n;return}for(let i of t.groups){let o=i.posts.indexOf(e);if(o>=0){i.posts[o]=n,this.posts.set(se(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(t){let e=0;await Promise.all(Array.from({length:ka},async()=>{while(e<t.length)await this.look(t[e++])}))}look(t){let e=se(t.site,t.post.id),n=this.looking.get(e);if(!n)n=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(e,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(e,n);return n}async pump(){let t=this.gen,e=this.board;if(this.pumping===t||e.sources.length===0)return;this.pumping=t;let n=[],r;try{e.searching=!0;while(t===this.gen){while(n.length<$a&&e.queue.length>0&&this.wants()){let s=e.queue.shift();n.push({pick:s,passed:this.vet(s)})}if(this.ahead(e),!r&&e.queue.length<$a&&e.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(e).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(e.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)e.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:e}){let n=Zn(e);if(!Mu(t,e,this.view.rating)||yu(e,this.view.block).length>0||!n)return!1;if(this.view.solo&&e.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(n.ext):e.ext==="png"}async vet(t){let[e]=await Promise.all([this.passes(t),this.look(t)]);return e}async passes({site:t,post:e}){return this.view.preset==="all"||t.vouched||this.transparent(t,e)}probes(t){let e=this.probed.get(t.key);if(!e)e=No(t,"probes.json"),this.probed.set(t.key,e);return e}async transparent(t,e){let n=this.probes(t),r=n[e.id];if(r!==void 0)return r;try{let i=(await Hu(t,e.file,this.signal))?.alpha===!0;return n[e.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let e=gt.find((n)=>n.key===t);if(e)Ro(e,"probes.json",this.probes(e))}this.unsaved.clear()}admit(t){let{site:e,post:n}=t,r=this.board,i=se(e,n.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,e,n){for(let r of e){let i=t.kindred.get(r);if(i)return i}return n&&t.shapes.find((r)=>ha(r.shape,n))?.group}register(t,e,n,r){for(let i of n)if(!t.kindred.has(i))t.kindred.set(i,e);if(r)t.shapes.push({shape:r,group:e})}async mateOwners(t){let e=this.owners.get(t.key);if(e)return e;let n=uu(this.home),r=No(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await Bi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);Ro(t,"owners.json",r);let c=vu(s);return this.owners.set(t.key,c),c}async cached(t,e,n,r){if(an(e))return Op(e).size;let i=this.inflight.get(e);if(i)return i;let o=(async()=>{let s=await ju(t,n,this.signal,r);return fr(ci(e),{recursive:!0}),lr(e,s),s.length})();this.inflight.set(e,o);try{return await o}finally{this.inflight.delete(e)}}thumbs(){while(this.thumbing<ka&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:e,post:n}=t,r=Jt.cols*this.cell.w,i=Jt.rows*this.cell.h,o=ae(Ie(e),"tile",`${Sa(n)}-${r}x${i}.png`);if(!an(o)){let s=this.previewPath(t);await this.cached(e,s,n.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(se(e,n.id),o),this.show(),this.draw()}select(){let t=this.view,e=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!e)return;if(this.current?.key===e.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(e),Kp),this.draw()}async load(t){let e=this.view,n=this.posts.get(t.key),r=n&&Zn(n.post);if(!n||!r)return;let{site:i}=n,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!an(c))e.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(f,l)=>{if(e.fetching?.id===t.key)e.fetching={id:t.key,got:f,size:l},this.draw()});if(s.signal.aborted)return;if(e.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};e.preparing=t.key,this.flush();let a=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(a.clear===0&&lo()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(e.preparing=void 0,e.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(e.cutting=void 0,h.cut){e.preparing=t.key,this.flush();let f=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(f&&jh(f.clear))h.using="cut";else Io(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,e.tiles[e.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)e.error=Fo(i.name,c)}finally{if(e.fetching?.id===t.key)e.fetching=void 0;if(e.preparing===t.key)e.preparing=void 0;if(e.cutting===t.key)e.cutting=void 0;this.draw()}}async cutOut(t,e,n,r){let i=ae(Ie(t),"cut",`${e}.png`);if(an(i))return i;try{return fr(ci(i),{recursive:!0}),await Ph(n,i,r),i}catch{Io(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let e of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Up)return;let n=t.tiles[e],r=n&&this.posts.get(n.key),i=r&&Zn(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:n.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,e){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,Zp),o=Math.max(1,Math.round(r*i/n)),s=ae(this.scratch,`${t.site.key}-${t.id}${e==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${e}`,u=this.clarity.get(c);if(u!==void 0&&an(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:e==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let e=t.using,{clear:n,path:r}=await this.render(t,e);if(this.current!==t||t.using!==e)return;this.view.shown={id:t.key,clear:n,bytes:t.size,path:r,cut:t.cut?e==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((e)=>{t.error=e instanceof Error?e.message:String(e)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,e=t.tiles[t.focus],n=this.current;if(!e||n?.key!==e.key||t.preparing!==void 0||t.shown?.id!==e.key)return;t.installing=e.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=No(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",Ro(n.site,"owners.json",r),hn(this.home),t.saved=`background · ${this.entry.name} ← ${n.site.name} ${n.id}`,t.installed.push(e.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=_h(this.view,this.cols,this.rows),e="\x1B[?2026h";t.lines.forEach((r,i)=>{e+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of t.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)e+=Uh(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)e+=Kh(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))e+=Jh(r),this.sent.delete(r),this.placed.delete(r);this.write(`${e}\x1B[?2026l`)}}function Ha(){if(process.versions.bun)return!0;let[t=0,e=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&e>=21}async function Ia(){if(!Ha())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
143
- `),1;let t=await wa(),e=Fa(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:${t.port}`,NO_PROXY:[process.env.NO_PROXY,Eu()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(t.port)}}),n=await new Promise((r)=>e.on("exit",(i)=>r(i??1)));return t.close(),n}async function ja(t){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Ia();let e=Pt(),n=Ut(e),r=ti(n.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Oa(e,n,r,r.booru??""),o=await i.run(),s=i.unblock?await Ia():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
144
- `),0;return s}function Pa(t,e){let n=Pt();if(ti(Ut(n).palettes,t),e==="next"||e==="prev"){let{key:r,at:i,of:o}=ou(n,t,e==="next"?1:-1);return hn(n),process.stderr.write(`background · ${t} ${i}/${o} ${r}
145
- `),0}if(e==="drop"){let{key:r,left:i}=su(n,t);return hn(n),process.stderr.write(`background · ${t} removed ${r} · ${i} left
146
- `),0}if(e==="tuned")return hn(n),0;throw Error(`unknown image action ${e} — next, prev, drop or tuned`)}import{execFileSync as X0,spawnSync as V0}from"node:child_process";import{chmodSync as Y0,copyFileSync as z0,existsSync as qt,mkdirSync as Xo,readdirSync as B0,readFileSync as kn,rmSync as Gf,writeFileSync as D0}from"node:fs";import{homedir as tw}from"node:os";import{dirname as $n,join as kt}from"node:path";import{styleText as To}from"node:util";import{stdout as za,stdin as h0}from"node:process";import a0 from"node:readline";var Ga=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),La=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},Ta=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var Xp=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Vp=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Aa=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Yp=/\t{1,1000}/y,Ua=/[\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,zp=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Bp=/\p{M}+/gu,Dp={limit:1/0,ellipsis:""},Ka=(t,e={},n={})=>{let r=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?Ka(i,Dp,n).width:0),s=0,c=n.controlWidth??0,u=n.tabWidth??8,h=n.emojiWidth??2,a=2,f=n.regularWidth??1,l=n.wideWidth??2,p=[[zp,f],[Xp,0],[Vp,c],[Yp,u],[Ua,h],[Aa,l]],b=0,g=0,$=t.length,y=0,F=!1,E=$,v=Math.max(0,r-o),d=0,j=0,k=0,H=0;t:while(!0){if(j>d||g>=$&&g>b){let R=t.slice(d,j)||t.slice(b,g);y=0;for(let L of R.replaceAll(Bp,"")){let P=L.codePointAt(0)||0;if(La(P))H=2;else if(Ta(P))H=l;else H=f;if(k+H>v)E=Math.min(E,Math.max(d,b)+y);if(k+H>r){F=!0;break t}y+=L.length,k+=H}d=j=0}if(g>=$)break t;for(let R=0,L=p.length;R<L;R++){let[P,C]=p[R];if(P.lastIndex=g,P.test(t)){if(y=P===Aa?Ga(t.slice(g,P.lastIndex)):P===Ua?1:P.lastIndex-g,H=y*C,k+H>v)E=Math.min(E,g+Math.floor((v-k)/C));if(k+H>r){F=!0;break t}k+=H,d=b,j=g,g=b=P.lastIndex;continue t}}g+=1}return{width:F?v:k,index:F?E:$,truncated:F,ellipsed:F&&r>=o}},Ja=Ka;var t0={limit:1/0,ellipsis:"",ellipsisWidth:0},e0=(t,e={})=>{return Ja(t,t0,e).width},Kt=e0;var hi="\x1B",qa="›",n0=39,Ho="\x07",_a="[",r0="]",Ca="m",jo=`${r0}8;;`,Wa=new RegExp(`(?:\\${_a}(?<code>\\d+)m|\\${jo}(?<uri>.*)${Ho})`,"y"),xa=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},Qa=(t)=>`${hi}${_a}${t}${Ca}`,Za=(t)=>`${hi}${jo}${t}${Ho}`,Oo=(t,e,n)=>{let r=e[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),c=s===void 0?0:Kt(s),u=r.next(),h=r.next(),a=0;while(!u.done){let f=u.value,l=Kt(f);if(c+l<=n)t[t.length-1]+=f;else t.push(f),c=0;if(f===hi||f===qa)i=!0,o=e.startsWith(jo,a+1);if(i){if(o){if(f===Ho)i=!1,o=!1}else if(f===Ca)i=!1}else if(c+=l,c===n&&!h.done)t.push(""),c=0;u=h,h=r.next(),a+=f.length}if(s=t.at(-1),!c&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},i0=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Kt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},o0=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),c=[""],u=0;for(let f=0;f<s.length;f++){let l=s[f];if(n.trim!==!1){let b=c.at(-1)??"",g=b.trimStart();if(b.length!==g.length)c[c.length-1]=g,u=Kt(g)}if(f!==0){if(u>=e&&(n.wordWrap===!1||n.trim===!1))c.push(""),u=0;if(u||n.trim===!1)c[c.length-1]+=" ",u++}let p=Kt(l);if(n.hard&&p>e){let b=e-u,g=1+Math.floor((p-b-1)/e);if(Math.floor((p-1)/e)<g)c.push("");Oo(c,l,e),u=Kt(c.at(-1)??"");continue}if(u+p>e&&u&&p){if(n.wordWrap===!1&&u<e){Oo(c,l,e),u=Kt(c.at(-1)??"");continue}c.push(""),u=0}if(u+p>e&&n.wordWrap===!1){Oo(c,l,e),u=Kt(c.at(-1)??"");continue}c[c.length-1]+=l,u+=p}if(n.trim!==!1)c=c.map((f)=>i0(f));let h=c.join(`
147
- `),a=!1;for(let f=0;f<h.length;f++){let l=h[f];if(r+=l,!a){if(a=l>="\uD800"&&l<="\uDBFF",a)continue}else a=!1;if(l===hi||l===qa){Wa.lastIndex=f+1;let b=Wa.exec(h)?.groups;if(b?.code!==void 0){let g=Number.parseFloat(b.code);i=g===n0?void 0:g}else if(b?.uri!==void 0)o=b.uri.length===0?void 0:b.uri}if(h[f+1]===`
148
- `){if(o)r+=Za("");let p=i?xa(i):void 0;if(i&&p)r+=Qa(p)}else if(l===`
149
- `){if(i&&xa(i))r+=Qa(i);if(o)r+=Za(o)}}return r},s0=/\r?\n/;function Re(t,e,n){return String(t).normalize().split(s0).map((r)=>o0(r,e,n)).join(`
150
- `)}var Zt=yr(Go(),1);function gn(t,e,n){if(!n.some((s)=>!s.disabled))return t;let r=t+e,i=Math.max(n.length-1,0),o=r<0?i:r>i?0:r;return n[o]?.disabled?gn(o,e<0?-1:1,n):o}function ai(t,e,n,r){let i=r.split(`
151
- `),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+n)),s=Math.min(s,i[o].length)+e;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var f0=["up","down","left","right","space","enter","cancel"],l0=["January","February","March","April","May","June","July","August","September","October","November","December"],xt={actions:new Set(f0),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:[...l0],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Ba(t,e){if(typeof t=="string")return xt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Ba(n,e))return!0;return!1}function g0(t,e){if(t===e)return;let n=t.split(`
152
- `),r=e.split(`
153
- `),i=Math.max(n.length,r.length),o=[];for(let s=0;s<i;s++)n[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var n1=globalThis.process.platform.startsWith("win"),Ao=Symbol("clack:cancel");function Oe(t){return t===Ao}function fi(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var gi=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Ko=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function gr(t,e,n,r=n,i=n,o){let s=gi(t??za);return Re(e,s-n.length,{hard:!0,trim:!1}).split(`
154
- `).map((c,u,h)=>{let a=o?o(c,u):c;return u===0?`${r}${a}`:u===h.length-1?`${i}${a}`:`${n}${a}`}).join(`
155
- `)}function Da(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}class be{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=h0,output:r=za,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],r=[];for(let i of n)i.cb(...e),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ao);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=a0.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),fi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zt.cursor.show),this.output.off("resize",this.render),fi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Zt.cursor.show),this.output.off("resize",this.render),fi(this.input,!1),t(Ao)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&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(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&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"),e?.name&&(!this._track&&xt.aliases.has(e.name)&&this.emit("cursor",xt.aliases.get(e.name)),xt.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=Da(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ba([t,e?.name,e?.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(`
156
- `),fi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Re(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
157
- `).length-1;this.output.write(Zt.cursor.move(-999,t*-1))}render(){let t=Re(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Zt.cursor.hide);else{let e=g0(this._prevFrame,t),n=Ko(this.output);if(this.restoreCursor(),e){let r=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),o=e.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(Zt.cursor.move(0,o-i)),this.output.write(Zt.erase.lines(1));let s=t.split(`
158
- `);this.output.write(s[o]),this._prevFrame=t,this.output.write(Zt.cursor.move(0,s.length-o-1));return}else if(e.lines.length>1){if(r<i)o=r;else{let c=o-i;c>0&&this.output.write(Zt.cursor.move(0,c))}this.output.write(Zt.erase.down());let s=t.split(`
159
- `).slice(o);this.output.write(s.join(`
160
- `)),this._prevFrame=t;return}}this.output.write(Zt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function d0(t,e){if(t===void 0||e.length===0)return 0;let n=e.findIndex((r)=>r.value===t);return n!==-1?n:0}function m0(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function p0(t,e){if(e)return t?e:e[0]}var w0=class extends be{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#t;#o;#c;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return To(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${e}${To("inverse",n)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#c=e.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=e.multiple===!0,this.#t=typeof e.options=="function"?e.filter:e.filter??m0;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=n.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#e=o)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,o)=>this.#n(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(e,n){return e==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&e!==void 0&&e!==""}#n(e,n){let r=n.name==="up",i=n.name==="down",o=n.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((a)=>!a.disabled&&(this.#t?this.#t(c,a):!0));if(n.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#e=gn(this.#e,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=p0(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((n)=>n!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#r(e){if(e!==this.#i){this.#i=e;let n=this.options;e&&this.#t?this.filteredOptions=n.filter((o)=>this.#t?.(e,o)):this.filteredOptions=[...n];let r=d0(this.focusedValue,this.filteredOptions);this.#e=gn(r,0,this.filteredOptions);let i=this.filteredOptions[this.#e];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Jo extends be{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(Zt.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var b0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Va(t){return[...t].map((e)=>b0[e])}function $0(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of e)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Lo(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function li(t){return{year:Lo(t.year),month:Lo(t.month),day:Lo(t.day)}}function Uo(t,e){return new Date(t||2001,e||1,0).getDate()}function tf(t){let{year:e,month:n,day:r}=li(t);if(!e||e<0||e>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(e,n-1,r));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:e,month:n,day:r}}function Ya(t){let e=tf(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function k0(t,e,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&e.year===i.year?i.month:1,max:o&&e.year===o.year?o.month:12}:{min:i&&e.year===i.year&&e.month===i.month?i.day:1,max:o&&e.year===o.year&&e.month===o.month?o.day:Uo(e.year,e.month)}}class ef extends be{#e;#i;#t;#o;#c;#n={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#t}}get segments(){return this.#e}get separator(){return this.#i}get formattedValue(){return this.#f(this.#t)}#f(t){return this.#e.map((e)=>t[e.type]).join(this.#i)}#u(){this._setUserInput(this.#f(this.#t)),this._setValue(Ya(this.#t)??void 0)}constructor(t){let e=t.format?{segments:Va(t.format),separator:t.separator??"/"}:$0(t.locale),n=t.separator??e.separator,r=t.format?Va(t.format):e.segments,i=t.initialValue??t.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=r.map((c)=>o[c.type]).join(n);super({...t,initialUserInput:s},!1),this.#e=r,this.#i=n,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#n.segmentIndex,this.#e.length-1)),e=this.#e[t];if(e)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,e.len-1)),{segment:e,index:t}}#a(t){this.inlineError="",this.#s=null;let e=this.#h();e&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#e.length-1,e.index+t)),this.#n.positionInSegment=0,this.#r=!0)}#l(t){let e=this.#h();if(!e)return;let{segment:n}=e,r=this.#t[n.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=k0(n.type,li(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[n.type]:c.toString().padStart(n.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#a(1);case"left":return this.#a(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(t,e){if(e?.name==="backspace"||e?.sequence===""||e?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let n=this.#h();if(!n)return;if(!this.#t[n.segment.type].replace(/_/g,"")){this.#a(-1);return}this.#t[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#u();return}if(e?.name==="tab"){this.inlineError="";let n=this.#h();if(!n)return;let r=e.shift?-1:1,i=n.index+r;i>=0&&i<this.#e.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#h();if(!n)return;let{segment:r}=n,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let l=this.#s+t,p={...this.#t,[r.type]:l},b=this.#g(p,r);if(b){this.inlineError=b,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=l,this.#s=null,this.#r=!1,this.#u(),n.index<this.#e.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#n.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(t,10);u=`0${t}`,h=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let l={...this.#t,[r.type]:u},p=this.#g(l,r);if(p){this.inlineError=p;return}}this.inlineError="",this.#t[r.type]=u;let a=u.includes("_")?void 0:tf(this.#t);if(a){let{year:l,month:p}=a,b=Uo(l,p);this.#t={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,p))).padStart(2,"0"),day:String(Math.max(1,Math.min(b,a.day))).padStart(2,"0")}}this.#u();let f=u.indexOf("_");h?(this.#r=!0,this.#s=t):f>=0?this.#n.positionInSegment=f:s>=0&&n.index<this.#e.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(c+1,r.len-1)}}#g(t,e){let{month:n,day:r}=li(t);if(e.type==="month"&&(n<0||n>12))return xt.date.messages.invalidMonth;if(e.type==="day"&&(r<0||r>31))return xt.date.messages.invalidDay(31,"any month")}#p(t){let{year:e,month:n,day:r}=li(this.#t);if(e&&n&&r){let i=Uo(e,n);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Ya(this.#t)??t.defaultValue??void 0}}var E0=class extends be{options;cursor=0;#e;getGroupItems(e){return this.options.filter((n)=>n.group===e)}isGroupSelected(e){let n=this.getGroupItems(e),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let n=e.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(e.value);this.value=n?this.value.filter((r)=>r!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:n}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),this.#e?0:1),this.on("cursor",(r)=>{switch(r){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.#e&&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.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},y0=new Set(["up","down","left","right"]);class nf extends be{#e=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return n===`
161
- `?`${e}█
162
- ${r}`:`${e}${To("inverse",n)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let e=this.value??"";switch(t){case"up":this._cursor=ai(this._cursor,0,-1,e);return;case"down":this._cursor=ai(this._cursor,0,1,e);return;case"left":this._cursor=ai(this._cursor,-1,0,e);return;case"right":this._cursor=ai(this._cursor,1,0,e);return}}_shouldSubmit(t,e){if(this.#i)return this.focused==="submit"?!0:(this.#t(`
163
- `),this._cursor++,!1);let n=this.#e;return this.#e=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
164
- `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
165
- `),this._cursor++,!1)}constructor(t){let e=t.initialUserInput??t.initialValue;super({...t,initialUserInput:e},!1),e!==void 0&&(this._cursor=e.length),this.#i=t.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&y0.has(r.name)){this.#e=!1,this.#o(r.name);return}if(n==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#e=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#t(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class Wo extends be{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?gn(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=gn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=gn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}import{styleText as S,stripVTControlCharacters as l1}from"node:util";import Yt from"node:process";var ff=yr(Go(),1);function M0(){if(Yt.platform!=="win32")return Yt.env.TERM!=="linux";return Boolean(Yt.env.CI)||Boolean(Yt.env.WT_SESSION)||Boolean(Yt.env.TERMINUS_SUBLIME)||Yt.env.ConEmuTask==="{cmd::Cmder}"||Yt.env.TERM_PROGRAM==="Terminus-Sublime"||Yt.env.TERM_PROGRAM==="vscode"||Yt.env.TERM==="xterm-256color"||Yt.env.TERM==="alacritty"||Yt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var v0=M0();var dt=(t,e)=>v0?t:e,S0=dt("◆","*"),I0=dt("■","x"),F0=dt("▲","x"),lf=dt("◇","o"),N0=dt("┌","T"),vt=dt("│","|"),dn=dt("└","—"),p1=dt("┐","T"),w1=dt("┘","—"),rf=dt("●",">"),of=dt("○"," "),R0=dt("◻","[•]"),sf=dt("◼","[+]"),cf=dt("◻","[ ]"),b1=dt("▪","•"),uf=dt("─","-"),O0=dt("╮","+"),H0=dt("├","+"),j0=dt("╯","+"),P0=dt("╰","+"),$1=dt("╭","+"),k1=dt("●","•"),E1=dt("◆","*"),y1=dt("▲","!"),M1=dt("■","x"),gf=(t)=>{switch(t){case"initial":case"active":return S("cyan",S0);case"cancel":return S("red",I0);case"error":return S("yellow",F0);case"submit":return S("green",lf)}},G0=(t)=>{switch(t){case"initial":case"active":return S("cyan",vt);case"cancel":return S("red",vt);case"error":return S("yellow",vt);case"submit":return S("green",vt)}};function L0(t,e){let n=[`${e?`${S("cyan",vt)} `:""}${t.join(" • ")}`];return e&&n.push(S("cyan",dn)),n}var hf=(t,e,n,r,i,o=!1)=>{let s=e,c=0;if(o)for(let u=r-1;u>=n;u--){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}else for(let u=n;u<r;u++){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}return{lineCount:s,removals:c}},af=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let c=gi(r)-o,u=Ko(r),h=S("dim","..."),a=Math.max(u-s,0),f=Math.max(Math.min(i,a),5),l=0;t>=f-3&&(l=Math.max(Math.min(t-f+3,e.length-f),0));let p=f<e.length&&l>0,b=f<e.length&&l+f<e.length,g=Math.min(l+f,e.length),$=[],y=0;p&&y++,b&&y++;let F=l+(p?1:0),E=g-(b?1:0);for(let d=F;d<E;d++){let j=e[d],k=j?n(j,d===t):"",H=Re(k,c,{hard:!0,trim:!1}).split(`
166
- `);$.push(H),y+=H.length}if(y>a){let d=0,j=0,k=y,H=t-F,R=a,L=()=>hf($,k,0,H,R),P=()=>hf($,k,H+1,$.length,R,!0);p?({lineCount:k,removals:d}=L(),k>R&&(b||(R-=1),{lineCount:k,removals:j}=P())):(b||(R-=1),{lineCount:k,removals:j}=P(),k>R&&(R-=1,{lineCount:k,removals:d}=L())),d>0&&(p=!0,$.splice(0,d)),j>0&&(b=!0,$.splice($.length-j,j))}let v=[];p&&v.push(h);for(let d of $)for(let j of d)v.push(j);return b&&v.push(h),v};var mr=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new Jo({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??xt.withGuide,i=`${gf(this.state)} `,o=r?`${S("gray",vt)} `:"",s=gr(t.output,t.message,o,i),c=`${r?`${S("gray",vt)}
167
- `:""}${s}
168
- `,u=this.value?e:n;switch(this.state){case"submit":{let h=r?`${S("gray",vt)} `:"";return`${c}${h}${S("dim",u)}`}case"cancel":{let h=r?`${S("gray",vt)} `:"";return`${c}${h}${S(["strikethrough","dim"],u)}${r?`
169
- ${S("gray",vt)}`:""}`}default:{let h=r?`${S("cyan",vt)} `:"",a=r?S("cyan",dn):"";return`${c}${h}${this.value?`${S("green",rf)} ${e}`:`${S("dim",of)} ${S("dim",e)}`}${t.vertical?r?`
170
- ${S("cyan",vt)} `:`
171
- `:` ${S("dim","/")} `}${this.value?`${S("dim",of)} ${S("dim",n)}`:`${S("green",rf)} ${n}`}
172
- ${a}
173
- `}}}}).prompt()};var T0=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Space:")} select`,`${S("dim","Enter:")} confirm`],dr=(t,e)=>t.split(`
174
- `).map((n)=>e(n)).join(`
175
- `),df=(t)=>{let e=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${S("gray",cf)} ${dr(s,(c)=>S(["strikethrough","gray"],c))}${i.hint?` ${S("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${S("cyan",R0)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${S("green",sf)} ${dr(s,(c)=>S("dim",c))}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${dr(s,(c)=>S(["strikethrough","dim"],c))}`:o==="active-selected"?`${S("green",sf)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${dr(s,(c)=>S("dim",c))}`:`${S("dim",cf)} ${dr(s,(c)=>S("dim",c))}`},n=t.required??!0,r=t.showInstructions??!0;return new Wo({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
176
- ${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??xt.withGuide,o=gr(t.output,t.message,i?`${G0(this.state)} `:"",`${gf(this.state)} `),s=`${i?`${S("gray",vt)}
177
- `:""}${o}
178
- `,c=this.value??[],u=(h,a)=>{if(h.disabled)return e(h,"disabled");let f=c.includes(h.value);return a&&f?e(h,"active-selected"):f?e(h,"selected"):e(h,a?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:f})=>c.includes(f)).map((f)=>e(f,"submitted")).join(S("dim",", "))||S("dim","none"),a=gr(t.output,h,i?`${S("gray",vt)} `:"");return`${s}${a}`}case"cancel":{let h=this.options.filter(({value:f})=>c.includes(f)).map((f)=>e(f,"cancelled")).join(S("dim",", "));if(h.trim()==="")return`${s}${S("gray",vt)}`;let a=gr(t.output,h,i?`${S("gray",vt)} `:"");return`${s}${a}${i?`
179
- ${S("gray",vt)}`:""}`}case"error":{let h=i?`${S("yellow",vt)} `:"",a=this.error.split(`
180
- `).map((p,b)=>b===0?`${i?`${S("yellow",dn)} `:""}${S("yellow",p)}`:` ${p}`).join(`
181
- `),f=s.split(`
182
- `).length,l=a.split(`
183
- `).length+1;return`${s}${h}${af({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+l,style:u}).join(`
184
- ${h}`)}
185
- ${a}
186
- `}default:{let h=i?`${S("cyan",vt)} `:"",a=s.split(`
187
- `).length,f=r?L0(T0,i):i?[S("cyan",dn)]:[],l=f.join(`
188
- `),p=f.length+1;return`${s}${h}${af({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:a+p,style:u}).join(`
189
- ${h}`)}
190
- ${l}
191
- `}}}}).prompt()};var mn=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??xt.withGuide?`${S("gray",dn)} `:"";n.write(`${r}${S("red",t)}
192
-
193
- `)},di=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??xt.withGuide?`${S("gray",N0)} `:"";n.write(`${r}${t}
194
- `)},mf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??xt.withGuide?`${S("gray",vt)}
195
- ${S("gray",dn)} `:"";n.write(`${r}${t}
196
-
197
- `)};var A0=(t)=>t,U0=(t,e,n)=>{let r={hard:!0,trim:!1},i=Re(t,e,r).split(`
198
- `),o=i.reduce((u,h)=>Math.max(Kt(h),u),0),s=i.map(n).reduce((u,h)=>Math.max(Kt(h),u),0),c=e-(s-o);return Re(t,c,r)},pn=(t="",e="",n)=>{let r=n?.output??Yt.stdout,i=n?.withGuide??xt.withGuide,o=n?.format??A0,s=["",...U0(t,gi(r)-6,o).split(`
199
- `).map(o),""],c=Kt(e),u=Math.max(s.reduce((l,p)=>{let b=Kt(p);return b>l?b:l},0),c)+2,h=s.map((l)=>`${S("gray",vt)} ${l}${" ".repeat(u-Kt(l))}${S("gray",vt)}`).join(`
200
- `),a=i?`${S("gray",vt)}
201
- `:"",f=i?H0:P0;r.write(`${a}${S("green",lf)} ${S("reset",e)} ${S("gray",uf.repeat(Math.max(u-c-1,1))+O0)}
202
- ${h}
203
- ${S("gray",f+uf.repeat(u+2)+j0)}
204
- `)};var v1={light:dt("─","-"),heavy:dt("━","="),block:dt("█","#")};var S1=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Enter:")} confirm`];var I1=`${S("gray",vt)} `;import{existsSync as C0}from"node:fs";import{openSync as K0,writeSync as J0}from"node:fs";import{ReadStream as W0}from"node:tty";var pf=["10","11","12","17",...Array.from({length:16},(t,e)=>`4;${e}`)];function pr(t=process.env){return Boolean(t.NO_COLOR)||t.TERM==="dumb"}function mi(t){return[`\x1B]11;${t.background}\x1B\\`,`\x1B]10;${t.foreground}\x1B\\`,`\x1B]12;${t.cursor}\x1B\\`,`\x1B]17;${t.selection}\x1B\\`,...t.ansi.map((e,n)=>`\x1B]4;${n};${e}\x1B\\`)].join("")}function wf(t){let e=new Map;for(let n of t.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)e.set(i,o)}return e}function bf(t){return[...t].map(([e,n])=>`\x1B]${e};${n}\x1B\\`).join("")}async function $f(){let t,e;try{t=K0("/dev/tty","r+"),e=new W0(t),e.setRawMode(!0)}catch{return new Map}try{J0(t,pf.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let n="";return await new Promise((r)=>{let i=setTimeout(r,120);e.on("data",(o)=>{if(n+=o.toString(),wf(n).size>=pf.length)clearTimeout(i),r()})}),wf(n)}finally{e.setRawMode(!1),e.destroy()}}function wn(t){let e=t.replace("#","");return[e.slice(0,2),e.slice(2,4),e.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function kf(t,e){return`\x1B[48;2;${wn(e)}m ${t} \x1B[0m`}function Qo(t,e){return`\x1B[48;2;${wn(t)};38;2;${wn(e)}m ● \x1B[0m`}function Ef(t){return`\x1B[38;2;${wn(t)}m`}function Zo(t,e){return`\x1B[48;2;${wn(e)}m${t.map((n)=>`\x1B[38;2;${wn(n)}m▄`).join("")} \x1B[0m`}function pi(t,e){let n=e.toLowerCase();return[t.name,t.group,t.native??""].some((r)=>r.toLowerCase().includes(n))}function Mf(t,e,n){let r=n.trim(),i=[],o=new Set;for(let s of t){if(s.default||o.has(s.group))continue;o.add(s.group);let c=t.filter((a)=>!a.default&&a.group===s.group),u=r?c.filter((a)=>pi(a,r)):c;if(r&&u.length===0)continue;let h=r.length>0||e.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:c.find((a)=>a.lead)??s,expanded:h,count:u.length}),h)i.push(...u.map((a)=>({kind:"palette",entry:a})))}return i}function x0(t,e){let n=e.trim(),r=new Set(t.filter((i)=>!i.default&&(n===""||pi(i,n))).map((i)=>i.group));return Mf(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Q0(t){let e=t.findIndex((n)=>n.kind==="palette");return e===-1?0:e}var ne="\x1B[0m",bn="\x1B[2m",Z0="\x1B[1m",yf="\x1B[1;7m",q0="\x1B[36m",_0="\x1B[33m";function vf(t){return t==="decode"||t==="glitch"?t:"typewriter"}class qo extends be{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(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=t.entries,this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.named=t.entries.filter((n)=>!n.default),this.series=[...new Set(this.named.map((n)=>n.group))],this.seriesPad=Math.max(0,...this.series.map((n)=>n.length)),this.maxItems=t.maxItems??12,this.color=t.color??!0,this.fx=t.fx??"typewriter",this.onFocus=t.onFocus,this.rollExample();let e=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);e.unref?.(),this.once("finalize",()=>{clearInterval(e),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(n)=>{if(n==="up")this.move(-1);else if(n==="down")this.move(1);else if(n==="left")this.fold(!1);else if(n==="right")this.fold(!0)}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.rebuild("keep")}),this.on("key",(n,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(t){return t==="\t"||t===" "}members(t){let e=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((n)=>n.group===t&&(e===""||pi(n,e)))}everyone(t){return t.flatMap((e)=>e.kind==="group"?this.members(e.name):[])}pick(t){let e=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(e.length===0)return;let n=e.some((r)=>!this.picked.has(r));for(let r of e)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(t){return this.members(t).filter((e)=>this.picked.has(e.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((t)=>this.members(t).every((e)=>this.picked.has(e.name))).length}rollExample(){let t=this.named[Math.floor(Math.random()*this.named.length)],e=this.series[Math.floor(Math.random()*this.series.length)];if(!t||!e){this.example="";return}let n=`${t.name} | ${e}`;this.example=n.length>30?`${n.slice(0,29)}…`:n,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 t=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let e=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<t||n(r)?r:e[Math.floor(Math.random()*e.length)]??r).join("")}sync(){let t=this.rows[this.cursor],e=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(e&&e.name!==this.lastFocused)this.lastFocused=e.name,this.onFocus?.(e)}rebuild(t){let e=this.rows[this.cursor],n=this.scope==="series"?x0(this.entries,this.userInput):Mf(this.entries,this.expanded,this.userInput),r=n.length>0?Q0(n)+1:0;if(this.rows=n.length>0?[{kind:"all",count:this.allCount(n)},...n]:[],t==="first")this.cursor=r;else if(t==="keep"){let i=e?.kind==="palette"?e.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){let e=this.cursor+t;if(e>=0&&e<this.rows.length)this.cursor=e;this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}fold(t){if(this.userInput||this.scope==="series")return;let e=this.rows[this.cursor];if(e?.kind==="group"){if(t!==e.expanded)this.toggle(e.name)}else if(e?.kind==="palette"&&!t&&!e.entry.default){let n=e.entry.group;if(this.expanded.delete(n),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===n),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(t,e){let n=e?"▶ ":" ";if(t.kind==="all"){let o=this.everyone(this.rows).every((c)=>this.picked.has(c.name))?"● ":"○ ",s=`(${t.count})`;return`${n}${o}select all ${this.color?`${bn}${s}${ne}`:s}`}if(t.kind==="group"&&this.scope==="series"){let o=this.pickedIn(t.name)===t.count?"● ":"○ ",s=t.name.padEnd(this.seriesPad),c=`(${t.count})${t.native?` ${t.native}`:""}`;if(!this.color)return`${n}${o}${s} ${c}`;let u=t.lead;return`${n}${o}${s} ${Qo(u.background,u.cursor)}${Zo(u.ansi.slice(1,7),u.background)} ${bn}${c}${ne}`}if(t.kind==="group"){let o=t.expanded?"▾":"▸",s=this.rows[this.cursor],c=s?.kind==="palette"&&s.entry.group===t.name?s.entry:void 0,u=this.color?e?`${yf} ${t.name} ${ne}`:c?`${yf}${Ef(c.cursor)} ${t.name} ${ne}`:` ${Z0}${t.name}${ne} `:e?`[${t.name}]`:` ${t.name}`,h=this.color?kf("●",t.lead.selection):"",a=`${this.pickedIn(t.name)}/${t.count}`,f=this.color?` ${bn}(${a})${ne}`:` (${a})`,l=t.native?this.color?` ${bn}${t.native}${ne}`:` ${t.native}`:"";return`${o}${u}${h}${f}${l}`}let r=t.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${n}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${n}${i}${r.name.padEnd(13)} ${Qo(r.background,r.cursor)}${Zo(r.ansi.slice(1,7),r.background)} ${bn}${r.ansiSource}${ne}`}draw(){let t=(g)=>this.color?`${bn}${g}${ne}`:g,e=(g)=>this.color?`${q0}${g}${ne}`:g,n=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${t("◇")} ${n} ${t(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${n} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((g)=>g.kind==="group").length:r?this.named.filter((g)=>pi(g,r)).length:i,s=`${e("◆")} ${n} ${t(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,c=`${e("│")} ${this.userInput?`⌕ ${this.userInput}_`:t(`⌕ 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 u=this.rows.slice(this.top,this.top+this.maxItems),h=u.length>0?u.map((g,$)=>`${e("│")} ${this.renderRow(g,this.top+$===this.cursor)}`):[`${e("│")} ${t(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(e("│"));let a=this.rows.length-this.top-u.length,f=a>0?`${e("│")} ${t(`↓ ${a} more`)}`:e("│"),l=this.scope==="series"?"":" · ←→ fold",p=this.scope==="series"?"continue":"install",b=this.state==="error"?`${e("└")} ${this.color?`${_0}${this.error}${ne}`:this.error}`:`${e("└")} ${t(`↑↓ move${l} · space pick · type to filter · enter ${p} · esc cancel`)}`;return[s,c,...h,f,b].join(`
205
- `)}}function wr(t,e,n,r){let i=Ne(),o=Boolean(ee(n))!==Boolean(ee(r)),s=o?cr(r,i):r;return ar(t,e,s),hr(t,s),o&&Qe(s,i)&&i.running()}function _o(t){console.log(`
206
- ${t} palettes installed — open a new tab, or reload your terminal config`)}function Sf(t){let e=Pt(),n=Ut(e),r=Wt(e),i=t.filter((c)=>r.palettes.includes(c)),o=t.filter((c)=>!r.palettes.includes(c));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...r,palettes:[...r.palettes,...o]};wr(e,n,r,s);for(let c of o)console.log(` + ${c}`);_o(s.palettes.length)}function If(t){let e=Pt(),n=Ut(e),r=Wt(e),i=t.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${t.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};wr(e,n,r,o),yo(e,n,r.terminals,i);for(let s of i)console.log(` - ${s}`);_o(o.palettes.length)}function Ff(t){let e=Pt(),n=Ut(e),r=Wt(e);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{off:i,...o}=r,s=Ne(),c=cr({...o,startup:t},s);ar(e,n,c),hr(e,c);let u=Qe(c,s);console.log(Of(t,c.terminals,u&&s.running()).join(`
207
- `))}function Nf(){let t=Pt(),e=Wt(t),n=un(e);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!e.off){console.log(`already on · ${n}`);return}let{off:r,...i}=e,o=wr(t,Ut(t),e,i);console.log(Of(n,i.terminals,o).join(`
208
- `))}function Rf(){let t=Pt(),e=Wt(t);if(e.off){console.log("already off");return}let n=wr(t,Ut(t),e,{...e,off:!0}),r=un(e);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),n)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function Of(t,e,n){let r=e.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${t} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(e.includes("iterm2"))i.push(n?'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 ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Hf(t,e=!1){let n=Pt(),r=Ut(n),i=new Set(Wt(n).palettes),o=Ge(r.palettes),s=_n(t?Rh(o,t):o);if(e){let u=s.map((h)=>({name:h.name,group:h.group,installed:i.has(h.name)}));console.log(JSON.stringify(u,null,2));return}let c=Math.max(...s.map((u)=>u.name.length),0);for(let u of s)console.log(` ${i.has(u.name)?"●":"○"} ${u.name.padEnd(c)} ${u.group}`);if(process.stdout.isTTY){let u=t?`${s.length} of ${o.length}`:`${o.length}`;console.log(`
209
- ${u} palettes — ${s.filter((h)=>i.has(h.name)).length} installed`)}}async function jf(){let t=Pt(),e=C0(Br(t))?Ut(t).palettes.length:0,n=await Fh(Sh);Dr(t,n);let r=n.palettes.length-e;console.log(`catalog ${n.version} — ${n.palettes.length} palettes${r>0?` (+${r})`:""}`)}async function Co(t,e,n,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:_n(t.palettes),o=process.stdout.isTTY===!0&&!pr(),s=o?await $f():new Map,c=new qo({entries:i,scope:n,installed:e,required:r,color:!pr(),fx:vf(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(mi(h)):void 0}),u=await c.prompt();if(process.stdout.write(bf(s)),Oe(u))return;return t.palettes.filter((h)=>c.picked.has(h.name)).map((h)=>h.name)}async function Pf(){let t=Pt(),e=Ut(t),n=Wt(t),r=await Co(e,n.palettes,"palette");if(!r){console.log("nothing changed");return}let i=n.palettes.filter((c)=>!r.includes(c)),o=r.filter((c)=>!n.palettes.includes(c));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...n,palettes:r};wr(t,e,n,s),yo(t,e,n.terminals,i);for(let c of o)console.log(` + ${c}`);for(let c of i)console.log(` - ${c}`);_o(s.palettes.length)}function ew(t,e,n){for(let r of B0(e))t.push({from:kt(e,r),to:kt(n,r)})}function Uf(t){return JSON.parse(kn(kt(t,"dist","manifest.json"),"utf8"))}function Lf(t,e){let n=kt(e.configHome,"ttheme"),r=[{from:kt(e.root,"bin","ttheme.js"),to:kt(n,"ttheme.js")},{from:kt(e.root,"bin","ttheme.js.map"),to:kt(n,"ttheme.js.map")},{from:kt(e.root,"shell","ttheme.zsh"),to:kt(n,"ttheme.zsh")},{from:kt(e.root,"shell","launch-tab.zsh"),to:kt(n,"launch-tab.zsh"),executable:!0}];ew(r,kt(e.root,"shell","adapters"),kt(n,"adapters"));let i=[{file:kt(e.zdotdir,".zshrc"),block:qu(n)}],o=kt(n,"config.zsh"),s=Vu(qt(o)?kn(o,"utf8"):""),c={file:o,content:s},u=[];if(t.terminals.includes("alacritty")){let f=Ze(e.configHome);if(qt(f)&&zn(kn(f,"utf8"),void 0)===void 0)u.push(`${f} already imports files under [general] — ttheme left it alone; add ${kt(e.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(t.terminals.includes("wezterm")){let f=cn(e.configHome,e.home);if(qt(f)&&Bn(kn(f,"utf8"),"")===void 0)u.push(`${f} has no \`return config\` line — ttheme left it alone; call \`dofile("${kt(n,"wezterm.lua")}")(config)\` from it yourself`)}let h=t.terminals.includes("windows-terminal");if(h&&!e.wtHome)u.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(t.terminals.includes("warp"))u.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let a={terminals:t.terminals,palettes:t.palettes,...h&&e.wtHome?{wtHome:e.wtHome}:{},...h&&e.wtProfile?{wtProfile:e.wtProfile}:{},...t.off?{off:!0}:{}};return u.push(...oa(e.configHome,t.terminals,e.home)),{home:e.home,copies:r,edits:i,settings:c,catalog:Uf(e.root),installed:a,notes:u}}function nw(t){try{return Wt(t).itermBase}catch{return}}function Tf(t,e=Ne()){for(let o of t.copies)if(Xo($n(o.to),{recursive:!0}),Gf(o.to,{force:!0}),Gf(`${o.to}.zwc`,{force:!0}),z0(o.from,o.to),o.executable)Y0(o.to,493);Xo($n(t.settings.file),{recursive:!0}),D0(t.settings.file,t.settings.content);let n=$n($n(t.settings.file)),r=nw(n),i=cr(r?{...t.installed,itermBase:r}:t.installed,e);Dr(n,t.catalog),hr(n,i),ar(n,t.catalog,i,t.home);for(let o of t.edits){Xo($n(o.file),{recursive:!0});let s=qt(o.file)?kn(o.file,"utf8"):"";Gn(o.file,Xn(s,o.block))}return Qe(i,e)}class He extends Error{}function Vo(t){if(Oe(t))throw mn("nothing changed"),new He;return t}function Kf(t){return Jr.filter((e)=>{if(e==="iterm2")return process.platform==="darwin";if(e==="windows-terminal")return t.wtHome!==void 0;return e!=="warp"||process.platform!=="win32"})}function rw(t,e){if(t==="iterm2")return qt(kt(e.home,"Library","Application Support","iTerm2"));if(t==="windows-terminal")return e.wtHome!==void 0;if(t==="warp")return qt($n(ii(e.home)));if(t==="wezterm")return qt(kt(e.configHome,"wezterm"))||qt(kt(e.home,".wezterm.lua"));return qt(kt(e.configHome,t))}function iw(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let t=(e,n)=>X0(e,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return t("wslpath",["-u",t("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function ow(t,e,n){return Vo(await df({message:"wire which terminals?",options:Kf(n).map((r)=>({value:r,hint:r===t?"detected":void 0})),initialValues:e,required:!0}))}function Af(t){let e=[...t.copies.filter((n)=>!qt(n.to)).map((n)=>n.to),...qt(t.settings.file)?[]:[t.settings.file],...t.edits.filter((n)=>!kn(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(e.length>0)throw Error(`init left gaps:
210
- ${e.join(`
211
- `)}`)}function Jf(t,e){return[...new Set(t.palettes.filter((n)=>e.includes(n.name)).map((n)=>n.group))]}function sw(t,e){let n=t.palettes.find((i)=>i.name===ee(e)),r=process.stdout.isTTY===!0&&!pr()&&!process.env.TMUX&&Wr(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(mi(n)),!0}function cw(t,e){let n=ee(t);if(!n)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${un(t)}`];return[`default ${n}${e?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function uw(t){V0("zsh",["-c",'source "$1" && __tt_preview init',"zsh",kt(t,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function hw(t,e,n,r){let i=Jf(t.catalog,e.palettes);pn([`${i.join(", ")} (${e.palettes.length})`,...cw(t.installed,n)].join(`
212
- `),`installed ${e.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(e.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(e.terminals.includes("kitty"))o.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(e.terminals.includes("alacritty"))o.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm"))o.push("wezterm reloads its config by itself");if(e.terminals.includes("windows-terminal"))o.push("windows terminal reloads its settings by itself");if(e.terminals.includes("iterm2"))o.push(...aw(ee(t.installed),r));pn([...o,...t.notes].join(`
213
- `),"next"),mf("done")}function aw(t,e){let n=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(t)n.push(e?`restart iterm2 new tabs open on "ttheme · default", which wears ${t}`:`iterm2 default "ttheme · default" wears ${t} and follows \`ttheme default\``);return n}function fw(t,e){let n=[`placed ${t.copies.length} files`,`settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`wired ${r.file}`)];if(e.terminals.includes("ghostty"))n.push("restart ghostty to pick up its config");if(e.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(e.terminals.includes("alacritty"))n.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm")||e.terminals.includes("windows-terminal"))n.push("wezterm and windows terminal reload their config by themselves");if(e.terminals.includes("iterm2"))n.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...t.notes),n.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
214
- `))}async function Wf(t={}){let e=kt(import.meta.dirname,"..");if(!qt(kt(e,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!qt(kt(e,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await qr()}let n=tw(),r=Pt(),i=process.env.ZDOTDIR??n,o=iw(),s=process.env.WT_PROFILE_ID,c={root:e,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},u=Wr(process.env),h=Kf(c).filter((d)=>d===u||rw(d,c));if(!t.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");if(t.yes){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let d={terminals:h,palettes:[]},j=Lf(d,c);Tf(j),Af(j),fw(j,d);return}di("ttheme init");let a=await ow(u,h,c),f=Uf(e),l=await Co(f,[],"series",!0);if(!l)throw mn("nothing changed"),new He;let p=l[0],b=l.length>1&&Wr(process.env)!=="warp",g=Vo(await mr({message:b?"pick a default palette in ttheme preview once installed?":`wear ${p} in every tab?`})),$={terminals:a,palettes:l,off:!g},y=Lf($,c);if(pn([`install ${l.length} palettes — ${Jf(y.catalog,l).join(", ")}`,`copy ${y.copies.length} files under ${r}`,`write ${y.settings.file}`,...y.edits.map((d)=>`edit ${d.file} — a ttheme block: source ttheme.zsh`),...ia(r,y.installed,n),"each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",g?b?`open ttheme preview — every tab wears the palette picked there, ${p} until then`:`paint every tab with ${p}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...a.includes("iterm2")&&g?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
215
- `),`wiring ${a.join(", ")}`),!Vo(await mr({message:"apply these changes?"})))throw mn("nothing changed"),new He;let F=Ne(),E=Tf(y,F);if(Af(y),g&&b)uw(r);let v=Wt(r);hw({...y,installed:v},$,sw(y.catalog,v),E&&F.running())}import{existsSync as Yo,readdirSync as lw,readFileSync as gw,rmSync as dw,utimesSync as mw}from"node:fs";import{homedir as pw}from"node:os";import{dirname as ww,join as En}from"node:path";function zo(t){return Yo(t)?gw(t,"utf8"):""}function bw(t){try{return Wt(t)}catch{return}}function $w(t,e){let n=oi(e,t),r=zo(n);if(!xr(r)?.includes(`path = "${ut("")}`))return;return{file:n,content:Qr(r,zo(ko(t))||$o)}}function kw(t){let{home:e,configHome:n}=t,r=bw(n),i=[],o=(h,a)=>{let f=zo(h),l=a(f);if(l!==f)i.push({file:h,content:l})};o(En(t.zdotdir,".zshrc"),Vn),o(xe("ghostty",n),Vn),o(xe("kitty",n),Vn),o(Ze(n),Vn),o(cn(n,e),th);let s=$w(n,e);if(s)i.push(s);let c=[];for(let h of["ghostty","kitty","alacritty","wezterm","warp"]){let a=We(h,n,e);if(Yo(a))c.push(...lw(a).flatMap((f)=>f.startsWith(ut(""))?[En(a,f)]:[]))}let u=[ur(e),...r?.wtHome?[ww(si(r.wtHome))]:[],En(n,"ttheme"),t.cacheDir,t.stateDir];return c.push(...u.filter((h)=>Yo(h))),{edits:i,removals:c,touches:r?.wtHome?Eo(r.wtHome):[],...r?{state:r}:{}}}function Ew(t,e=Ne()){let n=[];for(let{file:i,content:o}of t.edits){let s=Us(i,o);n.push(s==="removed"?`removed ${i} — ttheme had created it`:s==="restored"?`took ttheme out of ${i}`:`took ttheme out of ${i} — kept ${i}.ttheme.bak, since the file changed after ttheme's first edit`)}if(t.state&&Qe({...t.state,off:!0},e))n.push("gave iTerm2 its own default profile back — it takes it at its next start");for(let i of t.removals)dw(i,{recursive:!0,force:!0});if(t.removals.length>0)n.push(`deleted ${t.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of t.touches)mw(i,r,r);return n}function yw(){let t=pw();return{home:t,configHome:Pt(),zdotdir:process.env.ZDOTDIR??t,cacheDir:Ur(),stateDir:En(process.env.XDG_STATE_HOME??En(t,".local","state"),"ttheme")}}async function xf(t=!1){let e=yw(),n=kw(e);if(n.edits.length===0&&n.removals.length===0){console.log("nothing of ttheme is installed");return}if(!t){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=En(e.configHome,"ttheme");di("ttheme uninstall"),pn([...n.edits.map((o)=>`take ttheme out of ${o.file}`),...n.removals.map((o)=>o===r?`delete ${o} — settings, pins and every installed picture`:`delete ${o}`)].join(`
216
- `),"uninstall");let i=await mr({message:"remove ttheme?"});if(Oe(i)||!i)throw mn("nothing changed"),new He}for(let r of Ew(n))console.log(r);console.log("open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var vw={default:([t])=>Ff(t),on:()=>Nf(),off:()=>Rf(),browse:()=>Pf(),list:([t],{json:e})=>Hf(t,e),add:(t)=>Sf(t),remove:(t)=>If(t),update:()=>jf(),init:(t,{yes:e})=>Wf({yes:e}),uninstall:(t,{yes:e})=>xf(e),build:(t,{only:e})=>qr({only:e}),find:([t])=>ja(t),image:([t,e])=>Pa(t,e)},qf=Kr.map((t)=>({...t,run:vw[t.name]}));class qe extends Error{verb;constructor(t,e){super(t);this.verb=e}}function Qf(t){let e=qf.find((n)=>n.name===t);if(!e)throw new qe(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return e}function Sw(t,e){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(t.flags??{}))n[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return Mw({args:e,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new qe(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function Iw(t){let[e,...n]=t;if(e===void 0)return{kind:"help",code:1};if(e==="-h"||e==="--help")return{kind:"help",code:0};if(e==="-V"||e==="--version")return{kind:"version"};if(e==="help")return n[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:Qf(n[0]),code:0};let r=Qf(e),i=Sw(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[a,{choices:f}]of Object.entries(r.flags??{}))for(let l of[i.values[a]??[]].flat())if(f&&!f.includes(String(l)))throw new qe(`--${a} takes ${f.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((a)=>a.startsWith("<")).length,c=r.args.some((a)=>a.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new qe(`missing ${r.args[o.length]}`,r);if(o.length>c)throw new qe(`too many arguments: ${o.slice(c).join(" ")}`,r);let{help:u,...h}=i.values;return{kind:"run",verb:r,args:o,flags:h}}function Bo(t){let e=Object.entries(t.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[t.name,...e,...t.args].join(" ")}function Zf(t,e=Math.max(...t.map(([n])=>n.length))){return t.map(([n,r])=>` ${n.padEnd(e)} ${r}`)}var Fw=["tab","catalog","setup"];function Do(t){if(t){let i=Object.entries(t.flags??{}).map(([o,{short:s,value:c,about:u}])=>[`${s?`-${s}, `:""}--${o}${c?` ${c}`:""}`,u]);return[`Usage: ttheme ${Bo(t)}`,"",t.about,...i.length>0?["","Options:",...Zf(i)]:[]].join(`
217
- `)}let e=qf.filter((i)=>!i.hidden),n=(i)=>e.filter((o)=>o.section===i).map((o)=>[Bo(o),o.about]),r=Math.max(...e.map((i)=>Bo(i).length));return["Usage: ttheme <command>","",ie.description,"","Commands:",...Fw.flatMap((i,o)=>[...o>0?[""]:[],...Zf(n(i),r)]),"","Examples:"," npx @kecan0406/ttheme init -y wire the terminals found here, no prompts"," ttheme add homura madoka install two palettes"," ttheme use homura paint this tab with one"," ttheme list --json madoka the madoka series as JSON","","ttheme <command> --help describes one command · ttheme --version prints the version","https://kecan0406.github.io/ttheme"].join(`
218
- `)}async function _f(t){let e;try{let n=Iw(t);if(n.kind==="version")return console.log(ie.version),0;if(n.kind==="help"){if(n.code===0)console.log(Do(n.verb));else console.error(Do(n.verb));return n.code}if(e=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof qe)return console.error(`ttheme${n.verb?` ${n.verb.name}`:""}: ${n.message}
481
+ }`;async function Al(){if(mu())return;if(process.platform==="darwin"){let[e="",n=""]=(await In("osascript",["-l","JavaScript","-e",vb])).stdout.trim().split("\t");return{stamp:e,picture:n==="picture"}}if(process.platform==="linux"&&!Pl()){let n=Boolean(process.env.WAYLAND_DISPLAY)?(await In("wl-paste",["--list-types"])).stdout:(await In("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:n,picture:/^image\//m.test(n)}}return}function Tl(e){let n=[],t="",r=0;while(r<e.length){if(e[r]!=="\x1B"){t+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let o=e.indexOf("\x1B[201~",r+6);if(o===-1)return{events:n,keys:t,pending:e.slice(r)};n.push({kind:"paste",text:e.slice(r+6,o)}),r=o+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let o=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((f)=>f!==-1);if(o.length===0)return{events:n,keys:t,pending:e.slice(r)};let s=Math.min(...o),u=e.slice(r+2,s),[c="",a="",...h]=u.split(";");n.push({kind:"osc",code:c,meta:Mb(a),payload:h.join(";")}),r=s+(e[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")n.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");n.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(e.slice(r+1)))return{events:n,keys:t,pending:e.slice(r)};t+=e[r],r++}return{events:n,keys:t,pending:""}}function Mb(e){let n={};for(let t of e.split(":")){let r=t.indexOf("=");if(r>0)n[t.slice(0,r)]=t.slice(r+1)}return n}var ai=(e)=>Buffer.from(e).toString("base64"),lu=(e)=>Buffer.from(e,"base64");function vl(e,n){return n.find((t)=>e.includes(t))}class pu{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=ai(Ml("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,n){this.send=e,this.deliver=n}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${fu.join(" ")}\x1B\\`;this.send(e)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${ai("ttheme")}:pw=${this.pw};${ai(".")}\x1B\\`)}take(e){if(e.code==="5522")this.clip(e.meta,e.payload);else if(e.code==="72")this.drop(e.meta,e.payload)}clip(e,n){if(e.type!=="read")return;let t=e.status??"";if(t==="OK"){if(this.reading??={mime:".",chunks:[],pw:e.pw??"",listing:!0},e.pw)this.reading.pw=e.pw;return}let r=this.reading;if(!r)return;if(t==="DATA"){if(r.mime=e.mime?lu(e.mime).toString("utf8"):r.mime,n)r.chunks.push(lu(n));return}if(this.reading=void 0,t!=="DONE"){this.deliver({kind:"error",message:t==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${t}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=vl(o,[...gu,...wb]);if(!s){this.deliver({kind:"text",text:""});return}let u=r.pw||this.pw,c=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:u,listing:!1},this.send(`\x1B]5522;type=read:name=${ai(c)}:pw=${u};${ai(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,n){let t=e.t??"";if(t==="m"){if(e.x==="-1"){this.offered=[];return}if(n){this.offered=n.split(" ").filter(Boolean);let u=fu.filter((c)=>this.offered.includes(c));this.send(`\x1B]72;t=m:o=${u.length>0?1:0};${u.join(" ")}\x1B\\`)}return}if(t==="M"){let u=n?n.split(" ").filter(Boolean):this.offered,c=vl(u,fu);if(!c){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:u,index:u.indexOf(c)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(t==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${n.split(":")[0]||"unknown error"}`});return}if(t!=="r"&&t!=="")return;if(n)r.chunks.push(lu(n));if(e.m==="1"||n)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let u=i.toString("utf8"),c=o==="text/uri-list"?Ro(u).find((a)=>ab(a)):void 0;s=c?{kind:"bytes",bytes:new Uint8Array(Oo(c)),source:c}:{kind:"text",text:u}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}var Ve={pitch:25,cols:22,rows:9,height:13},It={cols:25,rows:16},Ib=2147483648,Nb=-1073741826,Ob=1600,Rb="\x1B[0m",On="\x1B[1m",ge="\x1B[2m",hi="\x1B[31m",Nn="\x1B[32m",xe="\x1B[33m",Ho="\x1B[1;34m",Fb="\x1B[35m",Hb={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn",I:"focus-in",O:"focus-out"};function jl(e){let n=[],t=0;while(t<e.length){let r=e[t]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(t+1));if(i){n.push(Hb[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),t+=1+i[0].length;continue}let o=e[t+1]??"";if(/^[a-z]$/.test(o)){n.push(`alt-${o}`),t+=2;continue}n.push("esc"),t++;continue}n.push(r==="\r"||r===`
482
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),t++}return n}var Jl="\x1B]1337;ReportCellSize\x07\x1B[16t",Gl="\x1B]1337;ReportCellSize=";function $u(e){let n=e.indexOf(Gl);if(n!==-1){let i=e.slice(n+Gl.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:e.slice(0,n)+i.slice(s+(i[s]==="\x07"?1:2))}}}let t=e.indexOf("\x1B[6;"),r=t===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(t+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,t)+e.slice(t+1+r[0].length)}}function nr(e,n){return{perRow:Math.max(1,Math.floor((e+1)/Ve.pitch)),rowsVis:Math.max(1,Math.floor((n-4)/Ve.height))}}function Kl(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function Cl(e){return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function Wl(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function _l(e){return`\x1B[38;2;${Ue(e).join(";")}m`}function wu(e){return`\x1B[48;2;${Ue(e).join(";")}m`}function cn(e){return Array.from(e).length}class Po{parts=[];cols;constructor(e){this.cols=e}put(e,n,t=""){return this.parts.push({col:e,text:n,sgr:t}),e+cn(n)}run(e,n){let t=e;for(let[r,i]of n)t=this.put(t,r,i);return t}right(e,n){this.run(e-n.reduce((t,[r])=>t+cn(r),0),n)}render(){let e="";for(let{col:n,text:t,sgr:r}of this.parts){if(n>=this.cols||n<0)continue;let i=Array.from(t).slice(0,this.cols-n).join("");e+=`\x1B[${n+1}G${r}${i}${r?Rb:""}`}return e}}function Ql(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Pb(e,n){if(!n)return Ql(e);return n>=1e6?`${(e/1e6).toFixed(1)}/${(n/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(n/1000)} KB`}function ql(e){return e.replace(/_\([^)]*\)?$/,"")}function Zl(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<Ob?xe:ge]}function fi(e,n,t,r){let i=[...r.keys??[]],o=r.lead,s=r.right,u=()=>{let h=[...o?[cn(o[0])]:[],...i.map(([l,g])=>cn(l)+1+cn(g))];return(r.badge?cn(r.badge)+4:0)+h.reduce((l,g)=>l+g,0)+3*Math.max(0,h.length-1)+(s?3+cn(s[0])+1+cn(s[1]):0)};while(u()>n)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()>n){let h=Math.max(0,cn(o[0])-(u()-n)-1);o=[`${Array.from(o[0]).slice(0,h).join("")}…`,o[1]]}let c=0;if(r.badge)c=e.put(0,` ${r.badge} `,`\x1B[7;1m${t}`)+2;if([...o?[[o]]:[],...i.map(([h,f])=>[[h,On],[` ${f}`,ge]])].forEach((h,f)=>{c=e.run(c+(f?3:0),h)}),s)e.right(n,[[s[0],On],[` ${s[1]}`,ge]])}function Lb(e,n,t,r,i,o){let{ansi:s,selection:u,cursor:c}=o.colors,a=r<44?3:4;if(r>=56)a=Math.min(7,Math.floor((r+1)/8)-1);let h=t;for(let m=0;m<8;m++)h=(e[n]?.put(h,"▀".repeat(a),_l(s[m]??c)+wu(s[m+8]??c))??h)+1;let f=["❯ ",Nn],l=[[["~/code/demo",Ho],[" on ",ge],["main",Fb],[" +2",Nn],[" ~1",xe]]];if(l.push([f,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",Nn],["...",""],["origin/main",hi],[" [ahead 1]",xe]]);if(l.push([[" M",hi],[" src/main.rs",""]]),l.push([["??",hi],[" notes.md",""]]),l.push([]),r>=44)l.push([f,["ls",""]]),l.push([["docs",Ho],[" ",""],["src",Ho],[" ",""],["tests",Ho],[" Cargo.toml README.md",""]]),l.push([]);l.push([f,["cargo test",""]]),l.push([[" ✓",Nn],[" parses config",""]]);let g=[[" ✗",hi],[" renders frame",""]];if(r>=44)g.push([" expected ",ge],["3",Nn],[", received ",ge],["2",hi]);l.push(g),l.push([]),l.push([f,["echo ",""],["selected text",wu(u)],[" ",""],[" ",wu(c)]]),l.forEach((m,d)=>{let $=n+2+d;if($<=i)e[$]?.run(t,m)})}function Ab(e,n,t,r,i,o){e[n]?.put(t,`╭${"─".repeat(i-2)}╮`,o);for(let s=n+1;s<n+r-1;s++)e[s]?.put(t,"│",o),e[s]?.put(t+i-1,"│",o);e[n+r-1]?.put(t,`╰${"─".repeat(i-2)}╯`,o)}function bu(e,n=e.site,t=e.siteAnsi){return[` ${n} `,`\x1B[7;${30+t}m`]}function Tb(e){return`${x[Math.floor(e/Hn)]?.name??"local"} ${e%Hn}`}function Gb(e,n,t){let r=[{name:"all",moved:!1},...x].flatMap((s,u)=>{let c=`${s.name}${s.moved?"*":""}`,a=s.name===t.site?bu(t,c):[` ${c} `,ge];return u?[[" ",""],a]:[a]}),i=r.reduce((s,[u])=>s+cn(u),0)<=n,o=e.run(0,i?r:[bu(t)]);if(t.asking!==void 0)e.run(o,[[` ${t.asking} was cut off — this network may block it. turn on the unblock proxy? `,xe],["y",On],[" turn on ",ge],["n",On],[" not now",ge]])}function Ub(e,n,t,r){if(t.editing!==void 0){let u=e.run(0,[["⌕ ",r],[t.editing,""],["█",r]]),c=t.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,t.editing?c:` a tag, a post url or an id, or drop a picture or ctrl+v — ${t.tag||"esc leaves"}`,ge);return}let i=e.run(0,[["⌕ ",r],[t.tag||"nothing yet — / searches, ctrl+v pastes a picture",t.tag?"":ge]]),o=at.filter((u)=>!t.block.includes(u)),s=[t.preset,...t.solo?["solo"]:[],t.order,...t.rating.join("+")==="safe"?[]:[t.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...t.unblocked?["unblock"]:[]];if(e.put(i,` ${s.join(" ")}`,ge),t.total>0||!t.searching){let u=[[`${t.tiles.length}/${t.checked}`,""]];if(t.checked<t.total)u.push([` of ${t.total}`,ge]);e.right(n,u)}}function jb(e){if(e.cut==="on")return[[`cut out · ${e.clear}% transparent`,Nn]];if(e.cut==="off")return[["opaque · x cuts out",xe]];if(e.cut==="failed")return[["opaque · no cut-out",xe]];return[e.clear>0?[`${e.clear}% transparent`,Nn]:["opaque",xe]]}function Ul(e){return e.site==="all"?"any site":e.site}function Yl(e){if(e.installing!==void 0)return[`installing ${e.palette} ← ${Tb(e.installing)}`,xe];if(e.hint)return[e.hint,Nn];if(e.error)return[e.error,xe];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,xe];if(e.fetching)return[`fetching ${e.fetching.id%Hn} · ${Pb(e.fetching.got,e.fetching.size)}`,xe];if(e.cutting!==void 0)return[`cutting out ${e.cutting%Hn}`,xe];if(e.preparing!==void 0)return[`preparing ${e.preparing%Hn}`,xe];if(e.saved)return[e.saved,Nn];if(e.note)return[e.note,ge];return}function Jb(e,n,t,r,i,o){let{perRow:s,rowsVis:u}=nr(t,r);Ub(e[0],t,i,o),Gb(e[1],t,i);for(let g=0;g<s*u;g++){let m=i.top*s+g,d=i.tiles[m];if(!d)break;let $=2+Math.floor(g/s)*Ve.height,y=g%s*Ve.pitch,N=m===i.focus;if(N)Ab(e,$,y,Ve.height,Ve.pitch-1,o);if(d.thumb)n.push({id:d.key,path:d.thumb,row:$+1,col:y+1,cols:Ve.cols,rows:Ve.rows,z:-1});if(e[$+10]?.run(y+1,[...i.installed.includes(d.key)?[["✓ ",Nn]]:[],...i.site==="all"?[["● ",`\x1B[${30+d.siteAnsi}m`]]:[],[String(d.id),N?On:""],[" ",""],Zl(d)]),d.mates.length>0)e[$+10]?.put(y+Ve.cols,"≈",o);let E=d.artist?ql(d.artist):d.owner&&`@${d.owner}`;if(E)e[$+11]?.put(y+1,E.slice(0,Ve.cols-8),ge);let v=[];if(d.score>0)v.push([`★${d.score}`,ge]);if(d.variants>1)v.push([` ×${d.variants}`,o]);if(v.length>0)e[$+11]?.right(y+Ve.cols+1,v)}let c=i.top*s,a=i.tiles.length-(i.top+u)*s,h=[...c>0?[`↑ ${c} above`]:[],...a>0?[`↓ ${a} more`]:[]];if(h.length>0)e[r-2]?.put(0,h.join(" "),ge);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Ul(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Ul(i)} — tab tries ${i.nextSite}`,ge);let f=e[r-1],l=Yl(i);if(i.searching&&i.tiles.length===0&&!l){fi(f,t,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ge],right:["esc","back"]});return}fi(f,t,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Kb(e,n,t,r,i,o){let s=i.tiles[i.focus];if(!s)return;let u=i.shown?.id===s.key?i.shown:void 0,c=[bu(i,s.site,s.siteAnsi),[" ",""],[String(s.id),On],[" ",""],Zl(s)];if(s.artist)c.push([` · ${ql(s.artist)}`,""]);if(s.score>0)c.push([` · ★${s.score}`,ge]);if(u)c.push([` · ${Ql(u.bytes)}`,ge]);if(s.owner)c.push([` · ${s.owner}`,ge]);if(s.origin)c.push([` · ${s.origin}`,ge]);if(u)c.push([" ",""],...jb(u));if(e[0]?.run(0,c),s.mates.length>0)e[0]?.right(t,[["≈ ",o],[s.mates.join(" "),ge]]);if(Lb(e,3,2,t-4,r-2,i),i.shown)n.push({id:Ib+i.shown.id,path:i.shown.path,row:0,col:0,cols:t,rows:r,z:Nb});let a=Yl(i);fi(e[r-1],t,o,{badge:"TRY",lead:a,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 Cb={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${x.map((e)=>e.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["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"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function Wb(e,n,t,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),u=Math.max(...r.settings.map((l)=>l.choices.reduce((g,m)=>g+m.length+(l.multi?6:3),0))),c=Math.min(n-2,Math.max(28,s+u+8)),a=r.settings.length+4,h=Math.floor((n-c)/2),f=Math.max(2,Math.floor((t-a)/2));e[f]?.put(h,`╭─ settings ${"─".repeat(Math.max(0,c-13))}╮`);for(let l=f+1;l<f+a-1;l++)e[l]?.put(h,`│${" ".repeat(c-2)}│`);r.settings.forEach((l,g)=>{let m=e[f+2+g];m.put(h+3,l.label,g===o?On:ge);let d=h+5+s,$=l.value.split(" ");l.choices.forEach((y,N)=>{let E=$.includes(y),v=l.multi&&g===o&&N===l.cursor?"4;":"",p=l.multi?` ${E?"[x]":"[ ]"} ${y} `:` ${y} `;d=m.put(d,p,E?`\x1B[${v}7;${30+r.siteAnsi}m`:v?`\x1B[4m${ge}`:ge)+1})}),e[f+a-1]?.put(h,`╰${"─".repeat(c-2)}╯`),fi(e[t-1],n,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function _b(e,n,t,r,i){let o=Cb[r.mode],s=Math.min(n-2,50),u=o.length+4,c=Math.floor((n-s)/2),a=Math.max(2,Math.floor((t-u)/2));e[a]?.put(c,`╭─ keys ${"─".repeat(s-9)}╮`);for(let h=a+1;h<a+u-1;h++)e[h]?.put(c,`│${" ".repeat(s-2)}│`);o.forEach(([h,f],l)=>{e[a+2+l]?.put(c+3,h,On),e[a+2+l]?.put(c+13,f.slice(0,s-16))}),e[a+u-1]?.put(c,`╰${"─".repeat(s-2)}╯`),fi(e[t-1],n,i,{badge:"KEYS",right:["? esc","close"]})}function Qb(e,n,t){let r=n.suggest??[],i=r.map((u)=>u.count>0?String(u.count):u.palette??"0"),o=Math.max(...r.map((u)=>cn(u.value))),s=Math.max(7,...i.map(cn));r.forEach((u,c)=>{let a=c===n.pick,h=e[1+c];h?.run(0,[[a?"▸ ":" ",t],[u.value,a?On+t:""]]),h?.right(2+o+2+s,[[i[c],ge]])})}function Xl(e,n,t){let r=Array.from({length:t},()=>new Po(n)),i=[],o=_l(e.colors.cursor);if(n<It.cols||t<It.rows)return r[0]?.put(0,"ttheme find",On+o),r[1]?.put(0,`needs ${It.cols}×${It.rows} — now ${n}×${t}`),r[2]?.put(0,"esc quits",ge),{lines:r.map((s)=>s.render()),images:i};if(e.mode==="try")Kb(r,i,n,t,e,o);else Jb(r,i,n,t,e,o);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let s=1;s<t-1;s++)r[s]=new Po(n);return Qb(r,e,o),{lines:r.map((s)=>s.render()),images:[]}}if(e.help||e.panel!==void 0){let s=e.mode==="try"?i:[];for(let u=0;u<t;u++)r[u]=new Po(n);if(e.help)_b(r,n,t,e,o);else Wb(r,n,t,e,o);return{lines:r.map((u)=>u.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var qb=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Zb=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),Yb=0.04,Xb=0.1,Vb=0.05,zb=4096;function Bb(e){return new Set(e.cutouts.split(/\s+/).map((n)=>n.replace(/^~/,"")).filter(Boolean))}function Db(e,n,t,r=0){let{site:i,post:o}=e,s=new Set(o.tags),u=[...Bb(i)].some((h)=>s.has(h)),c=Math.min(o.width,o.height),a=o.width>0&&o.height>0?o.width/o.height/(n.w/n.h):1;return(o.solo?2:0)+([...qb].some((h)=>s.has(h))?-3:0)+([...Zb].some((h)=>s.has(h))?-1.5:0)+2*Math.min(1,c/n.h)+(u?1.5:-Math.min(1.5,Math.abs(Math.log(a))))+(t>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(t):0)+2*r}function Lo(e,n,t=new Map){let r=new Map;for(let{site:i,post:o}of e)r.set(i,Math.max(r.get(i)??0,o.score));return e.map((i,o)=>({pick:i,at:o,score:Db(i,n,r.get(i.site)??0,t.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function zl(e){let n=new Map;for(let r of e)n.set(r.site,[...n.get(r.site)??[],r]);let t=[];for(let r=0;t.length<e.length;r++)for(let i of n.values()){let o=i[r];if(o)t.push(o)}return t}function ku(e){let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4}function Vl(e,n,t){let[r,i,o]=[ku(e),ku(n),ku(t)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),u=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*u-0.0040720468*c,1.9779984951*s-2.428592205*u+0.4505937099*c,0.0259040371*s+0.7827717662*u-0.808675766*c]}function Bl(e,n){let t=n.map((s)=>Vl(...Ue(s))).filter(([,s,u])=>Math.hypot(s,u)>=Yb);if(t.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/zb))),i=t.map(()=>0),o=0;for(let s=0;s<e.height;s+=r)for(let u=0;u<e.width;u+=r){let c=(s*e.width+u)*4;if(e.data[c+3]<128)continue;o++;let[a,h,f]=Vl(e.data[c],e.data[c+1],e.data[c+2]);t.forEach(([l,g,m],d)=>{if(Math.hypot(a-l,h-g,f-m)<Xb)i[d]=i[d]+1})}if(o===0)return 0;return i.reduce((s,u)=>s+Math.min(1,u/o/Vb),0)/t.length}import{mkdirSync as tg,readFileSync as rg,writeFileSync as ig}from"node:fs";import{dirname as og}from"node:path";import{isMainThread as t$,parentPort as sg,Worker as r$}from"node:worker_threads";var xb=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,e$=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Eu(e){let n=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...n&&e.source.includes("pximg")?[`pixiv:${n[1]}_p${n[2]}`]:[]]}function Dl(e,n){let t=xb.exec(n.source)?.[1]?.toLowerCase();return[`post:${e.key}:${n.id}`,...n.md5?[`md5:${n.md5}`]:[],...t&&t!==n.md5?[`md5:${t}`]:[],...e$.flatMap(([r,i])=>{let o=r.exec(n.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...n.family?[`family:${e.key}:${n.family}`]:[]]}function xl(e,n){let t=e.owner||e.artist;return t!==""&&t===(n.owner||n.artist)&&e.width===n.width&&e.height===n.height}function eg(e){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*e.height/8),u=Math.max(s+1,Math.floor((o+1)*e.height/8));for(let c=0;c<9;c++){let a=Math.floor(c*e.width/9),h=Math.max(a+1,Math.floor((c+1)*e.width/9)),f=0;for(let l=s;l<u;l++)for(let g=a;g<h;g++){let m=(l*e.width+g)*4,d=e.data[m+3]/255,$=0.299*e.data[m]+0.587*e.data[m+1]+0.114*e.data[m+2];f+=$*d+255*(1-d)}r.push(f/((h-a)*(u-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function n$(e,n){let t=BigInt(`0x${e}`)^BigInt(`0x${n}`),r=0;while(t>0n)r+=Number(t&1n),t>>=1n;return r}function ng(e,n){if(e.width<=0||e.height<=0||n.width<=0||n.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(n.width/n.height)))<0.01&&n$(e.hash,n.hash)<=2}var i$={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function o$(e){let n=vr(new Uint8Array(rg(e.from)),Sn);if(e.job==="backdrop")return qi(e.home,e.colors,e.tone,n,{...e.origin,bytes:new Uint8Array(rg(e.source))},e),0;if(e.job==="match")return{match:Bl(n,e.colors),hash:eg(n)};if(e.job==="thumb")return tg(og(e.to),{recursive:!0}),ig(e.to,ut(wa(n,e.width,e.height))),0;let t=_n(n);return tg(og(e.to),{recursive:!0}),ig(e.to,ut(gh(n,e.colors,e.tone,e.width,e.height))),t}function s$(e){e.on("message",(n)=>{try{e.postMessage({id:n.id,value:o$(n)})}catch(t){e.postMessage({id:n.id,error:t instanceof Error?t.message:String(t)})}})}class ug{worker;next=1;waiting=new Map;send(e){let n=this.next++;return new Promise((t,r)=>{let i=this.open();this.waiting.set(n,{ok:t,no:r}),i.ref(),i.postMessage({...e,id:n})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new r$(import.meta.filename);e.unref(),e.on("message",({id:t,value:r,error:i})=>{let o=this.waiting.get(t);if(this.waiting.delete(t),this.waiting.size===0)e.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let n=(t)=>{if(this.worker===e)this.worker=void 0;this.drop(t instanceof Error?t:Error("renderer stopped"))};return e.on("error",n),e.on("exit",()=>n(void 0)),this.worker=e,e}drop(e){for(let n of this.waiting.values())n.no(e);this.waiting.clear()}}class Su{lines=new Map;run(e){let n=i$[e.job],t=this.lines.get(n);if(!t)t=new ug,this.lines.set(n,t);return t.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}if(!t$&&sg)s$(sg);var rr=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Or,multi:{read:jt}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:at,multi:{read:Jt,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 l$(e,n){if(e.multi)return e.multi.read(n).join(" ")||e.multi.none;return e.choices.find((t)=>t===n)??e.choices[0]}var g$=["fit","newest","score"];function cg(e){return g$.find((n)=>n===e)??"fit"}function d$(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var ag=12,m$=4,p$=150,hg=12,w$=2,b$=150,$$=30,k$=4000,E$=8000,fg=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,S$=process.platform==="win32"?"alt+v":"ctrl+v",lg=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",y$=1280,gg=2,v$=3,M$=8;function To(e,n){return{key:e,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:n}}function ir(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return ir(e.errors[0]);if(e.cause)return ir(e.cause);let n=e.code;if(typeof n==="string")return n;let t=(e.message||e.name).split(".")[0]??"";return t.length>56?`${t.slice(0,55)}…`:t}function vu(e,n){return`${e}: ${ir(n)}`}function dg(e){return e.width*e.height}function mg(e){return`${e.id}-${pg("sha1").update(e.preview).digest("hex").slice(0,8)}`}function I$(e){let n=e.lastIndexOf("\x1B");return n!==-1&&/^\[?[0-9;]*$/.test(e.slice(n+1))}function Mu(e,n){try{return JSON.parse(wg(Rn(gn(e),n),"utf8"))}catch{return{}}}function Iu(e,n,t){li(gn(e),{recursive:!0}),gi(Rn(gn(e),n),`${JSON.stringify(t)}
483
+ `)}class bg{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(rr.map((e)=>[e.name,l$(e,process.env[e.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 Su;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new pu((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=c$(Rn(h$(),"ttheme-find-"));home;catalog;entry;constructor(e,n,t,r){this.home=e,this.catalog=n,this.entry=t,this.tone=Qt(t,t.signatureSlots),this.view={palette:t.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:cg(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:jt(this.setting("TTHEME_FIND_RATING")),block:Jt(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:rr.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:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=To(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:x[this.tab-1]}get sites(){return this.site?[this.site]:x}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??m$}get nextTabName(){let e=(this.tab+1)%(x.length+1);return e===0?"all":x[e-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(e){return this.values.get(e)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,n,t){return Rn(gn(e),"orig",`${n}.${t}`)}previewPath(e){return Rn(gn(e.site),"thumb",`${mg(e.post)}.${Rr(e.post.preview)}`)}tileOf(e,n){let{site:t,post:r}=e,i=yn(t,r.id),o=ht(r)??r;return{id:r.id,key:i,site:t.name,siteAnsi:t.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:t===Fo?Rl(r.source):r.artist,score:r.score,variants:n,origin:ms(r.source),mates:this.owners.get(t.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let e=this.view,n=this.board;e.tiles=n.groups.flatMap((t)=>t.open?t.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(t.posts[0],t.posts.length)]),e.checked=n.checked,e.total=n.total,e.searching=n.searching,e.note=n.note,e.focus=Math.max(0,Math.min(n.focus,e.tiles.length-1)),e.top=n.top}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:n}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),n.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}),r=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";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await t;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),e.off("data",this.onData),n.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),e.setRawMode(!1),e.pause(),this.saveProbes(),this.renders.close(),yu(this.scratch,{recursive:!0,force:!0}),Pa(),o}write(e){process.stdout.write(e)}get saved(){return this.view.saved}finish(e){this.done?.(e===2&&this.saved?0:e)}probe(){return new Promise((e)=>{let n=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(t)=>{clearTimeout(n),this.probeWait=void 0,e(t)},this.write(Jl)})}onData=(e)=>{this.input+=e.toString("utf8");for(let t=$u(this.input);t;t=$u(this.input))this.input=t.rest,this.probeWait?.(t.cell);if(this.probeWait)return;let n=Tl(this.input);if(this.input=n.pending,this.view.editing===void 0&&n.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(n.keys))this.pasted(n.keys),n.keys="";this.typed+=n.keys;for(let t of n.events)this.inbound(t);if(clearTimeout(this.partial),I$(this.typed)){this.partial=setTimeout(this.flushKeys,$$);return}this.flushKeys()};flushKeys=()=>{let e=jl(this.typed);this.typed="";for(let n of e)this.key(n)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let n=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(n),this.featureWait=void 0,e()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(e){if(e.kind==="mode"){if(e.mode===5522)this.grabber.clipboard=e.value!==0&&e.value!==4;return}if(e.kind==="attributes"){this.featureWait?.();return}if(e.kind==="osc"){if(e.code==="72"&&e.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(e);return}this.pasted(e.text)}pasted(e){let n=this.view;if(n.editing!==void 0&&e.trim()!==""&&!this.picture(e)){n.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(n.installing!==void 0||n.asking!==void 0||n.panel!==void 0||n.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let n=e.trim();if(/^https?:\/\/\S+$/i.test(n))return!Gi(n,this.site??x[0]);return Ro(n).length>0}async got(e){if(e.kind==="error"){this.notice(e.message);return}if(e.kind==="text"){if(e.text.trim()===""){this.notice(`no picture on the clipboard — ${lg}`);return}this.pasted(e.text);return}await this.bring(()=>No(e.bytes,e.source))}notice(e,n=k$){let t=this.view;t.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(t.error===e)t.error=void 0,this.draw()},n),this.draw()}async peek(){let e=this.view,n;try{n=await Al()}catch{return}if(!n||n.stamp===this.peeked)return;if(this.peeked=n.stamp,!n.picture||e.installing!==void 0||e.asking!==void 0)return;e.hint=`picture on the clipboard · ${S$} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},E$),this.draw()}async fromClipboard(){let e=this.view;if(mu()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let n;try{n=await Ll(Rn(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${ir(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in n){await this.bring(async(r)=>({...await du(n.image,r),source:"clipboard"}));return}let t=n.text.trim();if(!t){this.notice(`no picture on the clipboard — ${lg}`);return}if(this.picture(t)){await this.attach(t);return}if(e.editing===void 0)e.editing="";this.pasted(t)}async attach(e){let n=e.trim();if(/^https?:\/\//i.test(n)){let i=Gi(n,this.site??x[0]);if(i){await this.jump(i.site,i.id);return}}let[t,...r]=Ro(n).sort((i,o)=>Number(!fg.test(i))-Number(!fg.test(o)));if(!t){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>du(t,i),r.length)}async bring(e,n=0){let t=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,t.error=void 0,t.saved=void 0,t.note="reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)t.note=void 0,this.notice(ir(l),8000);return}if(r.signal.aborted)return;t.note=n>0?`the first picture of ${n+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),t.editing=void 0,t.suggest=void 0,t.pick=void 0;let o=Hl(i.bytes);Fl(o,i.source);let s=this.origPath(Fo,o,i.ext);li(Ao(s),{recursive:!0}),gi(s,i.bytes);let u=f$(s).href,c={id:o,file:u,width:i.width,height:i.height,ext:i.ext,preview:u,owner:"",artist:"",score:0,rating:"s",md5:pg("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},a={site:Fo,post:c},h=this.previewPath(a);li(Ao(h),{recursive:!0}),gi(h,i.bytes),++this.gen,this.current=void 0,t.shown=void 0;let f=To(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,a)}single(e,n){e.searching=!1,this.posts.set(yn(n.site,n.post.id),n),e.groups=[{posts:[n],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(n),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>Qn(i)>Qn(r)?i:r),n=Math.ceil((Qn(e)-Date.now())/1000),t=n>0?n:void 0;if(t!==this.view.waiting)this.view.waiting=t,this.view.slow=e.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(e){let n=this.view;if(e==="ctrl-c"){this.finish(2);return}if(n.installing!==void 0)return;if(n.asking!==void 0){this.askKey(e);return}if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&n.panel===void 0){this.fromClipboard();return}if(n.editing!==void 0){this.editKey(e);return}if(n.panel!==void 0){this.panelKey(e);return}if(n.help){if(e==="?"||e==="esc")n.help=!1,this.draw();return}if(this.cols<It.cols||this.rows<It.rows){if(e==="esc")this.finish(2);return}if(e==="?"){n.help=!0,this.draw();return}if(n.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let n=this.view,{perRow:t,rowsVis:r}=nr(this.cols,this.rows),o={left:-1,right:1,up:-t,down:t,pgup:-t*r,pgdn:t*r,home:-n.focus,end:n.tiles.length}[e];if(o!==void 0){this.focus(n.focus+o);return}if(e==="enter"&&n.tiles[n.focus]){n.mode="try",n.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){n.preset=n.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(x.length+1),this.syncSite(),this.turn();return}if(e==="/"){n.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){n.panel=0,this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let n=this.view,t=n.panel??0,r=n.settings[t];if(e==="up"||e==="down"){n.panel=Math.max(0,Math.min(n.settings.length-1,t+(e==="up"?-1:1))),this.draw();return}if((e==="left"||e==="right")&&r){let i=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(e===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!i.includes(u):i.includes(u)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(e==="esc"){n.settings.forEach((i,o)=>{i.value=this.setting(rr[o]?.name??"")}),n.panel=void 0,this.draw();return}if(e==="enter"||e==="alt-c")n.panel=void 0,this.adopt()}adopt(){let e=this.view,n=rr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let o=rr[i];if(o)this.values.set(o.name,r.value)});let t=rr.filter((r,i)=>this.setting(r.name)!==n[i]);if(t.length===0){this.draw();return}this.save(t),e.rating=jt(this.setting("TTHEME_FIND_RATING")),e.block=Jt(this.setting("TTHEME_FIND_BLOCK")),e.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",e.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",e.order=cg(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((n)=>[n.name,this.setting(n.name)]))}store(e){let n=Rn(this.home,"ttheme","config.zsh");try{let t=tr(n)?wg(n,"utf8"):"";return gi(n,e.reduce((r,[i,o])=>Hh(r,i,o),t)),!0}catch(t){return this.view.error=t instanceof Error?t.message:String(t),!1}}askKey(e){let n=this.view;if(e==="y"){if(n.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(e==="n"||e==="esc")n.asking=void 0,this.draw()}editKey(e){let n=this.view,t=n.editing??"",r=n.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=n.pick??-1,o=e==="down"?Math.min(r.length-1,i+1):i-1;n.pick=o<0?void 0:o,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(n.editing=void 0,n.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=n.pick===void 0?void 0:r[n.pick],o=i?t.replace(/\S*$/,i.value):t;if(n.editing=void 0,n.suggest=void 0,n.pick=void 0,o.trim()){this.commit(o.trim());return}if(n.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){n.editing=t.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")n.editing=t+e,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let e=this.view;e.pick=void 0;let n=/\S*$/.exec(e.editing??"")?.[0]??"";if(!d$(n)){e.suggest=void 0;return}let t=[...new Map(_f(this.catalog.palettes,this.entry,n).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,v$);e.suggest=t.length>0?t:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Ua(n,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let o=new Map(i.map((u)=>[u.value,u.count])),s=new Set(t.map((u)=>u.value));e.suggest=[...t.map((u)=>({...u,count:o.get(u.value)??0})),...i.filter((u)=>!s.has(u.value))].slice(0,M$),e.pick=e.pick!==void 0&&e.pick<t.length?e.pick:void 0,this.draw()}}catch{}},p$)}async commit(e){let n=Gi(e,this.site??x[0]);if(n){await this.jump(n.site,n.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,n){let t=++this.gen;this.tab=x.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=To(`${e.key}|post:${n}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Hr(e,n,this.signal);if(t!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${n}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(t,i,e)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let e=this.boards.get(this.boardKey);if(!e){await this.search();return}this.gen++,this.board=e,this.view.error=e.error,this.show(),this.draw(),await this.pump()}unfold(){let e=this.view,n=0;for(let t of this.board.groups){let r=t.open?t.posts.length:1;if(e.focus<n+r){if(t.posts.length<2)return;t.open=!t.open,this.board.focus=n;for(let i of t.posts)if(!this.thumbPath.has(yn(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}n+=r}}openPage(){let e=this.view.tiles[this.view.focus],n=e&&this.posts.get(e.key);if(!n)return;let t=process.platform==="darwin"?"open":"xdg-open";try{u$(t,[n.site.pageUrl(n.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let n=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(n.focus+this.direction);return}if(e==="o"){this.openPage();return}if(e==="x"){this.swap();return}if(e==="v"){this.fromClipboard();return}if(e==="enter"){this.install();return}if(e==="esc")this.fetch?.abort(),clearTimeout(this.settle),n.fetching=void 0,n.mode="grid",n.error=void 0,this.draw()}focus(e){let n=this.view;if(n.tiles.length===0)return;let t=Math.max(0,Math.min(n.tiles.length-1,e));if(t===n.focus)return;if(n.focus=t,this.board.focus=t,this.scroll(),this.pump(),n.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:n,rowsVis:t}=nr(this.cols,this.rows),r=Math.floor(e.focus/n);if(r<e.top)e.top=r;if(r>e.top+t-1)e.top=r-t+1;this.board.top=e.top}query(e){let n=this.view,t=n.tag===this.entry.booru?Qf(this.entry,e.key):[n.tag];if(t.length===0)return;let r=t.length>1,i=n.preset==="cutouts"?e.cutouts:"",o=r&&i.includes("~"),s=[r?t.map((a)=>`~${a}`).join(" "):t[0],e.rate(this.view.rating),o?"":i,n.order==="score"?e.best:""].filter(Boolean),u=[],c=[];for(let a of s)if(ds([...u,a].join(" "))<=e.tagBudget)u.push(a);else c.push(a);return{tags:u.join(" "),notes:[...c.length>0?[`${e.name} takes ${e.tagBudget} tags — ${c.join(" ")} left out`]:[],...o?[`${e.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let e=++this.gen,n=To(this.boardKey,!0);this.board=n,this.boards.set(n.key,n),this.view.error=void 0;let t=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!t.some((s)=>s.site===o)),i=[...t.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(n.note=i.length>0?i.join(" · "):void 0,t.length===0)n.searching=!1;this.show(),this.draw(),this.tally(e,n,t);try{let o=await Promise.all(t.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(e!==this.gen)return;n.sources=o.flatMap(({plan:{site:s,tags:u},owners:c})=>[...ds(u)+1<=s.tagBudget?[...c.keys()].map((a)=>({site:s,tags:`${u} user:${a}`,page:0,done:!1})):[],{site:s,tags:u,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(e,o)}}async tally(e,n,t){let r=await Promise.allSettled(t.map(({site:i,tags:o})=>Aa(i,o,this.signal)));if(e===this.gen)n.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(e,n,t=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=vu(t?.name??this.tabName,n),this.board.searching=!1,this.view.error=this.board.error,this.offer(t,n),this.show(),this.draw()}offer(e,n){if(e&&!this.view.unblocked&&si()&&ir(n)==="ECONNRESET")this.view.asking=e.name}drop(e,n,t){for(let r of e.sources)if(r.site===n)r.done=!0;e.note=[e.note,vu(n.name,t)].filter(Boolean).join(" · "),this.offer(n,t)}wants(){let{perRow:e,rowsVis:n}=nr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+n+gg)*e}need(){let{perRow:e,rowsVis:n}=nr(this.cols,this.rows);return(n+gg)*e}live(e){return this.boards.get(e.key)===e}page(e,n,t){let r=`${e.key}|${n}|${t}`,i=this.pages.get(r);if(!i)i=La(e,n,t,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e){let n=e.filter((t)=>t.solo===void 0&&t.md5!=="");if(n.length>0)try{Ta(n,await Ga(n.map((t)=>t.md5),this.signal))}catch{}return e}async round(e){let n=x.flatMap((u)=>{let c=e.sources.find((a)=>a.site===u&&!a.done);return c?[c]:[]}),t=await Promise.all(n.map(async(u)=>{try{return{source:u,posts:await this.page(u.site,u.tags,u.page)}}catch(c){if(e.sources.every((a)=>a.site===u.site)||this.signal.aborted)throw c;return this.drop(e,u.site,c),{source:u,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:u,posts:c}of t){if(!c)continue;u.page++,u.done=c.length<ct;let a=e.last.get(u);for(let h of c){let f=a&&xl(a.post,h)?a.set:`set:${u.site.key}:${h.id}`;a={post:h,set:f};let l=yn(u.site,h.id);if(e.seen.has(l))continue;e.seen.add(l);let g={site:u.site,post:h};if(this.eligible(g))e.kin.set(g,[f,...Dl(u.site,h)]),r.push(g);else e.checked++}if(a)e.last.set(u,a)}let i=this.dedupe(e,r),o=++e.rounds,s;if(this.view.order!=="fit")s=n.length>1?zl(i):i;else{let u=Lo(i,this.frame(),this.matched),c=u.slice(0,this.need());if(await this.looks(c),!this.live(e))return;s=[...Lo(c,this.frame(),this.matched),...u.slice(c.length)]}for(let u of s)e.roundOf.set(u,o);e.queue.push(...s),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let n=e.queue.slice(0,this.need()).filter((t)=>!this.looking.has(yn(t.site,t.post.id)));if(n.length===0)return;this.aheading=!0,this.looks(n).then(()=>{this.aheading=!1;for(let t of new Set(n.map((r)=>e.roundOf.get(r)??0)))this.resort(e,t);this.ahead(e)})}resort(e,n){let t=e.queue.flatMap((i,o)=>e.roundOf.get(i)===n?[o]:[]),r=Lo(t.map((i)=>e.queue[i]),this.frame(),this.matched);t.forEach((i,o)=>{e.queue[i]=r[o]})}dedupe(e,n){let t=[];for(let r of n){let i=Eu(r.post),o=i.map((u)=>e.same.get(u)).find(Boolean);if(!o){for(let u of i)e.same.set(u,r);t.push(r);continue}if(e.checked++,dg(r.post)<=dg(o.post))continue;for(let u of[...i,...Eu(o.post)])e.same.set(u,r);let s=t.indexOf(o);if(s>=0){t[s]=r;continue}this.replace(e,o,r)}return t}replace(e,n,t){e.roundOf.set(t,e.roundOf.get(n)??0);let r=e.queue.indexOf(n);if(r>=0){e.queue[r]=t;return}for(let i of e.groups){let o=i.posts.indexOf(n);if(o>=0){i.posts[o]=t,this.posts.set(yn(t.site,t.post.id),t),this.thumbQueue.push(t),this.thumbs();return}}}async looks(e){let n=0;await Promise.all(Array.from({length:hg},async()=>{while(n<e.length)await this.look(e[n++])}))}look(e){let n=yn(e.site,e.post.id),t=this.looking.get(n);if(!t)t=(async()=>{let r=this.previewPath(e);await this.cached(e.site,r,e.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(n,i),this.matched.set(e.post,i.match),i})().catch(()=>{return}),this.looking.set(n,t);return t}async pump(){let e=this.gen,n=this.board;if(this.pumping===e||n.sources.length===0)return;this.pumping=e;let t=[],r;try{n.searching=!0;while(e===this.gen){while(t.length<ag&&n.queue.length>0&&this.wants()){let s=n.queue.shift();t.push({pick:s,passed:this.vet(s)})}if(this.ahead(n),!r&&n.queue.length<ag&&n.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(n).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=t.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(e!==this.gen)return;if(n.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)n.searching=!1,this.show(),this.draw()}catch(i){this.fail(e,i)}finally{if(this.saveProbes(),this.pumping===e)this.pumping=0}}eligible({site:e,post:n}){let t=ht(n);if(!ji(e,n,this.view.rating)||Ui(n,this.view.block).length>0||!t)return!1;if(this.view.solo&&n.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(t.ext):n.ext==="png"}async vet(e){let[n]=await Promise.all([this.passes(e),this.look(e)]);return n}async passes({site:e,post:n}){return this.view.preset==="all"||e.vouched||this.transparent(e,n)}probes(e){let n=this.probed.get(e.key);if(!n)n=Mu(e,"probes.json"),this.probed.set(e.key,n);return n}async transparent(e,n){let t=this.probes(e),r=t[n.id];if(r!==void 0)return r;try{let i=(await ja(e,n.file,this.signal))?.alpha===!0;return t[n.id]=i,this.unsaved.add(e.key),i}catch{return!1}}saveProbes(){for(let e of this.unsaved){let n=x.find((t)=>t.key===e);if(n)Iu(n,"probes.json",this.probes(n))}this.unsaved.clear()}admit(e){let{site:n,post:t}=e,r=this.board,i=yn(n,t.id);this.posts.set(i,e);let o=r.kin.get(e)??[],s=this.looked.get(i),u=s&&{hash:s.hash,width:t.width,height:t.height},c=this.view.sets==="fold"?this.kindred(r,o,u):void 0;if(c){if(c.posts.push(e),this.register(r,c,o,u),c.open)this.thumbQueue.push(e),this.thumbs();return}let a={posts:[e],open:!1};r.groups.push(a),this.register(r,a,o,u),this.thumbQueue.push(e),this.thumbs()}kindred(e,n,t){for(let r of n){let i=e.kindred.get(r);if(i)return i}return t&&e.shapes.find((r)=>ng(r.shape,t))?.group}register(e,n,t,r){for(let i of t)if(!e.kindred.has(i))e.kindred.set(i,n);if(r)e.shapes.push({shape:r,group:n})}async mateOwners(e){let n=this.owners.get(e.key);if(n)return n;let t=Eh(this.home),r=Mu(e,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let a=t.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&a?.site===e.key?[{name:c.name,id:a.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let a=r[c.id];if(a!==void 0)return{...c,owner:a};try{return{...c,owner:(await Hr(e,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)r[c.id]=c.owner,s.set(c.name,c.owner);Iu(e,"owners.json",r);let u=Ha(s);return this.owners.set(e.key,u),u}async cached(e,n,t,r){if(tr(n))return a$(n).size;let i=this.inflight.get(n);if(i)return i;let o=(async()=>{let s=await Ki(e,t,this.signal,r);return li(Ao(n),{recursive:!0}),gi(n,s),s.length})();this.inflight.set(n,o);try{return await o}finally{this.inflight.delete(n)}}thumbs(){while(this.thumbing<hg&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:n,post:t}=e,r=Ve.cols*this.cell.w,i=Ve.rows*this.cell.h,o=Rn(gn(n),"tile",`${mg(t)}-${r}x${i}.png`);if(!tr(o)){let s=this.previewPath(e);await this.cached(n,s,t.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(yn(n,t.id),o),this.show(),this.draw()}select(){let e=this.view,n=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!n)return;if(this.current?.key===n.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(n),b$),this.draw()}async load(e){let n=this.view,t=this.posts.get(e.key),r=t&&ht(t.post);if(!t||!r)return;let{site:i}=t,o=this.board,s=new AbortController;this.fetch=s;try{let u=this.origPath(i,e.id,r.ext);if(!tr(u))n.fetching={id:e.key,got:0,size:0},this.draw();let c=await this.cached(i,u,r.file,(f,l)=>{if(n.fetching?.id===e.key)n.fetching={id:e.key,got:f,size:l},this.draw()});if(s.signal.aborted)return;if(n.fetching=void 0,o!==this.board)return;let a={site:i,id:e.id,key:e.key,path:u,ext:r.ext,size:c,using:"plain",failed:!1};n.preparing=e.key,this.flush();let h=await this.render(a,"plain");if(s.signal.aborted||o!==this.board)return;if(h.clear===0&&oi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(n.preparing=void 0,n.cutting=e.key,this.flush(),a.cut=await this.cutOut(i,e.id,u,s.signal),s.signal.aborted||o!==this.board)return;if(n.cutting=void 0,a.cut){n.preparing=e.key,this.flush();let f=await this.render(a,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(f&&So(f.clear))a.using="cut";else yu(a.cut,{force:!0}),a.cut=void 0,a.failed=!0}else a.failed=!0}if(this.current=a,n.tiles[n.focus]?.key===e.key)await this.present();this.preload()}catch(u){if(!s.signal.aborted&&!this.signal.aborted)n.error=vu(i.name,u)}finally{if(n.fetching?.id===e.key)n.fetching=void 0;if(n.preparing===e.key)n.preparing=void 0;if(n.cutting===e.key)n.cutting=void 0;this.draw()}}async cutOut(e,n,t,r){let i=Rn(gn(e),"cut",`${n}.png`);if(tr(i))return i;try{return li(Ao(i),{recursive:!0}),await yo(t,i,r),i}catch{yu(i,{force:!0});return}}swap(){let e=this.current;if(!e?.cut||this.view.shown?.id!==e.key)return;e.using=e.using==="cut"?"plain":"cut",this.reveal()}preload(){let e=this.view;if(e.mode!=="try")return;for(let n of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=w$)return;let t=e.tiles[n],r=t&&this.posts.get(t.key),i=r&&ht(r.post);if(!r||!i)continue;let{site:o,post:s}=r,u=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,u,i.file).then(()=>this.render({site:o,id:s.id,key:t.key,path:u,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,n){let t=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(t,y$),o=Math.max(1,Math.round(r*i/t)),s=Rn(this.scratch,`${e.site.key}-${e.id}${n==="cut"?"c":""}-${i}x${o}.png`),u=`${e.site.key}:${e.id}:${n}`,c=this.clarity.get(u);if(c!==void 0&&tr(s))return{clear:c,path:s};let a=await this.renders.run({job:"show",from:n==="cut"?e.cut:e.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(u,a),{clear:a,path:s}}async present(){let e=this.current;if(!e)return;let n=e.using,{clear:t,path:r}=await this.render(e,n);if(this.current!==e||e.using!==n)return;this.view.shown={id:e.key,clear:t,bytes:e.size,path:r,cut:e.cut?n==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((n)=>{e.error=n instanceof Error?n.message:String(n)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,n=e.tiles[e.focus],t=this.current;if(!n||t?.key!==n.key||e.preparing!==void 0||e.shown?.id!==n.key)return;e.installing=n.key,e.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 r=Mu(t.site,"owners.json");r[t.id]=this.posts.get(t.key)?.post.owner??"",Iu(t.site,"owners.json",r),et(this.home),e.saved=`background · ${this.entry.name} ← ${t.site.name} ${t.id}`,e.installed.push(n.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(r){e.error=r instanceof Error?r.message:String(r)}e.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let e=Xl(this.view,this.cols,this.rows),n="\x1B[?2026h";e.lines.forEach((r,i)=>{n+=`\x1B[${i+1};1H\x1B[K${r}`});let t=new Set;for(let r of e.images){if(t.add(r.id),this.sent.get(r.id)!==r.path)n+=Kl(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)n+=Cl(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!t.has(r))n+=Wl(r),this.sent.delete(r),this.placed.delete(r);this.write(`${n}\x1B[?2026l`)}}async function $g(e){if(ci())return ui();let n=Re(),t=Vt(n),r=$t(t.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new bg(n,t,r,r.booru??""),o=await i.run(),s=i.unblock?await ui():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
484
+ `),0;return s}function kg(e,n){let t=Re();if($t(Vt(t).palettes,e),n==="next"||n==="prev"){let{key:r,at:i,of:o}=ph(t,e,n==="next"?1:-1);return et(t),process.stderr.write(`background · ${e} ${i}/${o} ${r}
485
+ `),0}if(n==="drop"){let{key:r,left:i}=wh(t,e);return et(t),process.stderr.write(`background · ${e} removed ${r} · ${i} left
486
+ `),0}if(n==="tuned")return et(t),0;throw Error(`unknown image action ${n} — next, prev, drop or tuned`)}import{execFileSync as _g,spawnSync as T$}from"node:child_process";import{chmodSync as G$,copyFileSync as U$,existsSync as en,mkdirSync as Hu,readdirSync as j$,readFileSync as cr,rmSync as Cg,writeFileSync as J$}from"node:fs";import{homedir as K$}from"node:os";import{dirname as ur,join as ke}from"node:path";import{existsSync as Fg}from"node:fs";import{openSync as N$,writeSync as O$}from"node:fs";import{ReadStream as R$}from"node:tty";var Eg=["10","11","12","17",...Array.from({length:16},(e,n)=>`4;${n}`)];function di(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Go(e){return[`\x1B]11;${e.background}\x1B\\`,`\x1B]10;${e.foreground}\x1B\\`,`\x1B]12;${e.cursor}\x1B\\`,`\x1B]17;${e.selection}\x1B\\`,...e.ansi.map((n,t)=>`\x1B]4;${t};${n}\x1B\\`)].join("")}function Sg(e){let n=new Map;for(let t of e.split("\x1B")){let r=t.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)n.set(i,o)}return n}function yg(e){return[...e].map(([n,t])=>`\x1B]${n};${t}\x1B\\`).join("")}async function vg(){let e,n;try{e=N$("/dev/tty","r+"),n=new R$(e),n.setRawMode(!0)}catch{return new Map}try{O$(e,Eg.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let t="";return await new Promise((r)=>{let i=setTimeout(r,120);n.on("data",(o)=>{if(t+=o.toString(),Sg(t).size>=Eg.length)clearTimeout(i),r()})}),Sg(t)}finally{n.setRawMode(!1),n.destroy()}}function or(e){let n=e.replace("#","");return[n.slice(0,2),n.slice(2,4),n.slice(4,6)].map((t)=>Number.parseInt(t,16)).join(";")}function Mg(e,n){return`\x1B[48;2;${or(n)}m ${e} \x1B[0m`}function Nu(e,n){return`\x1B[48;2;${or(e)};38;2;${or(n)}m ● \x1B[0m`}function Ig(e){return`\x1B[38;2;${or(e)}m`}function Ou(e,n){return`\x1B[48;2;${or(n)}m${e.map((t)=>`\x1B[38;2;${or(t)}m▄`).join("")} \x1B[0m`}function Uo(e,n){let t=n.toLowerCase();return[e.name,e.group,e.native??""].some((r)=>r.toLowerCase().includes(t))}function Og(e,n,t){let r=t.trim(),i=[],o=new Set;for(let s of e){if(s.default||o.has(s.group))continue;o.add(s.group);let u=e.filter((h)=>!h.default&&h.group===s.group),c=r?u.filter((h)=>Uo(h,r)):u;if(r&&c.length===0)continue;let a=r.length>0||n.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:u.find((h)=>h.lead)??s,expanded:a,count:c.length}),a)i.push(...c.map((h)=>({kind:"palette",entry:h})))}return i}function F$(e,n){let t=n.trim(),r=new Set(e.filter((i)=>!i.default&&(t===""||Uo(i,t))).map((i)=>i.group));return Og(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function H$(e){let n=e.findIndex((t)=>t.kind==="palette");return n===-1?0:n}var $n="\x1B[0m",sr="\x1B[2m",P$="\x1B[1m",Ng="\x1B[1;7m",L$="\x1B[36m",A$="\x1B[33m";function Rg(e){return e==="decode"||e==="glitch"?e:"typewriter"}class Ru extends mn{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(e){super({render:()=>this.draw(),input:e.input,output:e.output,validate:e.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=e.entries,this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.named=e.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=e.maxItems??12,this.color=e.color??!0,this.fx=e.fx??"typewriter",this.onFocus=e.onFocus,this.rollExample();let n=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);n.unref?.(),this.once("finalize",()=>{clearInterval(n),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,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(e){return e==="\t"||e===" "}members(e){let n=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((t)=>t.group===e&&(n===""||Uo(t,n)))}everyone(e){return e.flatMap((n)=>n.kind==="group"?this.members(n.name):[])}pick(e){let n=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(n.length===0)return;let t=n.some((r)=>!this.picked.has(r));for(let r of n)if(t)this.picked.add(r);else this.picked.delete(r)}pickedIn(e){return this.members(e).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((e)=>this.members(e).every((n)=>this.picked.has(n.name))).length}rollExample(){let e=this.named[Math.floor(Math.random()*this.named.length)],n=this.series[Math.floor(Math.random()*this.series.length)];if(!e||!n){this.example="";return}let t=`${e.name} | ${n}`;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 e=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let n=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",t=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<e||t(r)?r:n[Math.floor(Math.random()*n.length)]??r).join("")}sync(){let e=this.rows[this.cursor],n=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(n&&n.name!==this.lastFocused)this.lastFocused=n.name,this.onFocus?.(n)}rebuild(e){let n=this.rows[this.cursor],t=this.scope==="series"?F$(this.entries,this.userInput):Og(this.entries,this.expanded,this.userInput),r=t.length>0?H$(t)+1:0;if(this.rows=t.length>0?[{kind:"all",count:this.allCount(t)},...t]:[],e==="first")this.cursor=r;else if(e==="keep"){let i=n?.kind==="palette"?n.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(e){return this.scope==="series"?e.length:this.everyone(e).length}move(e){let n=this.cursor+e;if(n>=0&&n<this.rows.length)this.cursor=n;this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}fold(e){if(this.userInput||this.scope==="series")return;let n=this.rows[this.cursor];if(n?.kind==="group"){if(e!==n.expanded)this.toggle(n.name)}else if(n?.kind==="palette"&&!e&&!n.entry.default){let t=n.entry.group;if(this.expanded.delete(t),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===t),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(e,n){let t=n?"▶ ":" ";if(e.kind==="all"){let o=this.everyone(this.rows).every((u)=>this.picked.has(u.name))?"● ":"○ ",s=`(${e.count})`;return`${t}${o}select all ${this.color?`${sr}${s}${$n}`:s}`}if(e.kind==="group"&&this.scope==="series"){let o=this.pickedIn(e.name)===e.count?"● ":"○ ",s=e.name.padEnd(this.seriesPad),u=`(${e.count})${e.native?` ${e.native}`:""}`;if(!this.color)return`${t}${o}${s} ${u}`;let c=e.lead;return`${t}${o}${s} ${Nu(c.background,c.cursor)}${Ou(c.ansi.slice(1,7),c.background)} ${sr}${u}${$n}`}if(e.kind==="group"){let o=e.expanded?"▾":"▸",s=this.rows[this.cursor],u=s?.kind==="palette"&&s.entry.group===e.name?s.entry:void 0,c=this.color?n?`${Ng} ${e.name} ${$n}`:u?`${Ng}${Ig(u.cursor)} ${e.name} ${$n}`:` ${P$}${e.name}${$n} `:n?`[${e.name}]`:` ${e.name}`,a=this.color?Mg("●",e.lead.selection):"",h=`${this.pickedIn(e.name)}/${e.count}`,f=this.color?` ${sr}(${h})${$n}`:` (${h})`,l=e.native?this.color?` ${sr}${e.native}${$n}`:` ${e.native}`:"";return`${o}${c}${a}${f}${l}`}let r=e.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${t}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${t}${i}${r.name.padEnd(13)} ${Nu(r.background,r.cursor)}${Ou(r.ansi.slice(1,7),r.background)} ${sr}${r.ansiSource}${$n}`}draw(){let e=(d)=>this.color?`${sr}${d}${$n}`:d,n=(d)=>this.color?`${L$}${d}${$n}`:d,t=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${e("◇")} ${t} ${e(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${t} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((d)=>d.kind==="group").length:r?this.named.filter((d)=>Uo(d,r)).length:i,s=`${n("◆")} ${t} ${e(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,u=`${n("│")} ${this.userInput?`⌕ ${this.userInput}_`:e(`⌕ 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),a=c.length>0?c.map((d,$)=>`${n("│")} ${this.renderRow(d,this.top+$===this.cursor)}`):[`${n("│")} ${e(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(a.length<this.maxItems)a.push(n("│"));let h=this.rows.length-this.top-c.length,f=h>0?`${n("│")} ${e(`↓ ${h} more`)}`:n("│"),l=this.scope==="series"?"":" · ←→ fold",g=this.scope==="series"?"continue":"install",m=this.state==="error"?`${n("└")} ${this.color?`${A$}${this.error}${$n}`:this.error}`:`${n("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${g} · esc cancel`)}`;return[s,u,...a,f,m].join(`
487
+ `)}}function Fu(e){console.log(`
488
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}async function Hg(e){let n=Re(),t=_e(n),r=[...new Set(e.map((c)=>c.startsWith(Dn)?dl(n,c,t):c))],i=Fe(n),o=r.filter((c)=>i.palettes.includes(c)),s=r.filter((c)=>!i.palettes.includes(c));if(s.length===0){bn(n,t,i),console.log(`already installed: ${o.join(", ")}`);return}let u={...i,palettes:[...i.palettes,...s]};nt(n,t,i,u);for(let c of s)console.log(` + ${c}`);await Mt(n,je(n,t,!1).palettes.filter((c)=>s.includes(c.name)),u.terminals),Fu(u.palettes.length)}function Pg(e){let n=Re(),t=_e(n),r=Fe(n),i=e.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${e.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};nt(n,t,r,o),su(n,t,r.terminals,i);for(let s of i)console.log(` - ${s}`);Fu(o.palettes.length)}function Lg(e){let n=Re(),t=_e(n),r=Fe(n);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...o}=r,s=Gn(),u=ri({...o,startup:e},s);bn(n,t,u),yt(n,u);let c=St(u,s);console.log(Gg(e,u.terminals,c&&s.running()).join(`
489
+ `))}function Ag(){let e=Re(),n=Fe(e),t=Un(n);if(!t)throw Error("no palettes installed — `ttheme browse` picks some");if(!n.off){console.log(`already on · ${t}`);return}let{off:r,...i}=n,o=nt(e,_e(e),n,i);console.log(Gg(t,i.terminals,o).join(`
490
+ `))}function Tg(){let e=Re(),n=Fe(e);if(n.off){console.log("already off");return}let t=nt(e,_e(e),n,{...n,off:!0}),r=Un(n);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),t)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function Gg(e,n,t){let r=n.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${e} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(n.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 ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Ug(e,n){let t=new Map(n.palettes.map((r)=>[r.name,"catalog"]));for(let r of fo(e,n.palettes,!1))t.set(r.name,"mine");return t}function jg(e,n=!1){let t=Re(),r=_e(t),i=new Set(Fe(t).palettes),o=Ug(t,r),s=dt(je(t,r).palettes),u=Gr(e?Wf(s,e):s),c=(f)=>o.get(f)??"kept";if(n){let f=u.map((l)=>({name:l.name,group:l.group,installed:i.has(l.name),source:c(l.name)}));console.log(JSON.stringify(f,null,2));return}let a=Math.max(...u.map((f)=>f.name.length),0),h={catalog:"",mine:" · yours",kept:" · no longer in the catalog"};for(let f of u)console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(a)} ${f.group}${h[c(f.name)]}`);if(process.stdout.isTTY){let f=e?`${u.length} of ${s.length}`:`${s.length}`;console.log(`
491
+ ${f} palettes — ${u.filter((l)=>i.has(l.name)).length} installed`)}}async function Jg(){let e=Re(),n=Fg(mo(e))?_e(e).palettes.length:0,t=await Cf(Gf);po(e,t);let r=t.palettes.length-n;if(console.log(`catalog ${t.version} — ${t.palettes.length} palettes${r>0?` (+${r})`:""}`),!Fg(bo(e)))return;let i=Fe(e),o=Ug(e,t),s=i.palettes.filter((c)=>!o.has(c)),u=new Map(Bs(e).map((c)=>[c.name,c.pictures]));bn(e,t,i);for(let c of s)console.log(` ${c} left the catalog — ttheme keeps the copy you have`);await Mt(e,je(e,t,!1).palettes.filter((c)=>i.palettes.includes(c.name)&&u.has(c.name)).map((c)=>vo(c,u.get(c.name))),i.terminals)}async function jo(e,n,t,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Gr(e.palettes),o=process.stdout.isTTY===!0&&!di(),s=o?await vg():new Map,u=new Ru({entries:i,scope:t,installed:n,required:r,color:!di(),fx:Rg(process.env.TTHEME_FX),onFocus:o?(a)=>process.stdout.write(Go(a)):void 0}),c=await u.prompt();if(process.stdout.write(yg(s)),dn(c))return;return e.palettes.filter((a)=>u.picked.has(a.name)).map((a)=>a.name)}async function Kg(){let e=Re(),n=_e(e),t=Fe(e),r=await jo(je(e,n),t.palettes,"palette");if(!r){console.log("nothing changed");return}let i=t.palettes.filter((u)=>!r.includes(u)),o=r.filter((u)=>!t.palettes.includes(u));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...t,palettes:r};nt(e,n,t,s),su(e,n,t.terminals,i);for(let u of o)console.log(` + ${u}`);for(let u of i)console.log(` - ${u}`);await Mt(e,je(e,n,!1).palettes.filter((u)=>o.includes(u.name)),s.terminals),Fu(s.palettes.length)}function C$(e,n,t){for(let r of j$(n))e.push({from:ke(n,r),to:ke(t,r)})}function Qg(e){return JSON.parse(cr(ke(e,"dist","manifest.json"),"utf8"))}function Pu(e,n){let t=ke(n.configHome,"ttheme"),r=[{from:ke(n.root,"bin","ttheme.js"),to:ke(t,"ttheme.js")},{from:ke(n.root,"bin","ttheme.js.map"),to:ke(t,"ttheme.js.map")},{from:ke(n.root,"shell","ttheme.zsh"),to:ke(t,"ttheme.zsh")},{from:ke(n.root,"shell","launch-tab.zsh"),to:ke(t,"launch-tab.zsh"),executable:!0}];C$(r,ke(n.root,"shell","adapters"),ke(t,"adapters"));let i=[{file:ke(n.zdotdir,".zshrc"),block:Oh(t)}],o=ke(t,"config.zsh"),s=Ph(en(o)?cr(o,"utf8"):""),u={file:o,content:s},c=[];if(e.terminals.includes("alacritty")){let f=vt(n.configHome);if(en(f)&&Xr(cr(f,"utf8"),void 0)===void 0)c.push(`${f} already imports files under [general] — ttheme left it alone; add ${ke(n.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let f=Dt(n.configHome,n.home);if(en(f)&&Vr(cr(f,"utf8"),"")===void 0)c.push(`${f} has no \`return config\` line — ttheme left it alone; call \`dofile("${ke(t,"wezterm.lua")}")(config)\` from it yourself`)}let a=e.terminals.includes("windows-terminal");if(a&&!n.wtHome)c.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.terminals.includes("warp"))c.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let h={terminals:e.terminals,palettes:e.palettes,...a&&n.wtHome?{wtHome:n.wtHome}:{},...a&&n.wtProfile?{wtProfile:n.wtProfile}:{},...e.off?{off:!0}:{}};return c.push(...tl(n.configHome,e.terminals,n.home)),{home:n.home,copies:r,edits:i,settings:u,catalog:Qg(n.root),installed:h,notes:c}}function W$(e){try{return Fe(e)}catch{return}}function _$(e,n){let t=Pu({terminals:e.terminals,palettes:e.palettes,off:e.off},n),r=new Set(t.catalog.palettes.map((h)=>h.name)),i=e.palettes.filter((h)=>r.has(h)),o=e.palettes.filter((h)=>!r.has(h)),{startup:s,...u}=e,c={...u,palettes:i,...s&&i.includes(s)?{startup:s}:{}},a=o.length>0?[`dropped ${o.join(", ")} — no longer in the catalog`,...t.notes]:t.notes;return{...t,installed:c,notes:a}}function Q$(e){try{return _g(process.execPath,[ke(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function qg(e){let n=wn(e);return[e.terminals.join(", "),`${e.palettes.length} palettes`,n?`default ${n}`:"no default — ttheme is off"].join(" · ")}function q$(e){try{return Fe(e).itermBase}catch{return}}function Lu(e,n=Gn()){for(let o of e.copies)if(Hu(ur(o.to),{recursive:!0}),Cg(o.to,{force:!0}),Cg(`${o.to}.zwc`,{force:!0}),U$(o.from,o.to),o.executable)G$(o.to,493);Hu(ur(e.settings.file),{recursive:!0}),J$(e.settings.file,e.settings.content);let t=ur(ur(e.settings.file)),r=q$(t),i=ri(r?{...e.installed,itermBase:r}:e.installed,n);po(t,e.catalog),yt(t,i),bn(t,e.catalog,i,e.home);for(let o of e.edits){Hu(ur(o.file),{recursive:!0});let s=en(o.file)?cr(o.file,"utf8"):"";Cr(o.file,qr(s,o.block))}return St(i,n)}class tt extends Error{}function Jo(e){if(dn(e))throw Yt("nothing changed"),new tt;return e}function Zg(e){return Yi.filter((n)=>{if(n==="iterm2")return process.platform==="darwin";if(n==="windows-terminal")return e.wtHome!==void 0;return n!=="warp"||process.platform!=="win32"})}function Z$(e,n){if(e==="iterm2")return en(ke(n.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return n.wtHome!==void 0;if(e==="warp")return en(ur($o(n.home)));if(e==="wezterm")return en(ke(n.configHome,"wezterm"))||en(ke(n.home,".wezterm.lua"));return en(ke(n.configHome,e))}function Y$(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(n,t)=>_g(n,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return e("wslpath",["-u",e("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function X$(e,n,t){return Jo(await Nf({message:"wire which terminals?",options:Zg(t).map((r)=>({value:r,hint:r===e?"detected":void 0})),initialValues:n,required:!0}))}function Au(e){let n=[...e.copies.filter((t)=>!en(t.to)).map((t)=>t.to),...en(e.settings.file)?[]:[e.settings.file],...e.edits.filter((t)=>!cr(t.file,"utf8").includes("# ttheme begin")).map((t)=>t.file)];if(n.length>0)throw Error(`init left gaps:
492
+ ${n.join(`
493
+ `)}`)}function Yg(e,n){return[...new Set(e.palettes.filter((t)=>n.includes(t.name)).map((t)=>t.group))]}function V$(e,n){let t=e.palettes.find((i)=>i.name===wn(n)),r=process.stdout.isTTY===!0&&!di()&&!process.env.TMUX&&Xi(process.env)!=="warp";if(!t||!r)return!1;return process.stdout.write(Go(t)),!0}function z$(e,n){let t=wn(e);if(!t)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${Un(e)}`];return[`default ${t}${n?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function B$(e){T$("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ke(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function D$(e,n,t,r){let i=Yg(e.catalog,n.palettes);pt([`${i.join(", ")} (${n.palettes.length})`,...z$(e.installed,t)].join(`
494
+ `),`installed ${n.palettes.length} palettes`),pt(["exec zsh the ttheme command in this tab",...Xg(n.terminals,e,r)].join(`
495
+ `),"next"),Vs("done")}function Xg(e,n,t){let r=[];if(e.includes("ghostty"))r.push("restart ghostty new tabs pick up its config");if(e.includes("kitty"))r.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(e.includes("alacritty"))r.push("alacritty reloads its config by itself");if(e.includes("wezterm"))r.push("wezterm reloads its config by itself");if(e.includes("windows-terminal"))r.push("windows terminal reloads its settings by itself");if(e.includes("iterm2"))r.push(...x$(wn(n.installed),t));return[...r,...n.notes]}function Wg(e,n,t){let r=_$(e,n),i=Gn(),o=Lu(r,i);Au(r);let s=["exec zsh open tabs run the new layer — new tabs already do",...Xg(r.installed.terminals,r,o&&i.running())],u=`updated to ${Ke.version} — kept ${qg(r.installed)}`;if(!t){console.log([u,...s].join(`
496
+ `));return}pt(s.join(`
497
+ `),u),Vs("done")}function x$(e,n){let t=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(e)t.push(n?`restart iterm2 new tabs open on "ttheme · default", which wears ${e}`:`iterm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return t}function e1(e,n){let t=[`placed ${e.copies.length} files`,`settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`wired ${r.file}`)];if(n.terminals.includes("ghostty"))t.push("restart ghostty to pick up its config");if(n.terminals.includes("kitty"))t.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(n.terminals.includes("alacritty"))t.push("alacritty reloads its config by itself");if(n.terminals.includes("wezterm")||n.terminals.includes("windows-terminal"))t.push("wezterm and windows terminal reload their config by themselves");if(n.terminals.includes("iterm2"))t.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');t.push(...e.notes),t.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(t.join(`
498
+ `))}async function Vg(e={}){let n=ke(import.meta.dirname,"..");if(!en(ke(n,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!en(ke(n,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Di()}let t=K$(),r=Re(),i=process.env.ZDOTDIR??t,o=Y$(),s=process.env.WT_PROFILE_ID,u={root:n,home:t,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},c=Xi(process.env),a=Zg(u).filter((I)=>I===c||Z$(I,u));if(!e.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");let h=W$(r);if(e.yes&&h){Wg(h,u,!1);return}if(e.yes){if(a.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let I={terminals:a,palettes:[]},P=Pu(I,u);Lu(P),Au(P),e1(P,I);return}if(co("ttheme init"),h){let I=Q$(r);if(Jo(await Zt({message:`ttheme${I?` ${I}`:""} is installed — ${qg(h)}
499
+ ${I===Ke.version?"reinstall":"update to"} ${Ke.version} and keep all of it?`,active:"yes",inactive:"no, set it up again",initialValue:!0}))){Wg(h,u,!0);return}}let f=await X$(c,h?.terminals??a,u),l=Qg(n),g=h?await jo(l,h.palettes,"palette",!0):await jo(l,[],"series",!0);if(!g)throw Yt("nothing changed"),new tt;let m=h&&Un(h),d=m&&g.includes(m)?m:void 0,$=d??g[0],y=g.length>1&&Xi(process.env)!=="warp",N=Jo(await Zt({message:y?"pick a default palette in ttheme preview once installed?":`wear ${$} in every tab?`,initialValue:h?!h.off:!0})),E={terminals:f,palettes:g,off:!N},v=Pu(E,u),p=d?{...v,installed:{...v.installed,startup:d}}:v;if(pt([`install ${g.length} palettes — ${Yg(p.catalog,g).join(", ")}`,`copy ${p.copies.length} files under ${r}`,`write ${p.settings.file}`,...p.edits.map((I)=>`edit ${I.file} — a ttheme block: source ttheme.zsh`),...nl(r,p.installed,t),"each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",N?y?`open ttheme preview — every tab wears the palette picked there, ${$} until then`:`paint every tab with ${$}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...f.includes("iterm2")&&N?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
500
+ `),`wiring ${f.join(", ")}`),!Jo(await Zt({message:"apply these changes?"})))throw Yt("nothing changed"),new tt;let H=Gn(),S=Lu(p,H);if(Au(p),N&&y)B$(r);let R=Fe(r);D$({...p,installed:R},E,V$(p.catalog,R),S&&H.running())}import{existsSync as n1,mkdirSync as t1,readFileSync as zg,rmSync as r1,writeFileSync as Tu}from"node:fs";import{dirname as i1,join as Gu}from"node:path";var Bg=Gu(import.meta.dirname,"..","themes");function o1(e){let n=/```(?:toml)?[^\n]*\n([\s\S]*?)\n```/.exec(e)?.[1],t=/###\s*Palette\s*\n([\s\S]*)$/.exec(e)?.[1],r=(n??t??e).trim();if(r===""||r==="_No response_")throw Error("the issue holds no palette — `ttheme submit <palette>` fills it in");return`${r}
501
+ `}function Dg(e,n){let t=o1(zg(e,"utf8")),r;try{r=Er(t).meta?.name}catch(u){throw Error(`the palette is not valid TOML — ${u.message.split(`
502
+ `)[0]}`)}if(typeof r!=="string"||Yn(r)||!Xe(r))throw Error(`meta.name must be <your GitHub handle>/<palette>, got ${JSON.stringify(r)}`);let i=Xe(r);if(i!==n.toLowerCase())throw Error(`${r} is named after ${i}, but this issue is from ${n} — a palette carries its author's handle`);let o=Gu(Bg,Ar,i,`${r.slice(i.length+1)}.toml`),s=n1(o)?zg(o,"utf8"):void 0;t1(i1(o),{recursive:!0}),Tu(o,t);try{let u=_i(Bg).find((f)=>f.name===r);if(!u)throw Error(`${r} did not load`);let c=At(u);if(c.length>0)throw Error(`it fails the contrast gate — \`ttheme check --fix ${r}\` suggests colors that pass:
503
+ ${c.map((f)=>` ${f.rule}: ${f.detail}`).join(`
504
+ `)}`);let a=on(u),h={...ti(a,r,u.waiveReason),...u.pictures?{pictures:u.pictures}:{}};Tu(o,Xt(h)),console.log(JSON.stringify({name:r,path:Gu("themes",Ar,i,`${r.slice(i.length+1)}.toml`),updating:s!==void 0,code:lo(h),gate:go(a)}))}catch(u){if(s===void 0)r1(o);else Tu(o,s);throw u}}import{existsSync as Ko,readdirSync as s1,readFileSync as u1,rmSync as c1,utimesSync as a1}from"node:fs";import{homedir as h1}from"node:os";import{dirname as f1,join as ar}from"node:path";function Uu(e){return Ko(e)?u1(e,"utf8"):""}function l1(e){try{return Fe(e)}catch{return}}function g1(e,n){let t=ko(n,e),r=Uu(t);if(!Vi(r)?.includes(`path = "${le("")}`))return;return{file:t,content:zi(r,Uu(iu(e))||ru)}}function d1(e){let{home:n,configHome:t}=e,r=l1(t),i=[],o=(a,h)=>{let f=Uu(a),l=h(f);if(l!==f)i.push({file:a,content:l})};o(ar(e.zdotdir,".zshrc"),Zr),o(Et("ghostty",t),Zr),o(Et("kitty",t),Zr),o(vt(t),Zr),o(Dt(t,n),Uh);let s=g1(t,n);if(s)i.push(s);let u=[];for(let a of["ghostty","kitty","alacritty","wezterm","warp"]){let h=kt(a,t,n);if(Ko(h))u.push(...s1(h).flatMap((f)=>f.startsWith(le(""))?[ar(h,f)]:[]))}let c=[ii(n),...r?.wtHome?[f1(Eo(r.wtHome))]:[],ar(t,"ttheme"),e.cacheDir,e.stateDir];return u.push(...c.filter((a)=>Ko(a))),{edits:i,removals:u,touches:r?.wtHome?ou(r.wtHome):[],...r?{state:r}:{}}}function m1(e,n=Gn()){let t=[];for(let{file:i,content:o}of e.edits){let s=nh(i,o);t.push(s==="removed"?`removed ${i} — ttheme had created it`:s==="restored"?`took ttheme out of ${i}`:`took ttheme out of ${i} — kept ${i}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state&&St({...e.state,off:!0},n))t.push("gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)c1(i,{recursive:!0,force:!0});if(e.removals.length>0)t.push(`deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)a1(i,r,r);return t}function p1(){let e=h1();return{home:e,configHome:Re(),zdotdir:process.env.ZDOTDIR??e,cacheDir:Ji(),stateDir:ar(process.env.XDG_STATE_HOME??ar(e,".local","state"),"ttheme")}}async function xg(e=!1){let n=p1(),t=d1(n);if(t.edits.length===0&&t.removals.length===0){console.log("nothing of ttheme is installed");return}if(!e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=ar(n.configHome,"ttheme");co("ttheme uninstall"),pt([...t.edits.map((o)=>`take ttheme out of ${o.file}`),...t.removals.map((o)=>o===r?`delete ${o} — settings, pins, every installed picture${Ko(ho(n.configHome))?", and the palettes you made (`ttheme share` prints a code that keeps one)":""}`:`delete ${o}`)].join(`
505
+ `),"uninstall");let i=await Zt({message:"remove ttheme?"});if(dn(i)||!i)throw Yt("nothing changed"),new tt}for(let r of m1(t))console.log(r);console.log("open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var mi=(e)=>(...n)=>ci()&&si()?ui():e(...n),b1={default:([e])=>Lg(e),on:()=>Ag(),off:()=>Tg(),browse:mi(()=>Kg()),list:([e],{json:n})=>jg(e,n),add:mi((e)=>Hg(e)),remove:(e)=>Pg(e),update:mi(()=>Jg()),new:mi(([e],{from:n})=>ml(e,n)),edit:mi(([e])=>pl(e)),check:([e],{fix:n})=>bl(e,n),share:([e])=>kl(e),submit:([e])=>El(e),init:(e,{yes:n})=>Vg({yes:n}),uninstall:(e,{yes:n})=>xg(n),build:(e,{only:n})=>Di({only:n}),find:([e])=>$g(e),image:([e,n])=>kg(e,n),intake:([e,n])=>Dg(e,n)},td=Zi.map((e)=>({...e,run:b1[e.name]}));class Nt extends Error{verb;constructor(e,n){super(e);this.verb=n}}function ed(e){let n=td.find((t)=>t.name===e);if(!n)throw new Nt(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return n}function $1(e,n){let t={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(e.flags??{}))t[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return w1({args:n,options:t,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Nt(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function k1(e){let[n,...t]=e;if(n===void 0)return{kind:"help",code:1};if(n==="-h"||n==="--help")return{kind:"help",code:0};if(n==="-V"||n==="--version")return{kind:"version"};if(n==="help")return t[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:ed(t[0]),code:0};let r=ed(n),i=$1(r,t);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[h,{choices:f}]of Object.entries(r.flags??{}))for(let l of[i.values[h]??[]].flat())if(f&&!f.includes(String(l)))throw new Nt(`--${h} takes ${f.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((h)=>h.startsWith("<")).length,u=r.args.some((h)=>h.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Nt(`missing ${r.args[o.length]}`,r);if(o.length>u)throw new Nt(`too many arguments: ${o.slice(u).join(" ")}`,r);let{help:c,...a}=i.values;return{kind:"run",verb:r,args:o,flags:a}}function ju(e){let n=Object.entries(e.flags??{}).map(([t,{value:r}])=>`[--${t}${r?` ${r}`:""}]`);return[e.name,...n,...e.args].join(" ")}function nd(e,n=Math.max(...e.map(([t])=>t.length))){return e.map(([t,r])=>` ${t.padEnd(n)} ${r}`)}var E1=["tab","catalog","own","setup"];function Ju(e){if(e){let i=Object.entries(e.flags??{}).map(([o,{short:s,value:u,about:c}])=>[`${s?`-${s}, `:""}--${o}${u?` ${u}`:""}`,c]);return[`Usage: ttheme ${ju(e)}`,"",e.about,...i.length>0?["","Options:",...nd(i)]:[]].join(`
506
+ `)}let n=td.filter((i)=>!i.hidden),t=(i)=>n.filter((o)=>o.section===i).map((o)=>[ju(o),o.about]),r=Math.max(...n.map((i)=>ju(i).length));return["Usage: ttheme <command>","",Ke.description,"","Commands:",...E1.flatMap((i,o)=>[...o>0?[""]:[],...nd(t(i),r)]),"","Examples:"," npx @kecan0406/ttheme init -y wire the terminals found here, no prompts"," ttheme add homura madoka install two palettes"," ttheme use homura paint this tab with one"," ttheme list --json madoka the madoka series as JSON"," ttheme new dusk --from madoka your own palette, <you>/dusk, to edit and share","","ttheme <command> --help describes one command · ttheme --version prints the version","https://kecan0406.github.io/ttheme"].join(`
507
+ `)}async function rd(e){let n;try{let t=k1(e);if(t.kind==="version")return console.log(Ke.version),0;if(t.kind==="help"){if(t.code===0)console.log(Ju(t.verb));else console.error(Ju(t.verb));return t.code}if(n=t.verb,!t.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await t.verb.run(t.args,t.flags);return typeof r==="number"?r:0}catch(t){if(t instanceof Nt)return console.error(`ttheme${t.verb?` ${t.verb.name}`:""}: ${t.message}
219
508
 
220
- ${Do(n.verb)}`),1;if(n instanceof He)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
221
- ttheme${e?` ${e.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(Rw)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let t=Nw(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=t.status??1}else process.exitCode=await _f(process.argv.slice(2));
509
+ ${Ju(t.verb)}`),1;if(t instanceof tt)return 1;let r=process.env.TTHEME_DEBUG&&t instanceof Error?t.stack:void 0;return console.error(`
510
+ ttheme${n?` ${n.name}`:""}: ${r??(t instanceof Error?t.message:String(t))}`),1}}if(y1)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=S1(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await rd(process.argv.slice(2));
222
511
 
223
- //# debugId=D85E6B78A530B43764756E2164756E21
512
+ //# debugId=4D7C307BC59E468364756E2164756E21
224
513
  //# sourceMappingURL=ttheme.js.map