@kecan0406/ttheme 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,74 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Bp}from"node:module";var qp=Object.create;var{getPrototypeOf:Qp,defineProperty:cl,getOwnPropertyNames:Yp}=Object;var Zp=Object.prototype.hasOwnProperty;function zp(e){return this[e]}var Vp,Xp,Es=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?Vp??=new WeakMap:Xp??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?qp(Qp(e)):{};let o=t||!e||!e.__esModule?cl(n,"default",{value:e,enumerable:!0}):n;for(let a of Yp(e))if(!Zp.call(o,a))cl(o,a,{get:zp.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Fe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ze=Bp(import.meta.url);var da=Fe((qv,Ml)=>{var fa={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},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"},fw={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},dw={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 t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?fa.up():"");if(e)t+=fa.left;return t}};Ml.exports={cursor:fa,scroll:fw,erase:dw,beep:"\x07"}});var ih=Fe((MM,js)=>{var rh=rh||function(e){return Buffer.from(e).toString("base64")};function ab(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,h,f=Array(65535),d=Array(65535),g=Array(64),m=Array(64),$=[],w=0,M=7,y=Array(64),S=Array(64),p=Array(64),N=Array(256),E=Array(2048),F,O=[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],U=[0,1,2,3,4,5,6,7,8,9,10,11],ce=[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],H=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],Q=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ne=[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 $e(b){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 C=r((G[J]*b+50)/100);if(C<1)C=1;else if(C>255)C=255;i[O[J]]=C}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 X=0;X<64;X++){var le=r((z[X]*b+50)/100);if(le<1)le=1;else if(le>255)le=255;s[O[X]]=le}var he=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var Oe=0;Oe<8;Oe++)for(var I=0;I<8;I++)o[Ue]=1/(i[O[Ue]]*he[Oe]*he[I]*8),a[Ue]=1/(s[O[Ue]]*he[Oe]*he[I]*8),Ue++}function x(b,G){var J=0,C=0,z=[];for(var X=1;X<=16;X++){for(var le=1;le<=b[X];le++)z[G[C]]=[],z[G[C]][0]=J,z[G[C]][1]=X,C++,J++;J*=2}return z}function Ge(){u=x(L,U),c=x(H,A),l=x(ce,j),h=x(Q,Ne)}function fe(){var b=1,G=2;for(var J=1;J<=15;J++){for(var C=b;C<G;C++)d[32767+C]=J,f[32767+C]=[],f[32767+C][1]=J,f[32767+C][0]=C;for(var z=-(G-1);z<=-b;z++)d[32767+z]=J,f[32767+z]=[],f[32767+z][1]=J,f[32767+z][0]=G-1+z;b<<=1,G<<=1}}function se(){for(var b=0;b<256;b++)E[b]=19595*b,E[b+256>>0]=38470*b,E[b+512>>0]=7471*b+32768,E[b+768>>0]=-11059*b,E[b+1024>>0]=-21709*b,E[b+1280>>0]=32768*b+8421375,E[b+1536>>0]=-27439*b,E[b+1792>>0]=-5329*b}function D(b){var G=b[0],J=b[1]-1;while(J>=0){if(G&1<<J)w|=1<<M;if(J--,M--,M<0){if(w==255)k(255),k(0);else k(w);M=7,w=0}}}function k(b){$.push(b)}function _(b){k(b>>8&255),k(b&255)}function ke(b,G){var J,C,z,X,le,he,Ue,Oe,I=0,T,Y=8,He=64;for(T=0;T<Y;++T){J=b[I],C=b[I+1],z=b[I+2],X=b[I+3],le=b[I+4],he=b[I+5],Ue=b[I+6],Oe=b[I+7];var B=J+Oe,re=J-Oe,Ee=C+Ue,K=C-Ue,ge=z+he,Ye=z-he,Te=X+le,mt=X-le,At=B+Te,Cn=B-Te,dr=Ee+ge,gr=Ee-ge;b[I]=At+dr,b[I+4]=At-dr;var si=(gr+Cn)*0.707106781;b[I+2]=Cn+si,b[I+6]=Cn-si,At=mt+Ye,dr=Ye+K,gr=K+re;var oi=(At-gr)*0.382683433,bs=0.5411961*At+oi,ai=1.306562965*gr+oi,ui=dr*0.707106781,ci=re+ui,li=re-ui;b[I+5]=li+bs,b[I+3]=li-bs,b[I+1]=ci+ai,b[I+7]=ci-ai,I+=8}I=0;for(T=0;T<Y;++T){J=b[I],C=b[I+8],z=b[I+16],X=b[I+24],le=b[I+32],he=b[I+40],Ue=b[I+48],Oe=b[I+56];var Xc=J+Oe,aa=J-Oe,Bc=C+Ue,xc=C-Ue,Dc=z+he,el=z-he,tl=X+le,Kp=X-le,hi=Xc+tl,ua=Xc-tl,$s=Bc+Dc,ks=Bc-Dc;b[I]=hi+$s,b[I+32]=hi-$s;var nl=(ks+ua)*0.707106781;b[I+16]=ua+nl,b[I+48]=ua-nl,hi=Kp+el,$s=el+xc,ks=xc+aa;var rl=(hi-ks)*0.382683433,il=0.5411961*hi+rl,sl=1.306562965*ks+rl,ol=$s*0.707106781,al=aa+ol,ul=aa-ol;b[I+40]=ul+il,b[I+24]=ul-il,b[I+8]=al+sl,b[I+56]=al-sl,I++}var ys;for(T=0;T<He;++T)ys=b[T]*G[T],g[T]=ys>0?ys+0.5|0:ys-0.5|0;return g}function ye(){_(65504),_(16),k(74),k(70),k(73),k(70),k(0),k(1),k(1),k(0),_(1),_(1),k(0),k(0)}function oe(b){if(!b)return;if(_(65505),b[0]===69&&b[1]===120&&b[2]===105&&b[3]===102)_(b.length+2);else _(b.length+5+2),k(69),k(120),k(105),k(102),k(0);for(var G=0;G<b.length;G++)k(b[G])}function ae(b,G){_(65472),_(17),k(8),_(G),_(b),k(3),k(1),k(17),k(0),k(2),k(17),k(1),k(3),k(17),k(1)}function te(){_(65499),_(132),k(0);for(var b=0;b<64;b++)k(i[b]);k(1);for(var G=0;G<64;G++)k(s[G])}function P(){_(65476),_(418),k(0);for(var b=0;b<16;b++)k(L[b+1]);for(var G=0;G<=11;G++)k(U[G]);k(16);for(var J=0;J<16;J++)k(ce[J+1]);for(var C=0;C<=161;C++)k(j[C]);k(1);for(var z=0;z<16;z++)k(H[z+1]);for(var X=0;X<=11;X++)k(A[X]);k(17);for(var le=0;le<16;le++)k(Q[le+1]);for(var he=0;he<=161;he++)k(Ne[he])}function R(b){if(typeof b>"u"||b.constructor!==Array)return;b.forEach((G)=>{if(typeof G!=="string")return;_(65534);var J=G.length;_(J+2);var C;for(C=0;C<J;C++)k(G.charCodeAt(C))})}function Re(){_(65498),_(12),k(3),k(1),k(0),k(2),k(17),k(3),k(17),k(0),k(63),k(0)}function q(b,G,J,C,z){var X=z[0],le=z[240],he,Ue=16,Oe=63,I=64,T=ke(b,G);for(var Y=0;Y<I;++Y)m[O[Y]]=T[Y];var He=m[0]-J;if(J=m[0],He==0)D(C[0]);else he=32767+He,D(C[d[he]]),D(f[he]);var B=63;for(;B>0&&m[B]==0;B--);if(B==0)return D(X),J;var re=1,Ee;while(re<=B){var K=re;for(;m[re]==0&&re<=B;++re);var ge=re-K;if(ge>=Ue){Ee=ge>>4;for(var Ye=1;Ye<=Ee;++Ye)D(le);ge=ge&15}he=32767+m[re],D(z[(ge<<4)+d[he]]),D(f[he]),re++}if(B!=Oe)D(X);return J}function ne(){var b=String.fromCharCode;for(var G=0;G<256;G++)N[G]=b(G)}this.encode=function(b,G){var J=new Date().getTime();if(G)gt(G);$=[],w=0,M=7,_(65496),ye(),R(b.comments),oe(b.exifBuffer),te(),ae(b.width,b.height),P(),Re();var C=0,z=0,X=0;w=0,M=7,this.encode.displayName="_encode_";var{data:le,width:he,height:Ue}=b,Oe=he*4,I=he*3,T,Y=0,He,B,re,Ee,K,ge,Ye,Te;while(Y<Ue){T=0;while(T<Oe){Ee=Oe*Y+T,K=Ee,ge=-1,Ye=0;for(Te=0;Te<64;Te++){if(Ye=Te>>3,ge=(Te&7)*4,K=Ee+Ye*Oe+ge,Y+Ye>=Ue)K-=Oe*(Y+1+Ye-Ue);if(T+ge>=Oe)K-=T+ge-Oe+4;He=le[K++],B=le[K++],re=le[K++],y[Te]=(E[He]+E[B+256>>0]+E[re+512>>0]>>16)-128,S[Te]=(E[He+768>>0]+E[B+1024>>0]+E[re+1280>>0]>>16)-128,p[Te]=(E[He+1280>>0]+E[B+1536>>0]+E[re+1792>>0]>>16)-128}C=q(y,o,C,u,l),z=q(S,a,z,c,h),X=q(p,a,X,c,h),T+=32}Y+=8}if(M>=0){var mt=[];mt[1]=M+1,mt[0]=(1<<M+1)-1,D(mt)}if(_(65497),typeof js>"u")return new Uint8Array($);return Buffer.from($);var At,Cn};function gt(b){if(b<=0)b=1;if(b>100)b=100;if(F==b)return;var G=0;if(b<50)G=Math.floor(5000/b);else G=Math.floor(200-b*2);$e(G),F=b}function vt(){var b=new Date().getTime();if(!e)e=50;ne(),Ge(),fe(),se(),gt(e);var G=new Date().getTime()-b}vt()}if(typeof js<"u")js.exports=nh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=nh;function nh(e,t){if(typeof t>"u")t=50;var n=new ab(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var oh=Fe((SM,Ha)=>{var Aa=function(){var t=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,s=2276,o=1567,a=3784,u=5793,c=2896;function l(){}function h(M,y){var S=0,p=[],N,E,F=16;while(F>0&&!M[F-1])F--;p.push({children:[],index:0});var O=p[0],L;for(N=0;N<F;N++){for(E=0;E<M[N];E++){O=p.pop(),O.children[O.index]=y[S];while(O.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");O=p.pop()}O.index++,p.push(O);while(p.length<=N)p.push(L={children:[],index:0}),O.children[O.index]=L.children,O=L;S++}if(N+1<F)p.push(L={children:[],index:0}),O.children[O.index]=L.children,O=L}return p[0].children}function f(M,y,S,p,N,E,F,O,L,U){var{precision:ce,samplesPerLine:j,scanLines:H,mcusPerLine:A,progressive:Q,maxH:Ne,maxV:$e}=S,x=y,Ge=0,fe=0;function se(){if(fe>0)return fe--,Ge>>fe&1;if(Ge=M[y++],Ge==255){var I=M[y++];if(I)throw Error("unexpected marker: "+(Ge<<8|I).toString(16))}return fe=7,Ge>>>7}function D(I){var T=I,Y;while((Y=se())!==null){if(T=T[Y],typeof T==="number")return T;if(typeof T!=="object")throw Error("invalid huffman sequence")}return null}function k(I){var T=0;while(I>0){var Y=se();if(Y===null)return;T=T<<1|Y,I--}return T}function _(I){var T=k(I);if(T>=1<<I-1)return T;return T+(-1<<I)+1}function ke(I,T){var Y=D(I.huffmanTableDC),He=Y===0?0:_(Y);T[0]=I.pred+=He;var B=1;while(B<64){var re=D(I.huffmanTableAC),Ee=re&15,K=re>>4;if(Ee===0){if(K<15)break;B+=16;continue}B+=K;var ge=t[B];T[ge]=_(Ee),B++}}function ye(I,T){var Y=D(I.huffmanTableDC),He=Y===0?0:_(Y)<<L;T[0]=I.pred+=He}function oe(I,T){T[0]|=se()<<L}var ae=0;function te(I,T){if(ae>0){ae--;return}var Y=E,He=F;while(Y<=He){var B=D(I.huffmanTableAC),re=B&15,Ee=B>>4;if(re===0){if(Ee<15){ae=k(Ee)+(1<<Ee)-1;break}Y+=16;continue}Y+=Ee;var K=t[Y];T[K]=_(re)*(1<<L),Y++}}var P=0,R;function Re(I,T){var Y=E,He=F,B=0;while(Y<=He){var re=t[Y],Ee=T[re]<0?-1:1;switch(P){case 0:var K=D(I.huffmanTableAC),ge=K&15,B=K>>4;if(ge===0)if(B<15)ae=k(B)+(1<<B),P=4;else B=16,P=1;else{if(ge!==1)throw Error("invalid ACn encoding");R=_(ge),P=B?2:3}continue;case 1:case 2:if(T[re])T[re]+=(se()<<L)*Ee;else if(B--,B===0)P=P==2?3:0;break;case 3:if(T[re])T[re]+=(se()<<L)*Ee;else T[re]=R<<L,P=0;break;case 4:if(T[re])T[re]+=(se()<<L)*Ee;break}Y++}if(P===4){if(ae--,ae===0)P=0}}function q(I,T,Y,He,B){var re=Y/A|0,Ee=Y%A,K=re*I.v+He,ge=Ee*I.h+B;if(I.blocks[K]===void 0&&U.tolerantDecoding)return;T(I,I.blocks[K][ge])}function ne(I,T,Y){var He=Y/I.blocksPerLine|0,B=Y%I.blocksPerLine;if(I.blocks[He]===void 0&&U.tolerantDecoding)return;T(I,I.blocks[He][B])}var gt=p.length,vt,b,G,J,C,z;if(Q)if(E===0)z=O===0?ye:oe;else z=O===0?te:Re;else z=ke;var X=0,le,he;if(gt==1)he=p[0].blocksPerLine*p[0].blocksPerColumn;else he=A*S.mcusPerColumn;if(!N)N=he;var Ue,Oe;while(X<he){for(b=0;b<gt;b++)p[b].pred=0;if(ae=0,gt==1){vt=p[0];for(C=0;C<N;C++)ne(vt,z,X),X++}else for(C=0;C<N;C++){for(b=0;b<gt;b++){vt=p[b],Ue=vt.h,Oe=vt.v;for(G=0;G<Oe;G++)for(J=0;J<Ue;J++)q(vt,z,X,G,J)}if(X++,X===he)break}if(X===he)do{if(M[y]===255){if(M[y+1]!==0)break}y+=1}while(y<M.length-2);if(fe=0,le=M[y]<<8|M[y+1],le<65280)throw Error("marker was not found");if(le>=65488&&le<=65495)y+=2;else break}return y-x}function d(M,y){var S=[],p=y.blocksPerLine,N=y.blocksPerColumn,E=p<<3,F=new Int32Array(64),O=new Uint8Array(64);function L(x,Ge,fe){var se=y.quantizationTable,D,k,_,ke,ye,oe,ae,te,P,R=fe,Re;for(Re=0;Re<64;Re++)R[Re]=x[Re]*se[Re];for(Re=0;Re<8;++Re){var q=8*Re;if(R[1+q]==0&&R[2+q]==0&&R[3+q]==0&&R[4+q]==0&&R[5+q]==0&&R[6+q]==0&&R[7+q]==0){P=u*R[0+q]+512>>10,R[0+q]=P,R[1+q]=P,R[2+q]=P,R[3+q]=P,R[4+q]=P,R[5+q]=P,R[6+q]=P,R[7+q]=P;continue}D=u*R[0+q]+128>>8,k=u*R[4+q]+128>>8,_=R[2+q],ke=R[6+q],ye=c*(R[1+q]-R[7+q])+128>>8,te=c*(R[1+q]+R[7+q])+128>>8,oe=R[3+q]<<4,ae=R[5+q]<<4,P=D-k+1>>1,D=D+k+1>>1,k=P,P=_*a+ke*o+128>>8,_=_*o-ke*a+128>>8,ke=P,P=ye-ae+1>>1,ye=ye+ae+1>>1,ae=P,P=te+oe+1>>1,oe=te-oe+1>>1,te=P,P=D-ke+1>>1,D=D+ke+1>>1,ke=P,P=k-_+1>>1,k=k+_+1>>1,_=P,P=ye*s+te*i+2048>>12,ye=ye*i-te*s+2048>>12,te=P,P=oe*r+ae*n+2048>>12,oe=oe*n-ae*r+2048>>12,ae=P,R[0+q]=D+te,R[7+q]=D-te,R[1+q]=k+ae,R[6+q]=k-ae,R[2+q]=_+oe,R[5+q]=_-oe,R[3+q]=ke+ye,R[4+q]=ke-ye}for(Re=0;Re<8;++Re){var ne=Re;if(R[8+ne]==0&&R[16+ne]==0&&R[24+ne]==0&&R[32+ne]==0&&R[40+ne]==0&&R[48+ne]==0&&R[56+ne]==0){P=u*fe[Re+0]+8192>>14,R[0+ne]=P,R[8+ne]=P,R[16+ne]=P,R[24+ne]=P,R[32+ne]=P,R[40+ne]=P,R[48+ne]=P,R[56+ne]=P;continue}D=u*R[0+ne]+2048>>12,k=u*R[32+ne]+2048>>12,_=R[16+ne],ke=R[48+ne],ye=c*(R[8+ne]-R[56+ne])+2048>>12,te=c*(R[8+ne]+R[56+ne])+2048>>12,oe=R[24+ne],ae=R[40+ne],P=D-k+1>>1,D=D+k+1>>1,k=P,P=_*a+ke*o+2048>>12,_=_*o-ke*a+2048>>12,ke=P,P=ye-ae+1>>1,ye=ye+ae+1>>1,ae=P,P=te+oe+1>>1,oe=te-oe+1>>1,te=P,P=D-ke+1>>1,D=D+ke+1>>1,ke=P,P=k-_+1>>1,k=k+_+1>>1,_=P,P=ye*s+te*i+2048>>12,ye=ye*i-te*s+2048>>12,te=P,P=oe*r+ae*n+2048>>12,oe=oe*n-ae*r+2048>>12,ae=P,R[0+ne]=D+te,R[56+ne]=D-te,R[8+ne]=k+ae,R[48+ne]=k-ae,R[16+ne]=_+oe,R[40+ne]=_-oe,R[24+ne]=ke+ye,R[32+ne]=ke-ye}for(Re=0;Re<64;++Re){var gt=128+(R[Re]+8>>4);Ge[Re]=gt<0?0:gt>255?255:gt}}w(E*N*8);var U,ce;for(var j=0;j<N;j++){var H=j<<3;for(U=0;U<8;U++)S.push(new Uint8Array(E));for(var A=0;A<p;A++){L(y.blocks[j][A],O,F);var Q=0,Ne=A<<3;for(ce=0;ce<8;ce++){var $e=S[H+ce];for(U=0;U<8;U++)$e[Ne+U]=O[Q++]}}}return S}function g(M){return M<0?0:M>255?255:M}l.prototype={load:function(y){var S=new XMLHttpRequest;S.open("GET",y,!0),S.responseType="arraybuffer",S.onload=function(){var p=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(y){var S=this.opts.maxResolutionInMP*1000*1000,p=0,N=y.length;function E(){var K=y[p]<<8|y[p+1];return p+=2,K}function F(){var K=E(),ge=y.subarray(p,p+K-2);return p+=ge.length,ge}function O(K){var ge=1,Ye=1,Te,mt;for(mt in K.components)if(K.components.hasOwnProperty(mt)){if(Te=K.components[mt],ge<Te.h)ge=Te.h;if(Ye<Te.v)Ye=Te.v}var At=Math.ceil(K.samplesPerLine/8/ge),Cn=Math.ceil(K.scanLines/8/Ye);for(mt in K.components)if(K.components.hasOwnProperty(mt)){Te=K.components[mt];var dr=Math.ceil(Math.ceil(K.samplesPerLine/8)*Te.h/ge),gr=Math.ceil(Math.ceil(K.scanLines/8)*Te.v/Ye),si=At*Te.h,oi=Cn*Te.v,bs=oi*si,ai=[];w(bs*256);for(var ui=0;ui<oi;ui++){var ci=[];for(var li=0;li<si;li++)ci.push(new Int32Array(64));ai.push(ci)}Te.blocksPerLine=dr,Te.blocksPerColumn=gr,Te.blocks=ai}K.maxH=ge,K.maxV=Ye,K.mcusPerLine=At,K.mcusPerColumn=Cn}var L=null,U=null,ce=null,j,H,A=[],Q=[],Ne=[],$e=[],x=E(),Ge=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=E();while(x!=65497){var fe,se,D;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var k=F();if(x===65534){var _=String.fromCharCode.apply(null,k);this.comments.push(_)}if(x===65504){if(k[0]===74&&k[1]===70&&k[2]===73&&k[3]===70&&k[4]===0)L={version:{major:k[5],minor:k[6]},densityUnits:k[7],xDensity:k[8]<<8|k[9],yDensity:k[10]<<8|k[11],thumbWidth:k[12],thumbHeight:k[13],thumbData:k.subarray(14,14+3*k[12]*k[13])}}if(x===65505){if(k[0]===69&&k[1]===120&&k[2]===105&&k[3]===102&&k[4]===0)this.exifBuffer=k.subarray(5,k.length)}if(x===65518){if(k[0]===65&&k[1]===100&&k[2]===111&&k[3]===98&&k[4]===101&&k[5]===0)U={version:k[6],flags0:k[7]<<8|k[8],flags1:k[9]<<8|k[10],transformCode:k[11]}}break;case 65499:var ke=E(),ye=ke+p-2;while(p<ye){var oe=y[p++];w(256);var ae=new Int32Array(64);if(oe>>4===0)for(se=0;se<64;se++){var te=t[se];ae[te]=y[p++]}else if(oe>>4===1)for(se=0;se<64;se++){var te=t[se];ae[te]=E()}else throw Error("DQT: invalid table spec");A[oe&15]=ae}break;case 65472:case 65473:case 65474:E(),j={},j.extended=x===65473,j.progressive=x===65474,j.precision=y[p++],j.scanLines=E(),j.samplesPerLine=E(),j.components={},j.componentsOrder=[];var P=j.scanLines*j.samplesPerLine;if(P>S){var R=Math.ceil((P-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${R}MP`)}var Re=y[p++],q,ne=0,gt=0;for(fe=0;fe<Re;fe++){q=y[p];var vt=y[p+1]>>4,b=y[p+1]&15,G=y[p+2];if(vt<=0||b<=0)throw Error("Invalid sampling factor, expected values above 0");j.componentsOrder.push(q),j.components[q]={h:vt,v:b,quantizationIdx:G},p+=3}O(j),Q.push(j);break;case 65476:var J=E();for(fe=2;fe<J;){var C=y[p++],z=new Uint8Array(16),X=0;for(se=0;se<16;se++,p++)X+=z[se]=y[p];w(16+X);var le=new Uint8Array(X);for(se=0;se<X;se++,p++)le[se]=y[p];fe+=17+X,(C>>4===0?$e:Ne)[C&15]=h(z,le)}break;case 65501:E(),H=E();break;case 65500:E(),E();break;case 65498:var he=E(),Ue=y[p++],Oe=[],I;for(fe=0;fe<Ue;fe++){I=j.components[y[p++]];var T=y[p++];I.huffmanTableDC=$e[T>>4],I.huffmanTableAC=Ne[T&15],Oe.push(I)}var Y=y[p++],He=y[p++],B=y[p++],re=f(y,p,j,Oe,H,Y,He,B>>4,B&15,this.opts);p+=re;break;case 65535:if(y[p]!==255)p--;break;default:if(y[p-3]==255&&y[p-2]>=192&&y[p-2]<=254){p-=3;break}else if(x===224||x==225){if(Ge!==-1)throw Error(`first unknown JPEG marker at offset ${Ge.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(p-1).toString(16)}`);Ge=p-1;let K=E();if(y[p+K-2]===255){p+=K-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=E()}if(Q.length!=1)throw Error("only single frame JPEGs supported");for(var fe=0;fe<Q.length;fe++){var Ee=Q[fe].components;for(var se in Ee)Ee[se].quantizationTable=A[Ee[se].quantizationIdx],delete Ee[se].quantizationIdx}this.width=j.samplesPerLine,this.height=j.scanLines,this.jfif=L,this.adobe=U,this.components=[];for(var fe=0;fe<j.componentsOrder.length;fe++){var I=j.components[j.componentsOrder[fe]];this.components.push({lines:d(j,I),scaleX:I.h/j.maxH,scaleY:I.v/j.maxV})}},getData:function(y,S){var p=this.width/y,N=this.height/S,E,F,O,L,U,ce,j,H,A,Q,Ne=0,$e,x,Ge,fe,se,D,k,_,ke,ye,oe,ae=y*S*this.components.length;w(ae);var te=new Uint8Array(ae);switch(this.components.length){case 1:E=this.components[0];for(Q=0;Q<S;Q++){U=E.lines[0|Q*E.scaleY*N];for(A=0;A<y;A++)$e=U[0|A*E.scaleX*p],te[Ne++]=$e}break;case 2:E=this.components[0],F=this.components[1];for(Q=0;Q<S;Q++){U=E.lines[0|Q*E.scaleY*N],ce=F.lines[0|Q*F.scaleY*N];for(A=0;A<y;A++)$e=U[0|A*E.scaleX*p],te[Ne++]=$e,$e=ce[0|A*F.scaleX*p],te[Ne++]=$e}break;case 3:if(oe=!0,this.adobe&&this.adobe.transformCode)oe=!0;else if(typeof this.opts.colorTransform<"u")oe=!!this.opts.colorTransform;E=this.components[0],F=this.components[1],O=this.components[2];for(Q=0;Q<S;Q++){U=E.lines[0|Q*E.scaleY*N],ce=F.lines[0|Q*F.scaleY*N],j=O.lines[0|Q*O.scaleY*N];for(A=0;A<y;A++){if(!oe)_=U[0|A*E.scaleX*p],ke=ce[0|A*F.scaleX*p],ye=j[0|A*O.scaleX*p];else $e=U[0|A*E.scaleX*p],x=ce[0|A*F.scaleX*p],Ge=j[0|A*O.scaleX*p],_=g($e+1.402*(Ge-128)),ke=g($e-0.3441363*(x-128)-0.71413636*(Ge-128)),ye=g($e+1.772*(x-128));te[Ne++]=_,te[Ne++]=ke,te[Ne++]=ye}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(oe=!1,this.adobe&&this.adobe.transformCode)oe=!0;else if(typeof this.opts.colorTransform<"u")oe=!!this.opts.colorTransform;E=this.components[0],F=this.components[1],O=this.components[2],L=this.components[3];for(Q=0;Q<S;Q++){U=E.lines[0|Q*E.scaleY*N],ce=F.lines[0|Q*F.scaleY*N],j=O.lines[0|Q*O.scaleY*N],H=L.lines[0|Q*L.scaleY*N];for(A=0;A<y;A++){if(!oe)se=U[0|A*E.scaleX*p],D=ce[0|A*F.scaleX*p],k=j[0|A*O.scaleX*p],fe=H[0|A*L.scaleX*p];else $e=U[0|A*E.scaleX*p],x=ce[0|A*F.scaleX*p],Ge=j[0|A*O.scaleX*p],fe=H[0|A*L.scaleX*p],se=255-g($e+1.402*(Ge-128)),D=255-g($e-0.3441363*(x-128)-0.71413636*(Ge-128)),k=255-g($e+1.772*(x-128));te[Ne++]=255-se,te[Ne++]=255-D,te[Ne++]=255-k,te[Ne++]=255-fe}}break;default:throw Error("Unsupported color mode")}return te},copyToImageData:function(y,S){var{width:p,height:N,data:E}=y,F=this.getData(p,N),O=0,L=0,U,ce,j,H,A,Q,Ne,$e,x;switch(this.components.length){case 1:for(ce=0;ce<N;ce++)for(U=0;U<p;U++)if(j=F[O++],E[L++]=j,E[L++]=j,E[L++]=j,S)E[L++]=255;break;case 3:for(ce=0;ce<N;ce++)for(U=0;U<p;U++)if(Ne=F[O++],$e=F[O++],x=F[O++],E[L++]=Ne,E[L++]=$e,E[L++]=x,S)E[L++]=255;break;case 4:for(ce=0;ce<N;ce++)for(U=0;U<p;U++)if(A=F[O++],Q=F[O++],j=F[O++],H=F[O++],Ne=255-g(A*(1-H/255)+H),$e=255-g(Q*(1-H/255)+H),x=255-g(j*(1-H/255)+H),E[L++]=Ne,E[L++]=$e,E[L++]=x,S)E[L++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,$=0;function w(M=0){var y=m+M;if(y>$){var S=Math.ceil((y-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}m=y}return l.resetMaxMemoryUsage=function(M){m=0,$=M},l.getBytesAllocated=function(){return m},l.requestMemoryAllocation=w,l}();if(typeof Ha<"u")Ha.exports=sh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=sh;function sh(e,t={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...t},i=new Uint8Array(e),s=new Aa;s.opts=r,Aa.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{Aa.requestMemoryAllocation(a);var u={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(a):Buffer.alloc(a)};if(s.comments.length>0)u.comments=s.comments}catch(c){if(c instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+a);if(c instanceof ReferenceError){if(c.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw c}return s.copyToImageData(u,r.formatAsRGBA),u}});var uh=Fe((IM,ah)=>{var ub=ih(),cb=oh();ah.exports={encode:ub,decode:cb}});var La=Fe((NM,lh)=>{var lb=ze("util"),ch=ze("stream"),St=lh.exports=function(){ch.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};lb.inherits(St,ch);St.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};St.prototype.write=function(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(e))n=e;else n=Buffer.from(e,t||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};St.prototype.end=function(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};St.prototype.destroySoon=St.prototype.end;St.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};St.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};St.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)};St.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);while(t<e.length){let i=this._buffers[n++],s=Math.min(i.length,e.length-t);if(i.copy(r,t,0,s),t+=s,s!==i.length)this._buffers[--n]=i.slice(s)}if(n>0)this._buffers.splice(0,n);this._buffered-=e.length,e.func.call(this,r)};St.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 Ga=Fe((hb)=>{var $n=[{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]}];hb.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<$n.length;a++){let u=$n[a],c=s*u.x.length,l=o*u.y.length;for(let h=0;h<u.x.length;h++)if(u.x[h]<r)c++;else break;for(let h=0;h<u.y.length;h++)if(u.y[h]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};hb.getInterlaceIterator=function(e){return function(t,n,r){let i=t%$n[r].x.length,s=(t-i)/$n[r].x.length*8+$n[r].x[i],o=n%$n[r].y.length,a=(n-o)/$n[r].y.length*8+$n[r].y[o];return s*4+a*e*4}}});var Ua=Fe((OM,hh)=>{hh.exports=function(t,n,r){let i=t+n-r,s=Math.abs(i-t),o=Math.abs(i-n),a=Math.abs(i-r);if(s<=o&&s<=a)return t;if(o<=a)return n;return r}});var _a=Fe((FM,dh)=>{var gb=Ga(),mb=Ua();function fh(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var vr=dh.exports=function(e,t){let{width:n,height:r,interlace:i,bpp:s,depth:o}=e;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=gb.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:fh(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:fh(n,s,o),height:r,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};vr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};vr.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=e[1+s],a=s>i?t[s-r]:0;t[s]=o+a}};vr.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=e[1+i],o=r?r[i]:0;t[i]=s+o}};vr.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+u)/2);t[o]=a+l}};vr.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=o>i&&s?s[o-r]:0,h=mb(c,u,l);t[o]=a+h}};vr.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error("Unrecognised filter type - "+t)}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 ph=Fe((PM,mh)=>{var pb=ze("util"),gh=La(),wb=_a(),bb=mh.exports=function(e){gh.call(this);let t=[],n=this;this._filter=new wb(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};pb.inherits(bb,gh)});var Mr=Fe((TM,wh)=>{wh.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 Wa=Fe((AM,bh)=>{var Ca=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)if(t&1)t=3988292384^t>>>1;else t=t>>>1;Ca[e]=t}})();var ja=bh.exports=function(){this._crc=-1};ja.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=Ca[(this._crc^e[t])&255]^this._crc>>>8;return!0};ja.prototype.crc32=function(){return this._crc^-1};ja.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=Ca[(t^e[n])&255]^t>>>8;return t^-1}});var Ja=Fe((HM,$h)=>{var Ke=Mr(),$b=Wa(),Qe=$h.exports=function(e,t){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[Ke.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ke.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ke.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ke.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ke.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ke.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Qe.prototype.start=function(){this.read(Ke.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Qe.prototype._parseSignature=function(e){let t=Ke.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(e[s]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&n!==Ke.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new $b,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](t);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(t+4,this._skipChunk.bind(this))};Qe.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Qe.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error("Crc error - "+t+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Qe.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r=e[8],i=e[9],s=e[10],o=e[11],a=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ke.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(s!==0){this.error(Error("Unsupported compression method"));return}if(o!==0){this.error(Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Ke.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&Ke.COLORTYPE_PALETTE),color:Boolean(i&Ke.COLORTYPE_COLOR),alpha:Boolean(i&Ke.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Qe.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Qe.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Qe.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Qe.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ke.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 t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}if(this._colorType===Ke.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ke.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Qe.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Qe.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ke.GAMMA_DIVISION),this._handleChunkEnd()};Qe.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Qe.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Ke.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(t);let n=e-t.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Qe.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Qe.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ka=Fe((Sb)=>{var kh=Ga(),kb=[function(){},function(e,t,n,r){if(r===t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],yb=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function Eb(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let s=e[r];r++;let o,a,u,c,l,h,f,d;switch(t){default:throw Error("unrecognised depth");case 16:f=e[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,d=s>>4,n.push(d,f);break;case 2:l=s&3,h=s>>2&3,f=s>>4&3,d=s>>6&3,n.push(d,f,h,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,h=s>>5&1,f=s>>6&1,d=s>>7&1,n.push(d,f,h,l,c,u,a,o);break}}return{get:function(s){while(n.length<s)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function vb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++)for(let l=0;l<o;l++){let h=n(l,c,u);kb[r](t,i,h,s),s+=r}return s}function Mb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++){for(let l=0;l<o;l++){let h=i.get(r),f=n(l,c,u);yb[r](t,h,f,s)}i.resetAfterLine()}}Sb.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=Eb(e,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,l=0,h,f;if(o)h=kh.getImagePasses(n,r),f=kh.getInterlaceIterator(n,r);else{let d=0;f=function(){let g=d;return d+=4,g},h=[{width:n,height:r}]}for(let d=0;d<h.length;d++)if(i===8)l=vb(h[d],u,f,s,e,l);else Mb(h[d],u,f,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var qa=Fe((GM,yh)=>{function Nb(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=i[e[s]];if(!u)throw Error("index "+e[s]+" not in palette");for(let c=0;c<4;c++)t[s+c]=u[c];s+=4}}function Rb(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=!1;if(i.length===1){if(i[0]===e[s])u=!0}else if(i[0]===e[s]&&i[1]===e[s+1]&&i[2]===e[s+2])u=!0;if(u)for(let c=0;c<4;c++)t[s+c]=0;s+=4}}function Ob(e,t,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<r;u++)for(let c=0;c<n;c++){for(let l=0;l<4;l++)t[a+l]=Math.floor(e[a+l]*s/o+0.5);a+=4}}yh.exports=function(e,t,n=!1){let{depth:r,width:i,height:s,colorType:o,transColor:a,palette:u}=t,c=e;if(o===3)Nb(e,c,i,s,u);else{if(a)Rb(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);Ob(e,c,i,s,r)}}return c}});var Mh=Fe((UM,vh)=>{var Fb=ze("util"),Qa=ze("zlib"),Eh=La(),Pb=ph(),Tb=Ja(),Ab=Ka(),Hb=qa(),Gt=vh.exports=function(e){Eh.call(this),this._parser=new Tb(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()};Fb.inherits(Gt,Eh);Gt.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};Gt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Qa.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,Qa.Z_MIN_CHUNK);this._inflate=Qa.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Gt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new Pb(this._bitmapInfo)};Gt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Gt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Gt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Gt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Gt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Gt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=Ab.dataToBitMap(e,this._bitmapInfo);t=Hb(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Ih=Fe((_M,Sh)=>{var bt=Mr();Sh.exports=function(e,t,n,r){let i=[bt.COLORTYPE_COLOR_ALPHA,bt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=bt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=bt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,h=0,f=r.bgColor||{};if(f.red===void 0)f.red=o;if(f.green===void 0)f.green=o;if(f.blue===void 0)f.blue=o;function d(){let g,m,$,w=o;switch(r.inputColorType){case bt.COLORTYPE_COLOR_ALPHA:w=s[l+3],g=s[l],m=s[l+1],$=s[l+2];break;case bt.COLORTYPE_COLOR:g=s[l],m=s[l+1],$=s[l+2];break;case bt.COLORTYPE_ALPHA:w=s[l+1],g=s[l],m=g,$=g;break;case bt.COLORTYPE_GRAYSCALE:g=s[l],m=g,$=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)w/=o,g=Math.min(Math.max(Math.round((1-w)*f.red+w*g),0),o),m=Math.min(Math.max(Math.round((1-w)*f.green+w*m),0),o),$=Math.min(Math.max(Math.round((1-w)*f.blue+w*$),0),o)}return{red:g,green:m,blue:$,alpha:w}}for(let g=0;g<n;g++)for(let m=0;m<t;m++){let $=d(s,l);switch(r.colorType){case bt.COLORTYPE_COLOR_ALPHA:case bt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[h]=$.red,c[h+1]=$.green,c[h+2]=$.blue,i)c[h+3]=$.alpha}else if(c.writeUInt16BE($.red,h),c.writeUInt16BE($.green,h+2),c.writeUInt16BE($.blue,h+4),i)c.writeUInt16BE($.alpha,h+6);break;case bt.COLORTYPE_ALPHA:case bt.COLORTYPE_GRAYSCALE:{let w=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(c[h]=w,i)c[h+1]=$.alpha}else if(c.writeUInt16BE(w,h),i)c.writeUInt16BE($.alpha,h+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,h+=u}return c}});var Oh=Fe((CM,Rh)=>{var Nh=Ua();function Lb(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Gb(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Ub(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=e[t+o]-a;r[i+o]=u}}function _b(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=e[t+s]-o;i+=Math.abs(a)}return i}function Cb(e,t,n,r,i){for(let s=0;s<n;s++){let o=t>0?e[t+s-n]:0,a=e[t+s]-o;r[i+s]=a}}function jb(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=t>0?e[s-n]:0,a=e[s]-o;r+=Math.abs(a)}return r}function Wb(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=e[t+o]-(a+u>>1);r[i+o]=c}}function Jb(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=e[t+s]-(o+a>>1);i+=Math.abs(u)}return i}function Kb(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=t>0&&o>=s?e[t+o-(n+s)]:0,l=e[t+o]-Nh(a,u,c);r[i+o]=l}}function qb(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=t>0&&s>=r?e[t+s-(n+r)]:0,c=e[t+s]-Nh(o,a,u);i+=Math.abs(c)}return i}var Qb={0:Lb,1:Ub,2:Cb,3:Wb,4:Kb},Yb={0:Gb,1:_b,2:jb,3:Jb,4:qb};Rh.exports=function(e,t,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType==="number")s=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let o=t*i,a=0,u=0,c=Buffer.alloc((o+1)*n),l=s[0];for(let h=0;h<n;h++){if(s.length>1){let f=1/0;for(let d=0;d<s.length;d++){let g=Yb[s[d]](e,u,o,i);if(g<f)l=s[d],f=g}}c[a]=l,a++,Qb[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var Ya=Fe((jM,Fh)=>{var xe=Mr(),Zb=Wa(),zb=Ih(),Vb=Oh(),Xb=ze("zlib"),kn=Fh.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||Xb.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:xe.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:xe.COLORTYPE_COLOR_ALPHA,[xe.COLORTYPE_GRAYSCALE,xe.COLORTYPE_COLOR,xe.COLORTYPE_COLOR_ALPHA,xe.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([xe.COLORTYPE_GRAYSCALE,xe.COLORTYPE_COLOR,xe.COLORTYPE_COLOR_ALPHA,xe.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")};kn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};kn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};kn.prototype.filterData=function(e,t,n){let r=zb(e,t,n,this._options),i=xe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Vb(r,t,n,this._options,i)};kn.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(Zb.crc32(r.slice(4,r.length-4)),r.length-4),r};kn.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*xe.GAMMA_DIVISION),0),this._packChunk(xe.TYPE_gAMA,t)};kn.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(xe.TYPE_IHDR,n)};kn.prototype.packIDAT=function(e){return this._packChunk(xe.TYPE_IDAT,e)};kn.prototype.packIEND=function(){return this._packChunk(xe.TYPE_IEND,null)}});var Hh=Fe((WM,Ah)=>{var Bb=ze("util"),Ph=ze("stream"),xb=Mr(),Db=Ya(),Th=Ah.exports=function(e){Ph.call(this);let t=e||{};this._packer=new Db(t),this._deflate=this._packer.createDeflate(),this.readable=!0};Bb.inherits(Th,Ph);Th.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(xb.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var jh=Fe((wi,Ch)=>{var Lh=ze("assert").ok,Sr=ze("zlib"),e0=ze("util"),Gh=ze("buffer").kMaxLength;function Jn(e){if(!(this instanceof Jn))return new Jn(e);if(e&&e.chunkSize<Sr.Z_MIN_CHUNK)e.chunkSize=Sr.Z_MIN_CHUNK;if(Sr.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 t0(e){return new Jn(e)}function Uh(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Jn.prototype._processChunk=function(e,t,n){if(typeof n==="function")return Sr.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function h(g,m){if(r._hadError)return;let $=s-m;if(Lh($>=0,"have should not go down"),$>0){let w=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,w.length>o)w=w.slice(0,o);if(u.push(w),c+=w.length,o-=w.length,o===0)return!1}if(m===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(m===0)return a+=i-g,i=g,!0;return!1}Lh(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&h(f[0],f[1]));if(this._hadError)throw l;if(c>=Gh)throw Uh(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Gh.toString(16)+" bytes");let d=Buffer.concat(u,c);return Uh(this),d};e0.inherits(Jn,Sr.Inflate);function n0(e,t){if(typeof t==="string")t=Buffer.from(t);if(!(t instanceof Buffer))throw TypeError("Not a string or buffer");let n=e._finishFlushFlag;if(n==null)n=Sr.Z_FINISH;return e._processChunk(t,n)}function _h(e,t){return n0(new Jn(t),e)}Ch.exports=wi=_h;wi.Inflate=Jn;wi.createInflate=t0;wi.inflateSync=_h});var Za=Fe((JM,Jh)=>{var Wh=Jh.exports=function(e){this._buffer=e,this._reads=[]};Wh.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};Wh.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 t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.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 Kh=Fe((s0)=>{var r0=Za(),i0=_a();s0.process=function(e,t){let n=[],r=new r0(e);return new i0(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Zh=Fe((qM,Yh)=>{var qh=!0,Qh=ze("zlib"),a0=jh();if(!Qh.deflateSync)qh=!1;var u0=Za(),c0=Kh(),l0=Ja(),h0=Ka(),f0=qa();Yh.exports=function(e,t){if(!qh)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(S){n=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function u(){i.alpha=!0}let c;function l(S){c=S}let h=[];function f(S){h.push(S)}let d=new u0(e);if(new l0(t,{read:d.read.bind(d),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:f,simpleTransparency:u}).start(),d.process(),n)throw n;let m=Buffer.concat(h);h.length=0;let $;if(i.interlace)$=Qh.inflateSync(m);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=a0(m,{chunkSize:p,maxLength:p})}if(m=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let w=c0.process($,i);m=null;let M=h0.dataToBitMap(w,i);w=null;let y=f0(M,i,t.skipRescale);return i.data=y,i.gamma=c||0,i}});var Bh=Fe((QM,Xh)=>{var zh=!0,Vh=ze("zlib");if(!Vh.deflateSync)zh=!1;var d0=Mr(),g0=Ya();Xh.exports=function(e,t){if(!zh)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new g0(t||{}),i=[];if(i.push(Buffer.from(d0.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let s=r.filterData(e.data,e.width,e.height),o=Vh.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var xh=Fe((w0)=>{var m0=Zh(),p0=Bh();w0.read=function(e,t){return m0(e,t||{})};w0.write=function(e,t){return p0(e,t)}});var ef=Fe((M0)=>{var k0=ze("util"),Dh=ze("stream"),y0=Mh(),E0=Hh(),v0=xh(),tt=M0.PNG=function(e){if(Dh.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 y0(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(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new E0(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"))};k0.inherits(tt,Dh);tt.sync=v0;tt.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};tt.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};tt.prototype.write=function(e){return this._parser.write(e),!0};tt.prototype.end=function(e){this._parser.end(e)};tt.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};tt.prototype._gamma=function(e){this.gamma=e};tt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};tt.bitblt=function(e,t,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+s>e.height)throw Error("bitblt reading outside image");if(o>t.width||a>t.height||o+i>t.width||a+s>t.height)throw Error("bitblt writing outside image");for(let u=0;u<s;u++)e.data.copy(t.data,(a+u)*t.width+o<<2,(r+u)*e.width+n<<2,(r+u)*e.width+n+i<<2)};tt.prototype.bitblt=function(e,t,n,r,i,s,o){return tt.bitblt(this,e,t,n,r,i,s,o),this};tt.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let i=0;i<3;i++){let s=e.data[r+i]/255;s=Math.pow(s,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(s*255)}}e.gamma=0}};tt.prototype.adjustGamma=function(){tt.adjustGamma(this)}});import{spawnSync as Tv}from"node:child_process";import{isMainThread as Av}from"node:worker_threads";import{parseArgs as Iv}from"node:util";var Ve={name:"@kecan0406/ttheme",version:"1.1.1",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","fast-string-width":"^3.0.2","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{existsSync as wm,readdirSync as l1,readFileSync as bm}from"node:fs";import{basename as h1,join as $m}from"node:path";import{styleText as Ns}from"node:util";import{stdout as Nl,stdin as gw}from"node:process";import mw from"node:readline";var ll=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),hl=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},fl=(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 Dp=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ew=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,dl=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,tw=/\t{1,1000}/y,gl=/[\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,nw=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,rw=/\p{M}+/gu,iw={limit:1/0,ellipsis:""},ml=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?ml(i,iw,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,h=n.regularWidth??1,f=n.wideWidth??2,d=[[nw,h],[Dp,0],[ew,a],[tw,u],[gl,c],[dl,f]],g=0,m=0,$=e.length,w=0,M=!1,y=$,S=Math.max(0,r-s),p=0,N=0,E=0,F=0;e:while(!0){if(N>p||m>=$&&m>g){let O=e.slice(p,N)||e.slice(g,m);w=0;for(let L of O.replaceAll(rw,"")){let U=L.codePointAt(0)||0;if(hl(U))F=2;else if(fl(U))F=f;else F=h;if(E+F>S)y=Math.min(y,Math.max(p,g)+w);if(E+F>r){M=!0;break e}w+=L.length,E+=F}p=N=0}if(m>=$)break e;for(let O=0,L=d.length;O<L;O++){let[U,ce]=d[O];if(U.lastIndex=m,U.test(e)){if(w=U===dl?ll(e.slice(m,U.lastIndex)):U===gl?1:U.lastIndex-m,F=w*ce,E+F>S)y=Math.min(y,m+Math.floor((S-E)/ce));if(E+F>r){M=!0;break e}E+=F,p=g,N=m,m=g=U.lastIndex;continue e}}m+=1}return{width:M?S:E,index:M?y:$,truncated:M,ellipsed:M&&r>=s}},pl=ml;var sw={limit:1/0,ellipsis:"",ellipsisWidth:0},ow=(e,t={})=>{return pl(e,sw,t).width},Ce=ow;var vs="\x1B",yl="›",aw=39,la="\x07",El="[",uw="]",vl="m",ha=`${uw}8;;`,wl=new RegExp(`(?:\\${El}(?<code>\\d+)m|\\${ha}(?<uri>.*)${la})`,"y"),bl=(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},$l=(e)=>`${vs}${El}${e}${vl}`,kl=(e)=>`${vs}${ha}${e}${la}`,ca=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:Ce(o),u=r.next(),c=r.next(),l=0;while(!u.done){let h=u.value,f=Ce(h);if(a+f<=n)e[e.length-1]+=h;else e.push(h),a=0;if(h===vs||h===yl)i=!0,s=t.startsWith(ha,l+1);if(i){if(s){if(h===la)i=!1,s=!1}else if(h===vl)i=!1}else if(a+=f,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=h.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},cw=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Ce(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},lw=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let g=a.at(-1)??"",m=g.trimStart();if(g.length!==m.length)a[a.length-1]=m,u=Ce(m)}if(h!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let d=Ce(f);if(n.hard&&d>t){let g=t-u,m=1+Math.floor((d-g-1)/t);if(Math.floor((d-1)/t)<m)a.push("");ca(a,f,t),u=Ce(a.at(-1)??"");continue}if(u+d>t&&u&&d){if(n.wordWrap===!1&&u<t){ca(a,f,t),u=Ce(a.at(-1)??"");continue}a.push(""),u=0}if(u+d>t&&n.wordWrap===!1){ca(a,f,t),u=Ce(a.at(-1)??"");continue}a[a.length-1]+=f,u+=d}if(n.trim!==!1)a=a.map((h)=>cw(h));let c=a.join(`
3
- `),l=!1;for(let h=0;h<c.length;h++){let f=c[h];if(r+=f,!l){if(l=f>="\uD800"&&f<="\uDBFF",l)continue}else l=!1;if(f===vs||f===yl){wl.lastIndex=h+1;let g=wl.exec(c)?.groups;if(g?.code!==void 0){let m=Number.parseFloat(g.code);i=m===aw?void 0:m}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[h+1]===`
4
- `){if(s)r+=kl("");let d=i?bl(i):void 0;if(i&&d)r+=$l(d)}else if(f===`
5
- `){if(i&&bl(i))r+=$l(i);if(s)r+=kl(s)}}return r},hw=/\r?\n/;function fn(e,t,n){return String(e).normalize().split(hw).map((r)=>lw(r,t,n)).join(`
6
- `)}var at=Es(da(),1);function mr(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?mr(s,t<0?-1:1,n):s}function Ms(e,t,n,r){let i=r.split(`
7
- `),s=0,o=e;for(let u of i){if(o<=u.length)break;o-=u.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let u=0;u<s;u++)a+=i[u].length+1;return a+o}var pw=["up","down","left","right","space","enter","cancel"],ww=["January","February","March","April","May","June","July","August","September","October","November","December"],Xe={actions:new Set(pw),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:[...ww],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,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 Rl(e,t){if(typeof e=="string")return Xe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Rl(n,t))return!0;return!1}function bw(e,t){if(e===t)return;let n=e.split(`
2
+ import{createRequire as nw}from"node:module";var Vp=Object.create;var{getPrototypeOf:Xp,defineProperty:dl,getOwnPropertyNames:Bp}=Object;var xp=Object.prototype.hasOwnProperty;function Dp(e){return this[e]}var ew,tw,Rs=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?ew??=new WeakMap:tw??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?Vp(Xp(e)):{};let o=t||!e||!e.__esModule?dl(n,"default",{value:e,enumerable:!0}):n;for(let a of Bp(e))if(!xp.call(o,a))dl(o,a,{get:Dp.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ze=nw(import.meta.url);var wa=Oe((zv,Rl)=>{var pa={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},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"},ww={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},bw={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 t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?pa.up():"");if(e)t+=pa.left;return t}};Rl.exports={cursor:pa,scroll:ww,erase:bw,beep:"\x07"}});var uh=Oe((RM,Ys)=>{var ah=ah||function(e){return Buffer.from(e).toString("base64")};function fb(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,h,f=Array(65535),d=Array(65535),g=Array(64),m=Array(64),$=[],p=0,E=7,y=Array(64),S=Array(64),w=Array(64),N=Array(256),v=Array(2048),O,F=[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],U=[0,1,2,3,4,5,6,7,8,9,10,11],ce=[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],H=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],Q=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ne=[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 ke(b){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 C=r((G[J]*b+50)/100);if(C<1)C=1;else if(C>255)C=255;i[F[J]]=C}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 X=0;X<64;X++){var le=r((z[X]*b+50)/100);if(le<1)le=1;else if(le>255)le=255;s[F[X]]=le}var he=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var Fe=0;Fe<8;Fe++)for(var I=0;I<8;I++)o[Ue]=1/(i[F[Ue]]*he[Fe]*he[I]*8),a[Ue]=1/(s[F[Ue]]*he[Fe]*he[I]*8),Ue++}function x(b,G){var J=0,C=0,z=[];for(var X=1;X<=16;X++){for(var le=1;le<=b[X];le++)z[G[C]]=[],z[G[C]][0]=J,z[G[C]][1]=X,C++,J++;J*=2}return z}function Ge(){u=x(L,U),c=x(H,A),l=x(ce,j),h=x(Q,Ne)}function fe(){var b=1,G=2;for(var J=1;J<=15;J++){for(var C=b;C<G;C++)d[32767+C]=J,f[32767+C]=[],f[32767+C][1]=J,f[32767+C][0]=C;for(var z=-(G-1);z<=-b;z++)d[32767+z]=J,f[32767+z]=[],f[32767+z][1]=J,f[32767+z][0]=G-1+z;b<<=1,G<<=1}}function se(){for(var b=0;b<256;b++)v[b]=19595*b,v[b+256>>0]=38470*b,v[b+512>>0]=7471*b+32768,v[b+768>>0]=-11059*b,v[b+1024>>0]=-21709*b,v[b+1280>>0]=32768*b+8421375,v[b+1536>>0]=-27439*b,v[b+1792>>0]=-5329*b}function D(b){var G=b[0],J=b[1]-1;while(J>=0){if(G&1<<J)p|=1<<E;if(J--,E--,E<0){if(p==255)k(255),k(0);else k(p);E=7,p=0}}}function k(b){$.push(b)}function _(b){k(b>>8&255),k(b&255)}function ye(b,G){var J,C,z,X,le,he,Ue,Fe,I=0,T,Y=8,He=64;for(T=0;T<Y;++T){J=b[I],C=b[I+1],z=b[I+2],X=b[I+3],le=b[I+4],he=b[I+5],Ue=b[I+6],Fe=b[I+7];var B=J+Fe,re=J-Fe,ve=C+Ue,K=C-Ue,ge=z+he,Ye=z-he,Te=X+le,mt=X-le,At=B+Te,_n=B-Te,dr=ve+ge,gr=ve-ge;b[I]=At+dr,b[I+4]=At-dr;var si=(gr+_n)*0.707106781;b[I+2]=_n+si,b[I+6]=_n-si,At=mt+Ye,dr=Ye+K,gr=K+re;var oi=(At-gr)*0.382683433,Ms=0.5411961*At+oi,ai=1.306562965*gr+oi,ui=dr*0.707106781,ci=re+ui,li=re-ui;b[I+5]=li+Ms,b[I+3]=li-Ms,b[I+1]=ci+ai,b[I+7]=ci-ai,I+=8}I=0;for(T=0;T<Y;++T){J=b[I],C=b[I+8],z=b[I+16],X=b[I+24],le=b[I+32],he=b[I+40],Ue=b[I+48],Fe=b[I+56];var el=J+Fe,ha=J-Fe,tl=C+Ue,nl=C-Ue,rl=z+he,il=z-he,sl=X+le,zp=X-le,hi=el+sl,fa=el-sl,Ss=tl+rl,Is=tl-rl;b[I]=hi+Ss,b[I+32]=hi-Ss;var ol=(Is+fa)*0.707106781;b[I+16]=fa+ol,b[I+48]=fa-ol,hi=zp+il,Ss=il+nl,Is=nl+ha;var al=(hi-Is)*0.382683433,ul=0.5411961*hi+al,cl=1.306562965*Is+al,ll=Ss*0.707106781,hl=ha+ll,fl=ha-ll;b[I+40]=fl+ul,b[I+24]=fl-ul,b[I+8]=hl+cl,b[I+56]=hl-cl,I++}var Ns;for(T=0;T<He;++T)Ns=b[T]*G[T],g[T]=Ns>0?Ns+0.5|0:Ns-0.5|0;return g}function Ee(){_(65504),_(16),k(74),k(70),k(73),k(70),k(0),k(1),k(1),k(0),_(1),_(1),k(0),k(0)}function oe(b){if(!b)return;if(_(65505),b[0]===69&&b[1]===120&&b[2]===105&&b[3]===102)_(b.length+2);else _(b.length+5+2),k(69),k(120),k(105),k(102),k(0);for(var G=0;G<b.length;G++)k(b[G])}function ae(b,G){_(65472),_(17),k(8),_(G),_(b),k(3),k(1),k(17),k(0),k(2),k(17),k(1),k(3),k(17),k(1)}function te(){_(65499),_(132),k(0);for(var b=0;b<64;b++)k(i[b]);k(1);for(var G=0;G<64;G++)k(s[G])}function P(){_(65476),_(418),k(0);for(var b=0;b<16;b++)k(L[b+1]);for(var G=0;G<=11;G++)k(U[G]);k(16);for(var J=0;J<16;J++)k(ce[J+1]);for(var C=0;C<=161;C++)k(j[C]);k(1);for(var z=0;z<16;z++)k(H[z+1]);for(var X=0;X<=11;X++)k(A[X]);k(17);for(var le=0;le<16;le++)k(Q[le+1]);for(var he=0;he<=161;he++)k(Ne[he])}function R(b){if(typeof b>"u"||b.constructor!==Array)return;b.forEach((G)=>{if(typeof G!=="string")return;_(65534);var J=G.length;_(J+2);var C;for(C=0;C<J;C++)k(G.charCodeAt(C))})}function Re(){_(65498),_(12),k(3),k(1),k(0),k(2),k(17),k(3),k(17),k(0),k(63),k(0)}function q(b,G,J,C,z){var X=z[0],le=z[240],he,Ue=16,Fe=63,I=64,T=ye(b,G);for(var Y=0;Y<I;++Y)m[F[Y]]=T[Y];var He=m[0]-J;if(J=m[0],He==0)D(C[0]);else he=32767+He,D(C[d[he]]),D(f[he]);var B=63;for(;B>0&&m[B]==0;B--);if(B==0)return D(X),J;var re=1,ve;while(re<=B){var K=re;for(;m[re]==0&&re<=B;++re);var ge=re-K;if(ge>=Ue){ve=ge>>4;for(var Ye=1;Ye<=ve;++Ye)D(le);ge=ge&15}he=32767+m[re],D(z[(ge<<4)+d[he]]),D(f[he]),re++}if(B!=Fe)D(X);return J}function ne(){var b=String.fromCharCode;for(var G=0;G<256;G++)N[G]=b(G)}this.encode=function(b,G){var J=new Date().getTime();if(G)gt(G);$=[],p=0,E=7,_(65496),Ee(),R(b.comments),oe(b.exifBuffer),te(),ae(b.width,b.height),P(),Re();var C=0,z=0,X=0;p=0,E=7,this.encode.displayName="_encode_";var{data:le,width:he,height:Ue}=b,Fe=he*4,I=he*3,T,Y=0,He,B,re,ve,K,ge,Ye,Te;while(Y<Ue){T=0;while(T<Fe){ve=Fe*Y+T,K=ve,ge=-1,Ye=0;for(Te=0;Te<64;Te++){if(Ye=Te>>3,ge=(Te&7)*4,K=ve+Ye*Fe+ge,Y+Ye>=Ue)K-=Fe*(Y+1+Ye-Ue);if(T+ge>=Fe)K-=T+ge-Fe+4;He=le[K++],B=le[K++],re=le[K++],y[Te]=(v[He]+v[B+256>>0]+v[re+512>>0]>>16)-128,S[Te]=(v[He+768>>0]+v[B+1024>>0]+v[re+1280>>0]>>16)-128,w[Te]=(v[He+1280>>0]+v[B+1536>>0]+v[re+1792>>0]>>16)-128}C=q(y,o,C,u,l),z=q(S,a,z,c,h),X=q(w,a,X,c,h),T+=32}Y+=8}if(E>=0){var mt=[];mt[1]=E+1,mt[0]=(1<<E+1)-1,D(mt)}if(_(65497),typeof Ys>"u")return new Uint8Array($);return Buffer.from($);var At,_n};function gt(b){if(b<=0)b=1;if(b>100)b=100;if(O==b)return;var G=0;if(b<50)G=Math.floor(5000/b);else G=Math.floor(200-b*2);ke(G),O=b}function vt(){var b=new Date().getTime();if(!e)e=50;ne(),Ge(),fe(),se(),gt(e);var G=new Date().getTime()-b}vt()}if(typeof Ys<"u")Ys.exports=oh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=oh;function oh(e,t){if(typeof t>"u")t=50;var n=new fb(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var lh=Oe((FM,_a)=>{var Ua=function(){var t=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,s=2276,o=1567,a=3784,u=5793,c=2896;function l(){}function h(E,y){var S=0,w=[],N,v,O=16;while(O>0&&!E[O-1])O--;w.push({children:[],index:0});var F=w[0],L;for(N=0;N<O;N++){for(v=0;v<E[N];v++){F=w.pop(),F.children[F.index]=y[S];while(F.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");F=w.pop()}F.index++,w.push(F);while(w.length<=N)w.push(L={children:[],index:0}),F.children[F.index]=L.children,F=L;S++}if(N+1<O)w.push(L={children:[],index:0}),F.children[F.index]=L.children,F=L}return w[0].children}function f(E,y,S,w,N,v,O,F,L,U){var{precision:ce,samplesPerLine:j,scanLines:H,mcusPerLine:A,progressive:Q,maxH:Ne,maxV:ke}=S,x=y,Ge=0,fe=0;function se(){if(fe>0)return fe--,Ge>>fe&1;if(Ge=E[y++],Ge==255){var I=E[y++];if(I)throw Error("unexpected marker: "+(Ge<<8|I).toString(16))}return fe=7,Ge>>>7}function D(I){var T=I,Y;while((Y=se())!==null){if(T=T[Y],typeof T==="number")return T;if(typeof T!=="object")throw Error("invalid huffman sequence")}return null}function k(I){var T=0;while(I>0){var Y=se();if(Y===null)return;T=T<<1|Y,I--}return T}function _(I){var T=k(I);if(T>=1<<I-1)return T;return T+(-1<<I)+1}function ye(I,T){var Y=D(I.huffmanTableDC),He=Y===0?0:_(Y);T[0]=I.pred+=He;var B=1;while(B<64){var re=D(I.huffmanTableAC),ve=re&15,K=re>>4;if(ve===0){if(K<15)break;B+=16;continue}B+=K;var ge=t[B];T[ge]=_(ve),B++}}function Ee(I,T){var Y=D(I.huffmanTableDC),He=Y===0?0:_(Y)<<L;T[0]=I.pred+=He}function oe(I,T){T[0]|=se()<<L}var ae=0;function te(I,T){if(ae>0){ae--;return}var Y=v,He=O;while(Y<=He){var B=D(I.huffmanTableAC),re=B&15,ve=B>>4;if(re===0){if(ve<15){ae=k(ve)+(1<<ve)-1;break}Y+=16;continue}Y+=ve;var K=t[Y];T[K]=_(re)*(1<<L),Y++}}var P=0,R;function Re(I,T){var Y=v,He=O,B=0;while(Y<=He){var re=t[Y],ve=T[re]<0?-1:1;switch(P){case 0:var K=D(I.huffmanTableAC),ge=K&15,B=K>>4;if(ge===0)if(B<15)ae=k(B)+(1<<B),P=4;else B=16,P=1;else{if(ge!==1)throw Error("invalid ACn encoding");R=_(ge),P=B?2:3}continue;case 1:case 2:if(T[re])T[re]+=(se()<<L)*ve;else if(B--,B===0)P=P==2?3:0;break;case 3:if(T[re])T[re]+=(se()<<L)*ve;else T[re]=R<<L,P=0;break;case 4:if(T[re])T[re]+=(se()<<L)*ve;break}Y++}if(P===4){if(ae--,ae===0)P=0}}function q(I,T,Y,He,B){var re=Y/A|0,ve=Y%A,K=re*I.v+He,ge=ve*I.h+B;if(I.blocks[K]===void 0&&U.tolerantDecoding)return;T(I,I.blocks[K][ge])}function ne(I,T,Y){var He=Y/I.blocksPerLine|0,B=Y%I.blocksPerLine;if(I.blocks[He]===void 0&&U.tolerantDecoding)return;T(I,I.blocks[He][B])}var gt=w.length,vt,b,G,J,C,z;if(Q)if(v===0)z=F===0?Ee:oe;else z=F===0?te:Re;else z=ye;var X=0,le,he;if(gt==1)he=w[0].blocksPerLine*w[0].blocksPerColumn;else he=A*S.mcusPerColumn;if(!N)N=he;var Ue,Fe;while(X<he){for(b=0;b<gt;b++)w[b].pred=0;if(ae=0,gt==1){vt=w[0];for(C=0;C<N;C++)ne(vt,z,X),X++}else for(C=0;C<N;C++){for(b=0;b<gt;b++){vt=w[b],Ue=vt.h,Fe=vt.v;for(G=0;G<Fe;G++)for(J=0;J<Ue;J++)q(vt,z,X,G,J)}if(X++,X===he)break}if(X===he)do{if(E[y]===255){if(E[y+1]!==0)break}y+=1}while(y<E.length-2);if(fe=0,le=E[y]<<8|E[y+1],le<65280)throw Error("marker was not found");if(le>=65488&&le<=65495)y+=2;else break}return y-x}function d(E,y){var S=[],w=y.blocksPerLine,N=y.blocksPerColumn,v=w<<3,O=new Int32Array(64),F=new Uint8Array(64);function L(x,Ge,fe){var se=y.quantizationTable,D,k,_,ye,Ee,oe,ae,te,P,R=fe,Re;for(Re=0;Re<64;Re++)R[Re]=x[Re]*se[Re];for(Re=0;Re<8;++Re){var q=8*Re;if(R[1+q]==0&&R[2+q]==0&&R[3+q]==0&&R[4+q]==0&&R[5+q]==0&&R[6+q]==0&&R[7+q]==0){P=u*R[0+q]+512>>10,R[0+q]=P,R[1+q]=P,R[2+q]=P,R[3+q]=P,R[4+q]=P,R[5+q]=P,R[6+q]=P,R[7+q]=P;continue}D=u*R[0+q]+128>>8,k=u*R[4+q]+128>>8,_=R[2+q],ye=R[6+q],Ee=c*(R[1+q]-R[7+q])+128>>8,te=c*(R[1+q]+R[7+q])+128>>8,oe=R[3+q]<<4,ae=R[5+q]<<4,P=D-k+1>>1,D=D+k+1>>1,k=P,P=_*a+ye*o+128>>8,_=_*o-ye*a+128>>8,ye=P,P=Ee-ae+1>>1,Ee=Ee+ae+1>>1,ae=P,P=te+oe+1>>1,oe=te-oe+1>>1,te=P,P=D-ye+1>>1,D=D+ye+1>>1,ye=P,P=k-_+1>>1,k=k+_+1>>1,_=P,P=Ee*s+te*i+2048>>12,Ee=Ee*i-te*s+2048>>12,te=P,P=oe*r+ae*n+2048>>12,oe=oe*n-ae*r+2048>>12,ae=P,R[0+q]=D+te,R[7+q]=D-te,R[1+q]=k+ae,R[6+q]=k-ae,R[2+q]=_+oe,R[5+q]=_-oe,R[3+q]=ye+Ee,R[4+q]=ye-Ee}for(Re=0;Re<8;++Re){var ne=Re;if(R[8+ne]==0&&R[16+ne]==0&&R[24+ne]==0&&R[32+ne]==0&&R[40+ne]==0&&R[48+ne]==0&&R[56+ne]==0){P=u*fe[Re+0]+8192>>14,R[0+ne]=P,R[8+ne]=P,R[16+ne]=P,R[24+ne]=P,R[32+ne]=P,R[40+ne]=P,R[48+ne]=P,R[56+ne]=P;continue}D=u*R[0+ne]+2048>>12,k=u*R[32+ne]+2048>>12,_=R[16+ne],ye=R[48+ne],Ee=c*(R[8+ne]-R[56+ne])+2048>>12,te=c*(R[8+ne]+R[56+ne])+2048>>12,oe=R[24+ne],ae=R[40+ne],P=D-k+1>>1,D=D+k+1>>1,k=P,P=_*a+ye*o+2048>>12,_=_*o-ye*a+2048>>12,ye=P,P=Ee-ae+1>>1,Ee=Ee+ae+1>>1,ae=P,P=te+oe+1>>1,oe=te-oe+1>>1,te=P,P=D-ye+1>>1,D=D+ye+1>>1,ye=P,P=k-_+1>>1,k=k+_+1>>1,_=P,P=Ee*s+te*i+2048>>12,Ee=Ee*i-te*s+2048>>12,te=P,P=oe*r+ae*n+2048>>12,oe=oe*n-ae*r+2048>>12,ae=P,R[0+ne]=D+te,R[56+ne]=D-te,R[8+ne]=k+ae,R[48+ne]=k-ae,R[16+ne]=_+oe,R[40+ne]=_-oe,R[24+ne]=ye+Ee,R[32+ne]=ye-Ee}for(Re=0;Re<64;++Re){var gt=128+(R[Re]+8>>4);Ge[Re]=gt<0?0:gt>255?255:gt}}p(v*N*8);var U,ce;for(var j=0;j<N;j++){var H=j<<3;for(U=0;U<8;U++)S.push(new Uint8Array(v));for(var A=0;A<w;A++){L(y.blocks[j][A],F,O);var Q=0,Ne=A<<3;for(ce=0;ce<8;ce++){var ke=S[H+ce];for(U=0;U<8;U++)ke[Ne+U]=F[Q++]}}}return S}function g(E){return E<0?0:E>255?255:E}l.prototype={load:function(y){var S=new XMLHttpRequest;S.open("GET",y,!0),S.responseType="arraybuffer",S.onload=function(){var w=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(y){var S=this.opts.maxResolutionInMP*1000*1000,w=0,N=y.length;function v(){var K=y[w]<<8|y[w+1];return w+=2,K}function O(){var K=v(),ge=y.subarray(w,w+K-2);return w+=ge.length,ge}function F(K){var ge=1,Ye=1,Te,mt;for(mt in K.components)if(K.components.hasOwnProperty(mt)){if(Te=K.components[mt],ge<Te.h)ge=Te.h;if(Ye<Te.v)Ye=Te.v}var At=Math.ceil(K.samplesPerLine/8/ge),_n=Math.ceil(K.scanLines/8/Ye);for(mt in K.components)if(K.components.hasOwnProperty(mt)){Te=K.components[mt];var dr=Math.ceil(Math.ceil(K.samplesPerLine/8)*Te.h/ge),gr=Math.ceil(Math.ceil(K.scanLines/8)*Te.v/Ye),si=At*Te.h,oi=_n*Te.v,Ms=oi*si,ai=[];p(Ms*256);for(var ui=0;ui<oi;ui++){var ci=[];for(var li=0;li<si;li++)ci.push(new Int32Array(64));ai.push(ci)}Te.blocksPerLine=dr,Te.blocksPerColumn=gr,Te.blocks=ai}K.maxH=ge,K.maxV=Ye,K.mcusPerLine=At,K.mcusPerColumn=_n}var L=null,U=null,ce=null,j,H,A=[],Q=[],Ne=[],ke=[],x=v(),Ge=-1;if(this.comments=[],x!=65496)throw Error("SOI not found");x=v();while(x!=65497){var fe,se,D;switch(x){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var k=O();if(x===65534){var _=String.fromCharCode.apply(null,k);this.comments.push(_)}if(x===65504){if(k[0]===74&&k[1]===70&&k[2]===73&&k[3]===70&&k[4]===0)L={version:{major:k[5],minor:k[6]},densityUnits:k[7],xDensity:k[8]<<8|k[9],yDensity:k[10]<<8|k[11],thumbWidth:k[12],thumbHeight:k[13],thumbData:k.subarray(14,14+3*k[12]*k[13])}}if(x===65505){if(k[0]===69&&k[1]===120&&k[2]===105&&k[3]===102&&k[4]===0)this.exifBuffer=k.subarray(5,k.length)}if(x===65518){if(k[0]===65&&k[1]===100&&k[2]===111&&k[3]===98&&k[4]===101&&k[5]===0)U={version:k[6],flags0:k[7]<<8|k[8],flags1:k[9]<<8|k[10],transformCode:k[11]}}break;case 65499:var ye=v(),Ee=ye+w-2;while(w<Ee){var oe=y[w++];p(256);var ae=new Int32Array(64);if(oe>>4===0)for(se=0;se<64;se++){var te=t[se];ae[te]=y[w++]}else if(oe>>4===1)for(se=0;se<64;se++){var te=t[se];ae[te]=v()}else throw Error("DQT: invalid table spec");A[oe&15]=ae}break;case 65472:case 65473:case 65474:v(),j={},j.extended=x===65473,j.progressive=x===65474,j.precision=y[w++],j.scanLines=v(),j.samplesPerLine=v(),j.components={},j.componentsOrder=[];var P=j.scanLines*j.samplesPerLine;if(P>S){var R=Math.ceil((P-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${R}MP`)}var Re=y[w++],q,ne=0,gt=0;for(fe=0;fe<Re;fe++){q=y[w];var vt=y[w+1]>>4,b=y[w+1]&15,G=y[w+2];if(vt<=0||b<=0)throw Error("Invalid sampling factor, expected values above 0");j.componentsOrder.push(q),j.components[q]={h:vt,v:b,quantizationIdx:G},w+=3}F(j),Q.push(j);break;case 65476:var J=v();for(fe=2;fe<J;){var C=y[w++],z=new Uint8Array(16),X=0;for(se=0;se<16;se++,w++)X+=z[se]=y[w];p(16+X);var le=new Uint8Array(X);for(se=0;se<X;se++,w++)le[se]=y[w];fe+=17+X,(C>>4===0?ke:Ne)[C&15]=h(z,le)}break;case 65501:v(),H=v();break;case 65500:v(),v();break;case 65498:var he=v(),Ue=y[w++],Fe=[],I;for(fe=0;fe<Ue;fe++){I=j.components[y[w++]];var T=y[w++];I.huffmanTableDC=ke[T>>4],I.huffmanTableAC=Ne[T&15],Fe.push(I)}var Y=y[w++],He=y[w++],B=y[w++],re=f(y,w,j,Fe,H,Y,He,B>>4,B&15,this.opts);w+=re;break;case 65535:if(y[w]!==255)w--;break;default:if(y[w-3]==255&&y[w-2]>=192&&y[w-2]<=254){w-=3;break}else if(x===224||x==225){if(Ge!==-1)throw Error(`first unknown JPEG marker at offset ${Ge.toString(16)}, second unknown JPEG marker ${x.toString(16)} at offset ${(w-1).toString(16)}`);Ge=w-1;let K=v();if(y[w+K-2]===255){w+=K-2;break}}throw Error("unknown JPEG marker "+x.toString(16))}x=v()}if(Q.length!=1)throw Error("only single frame JPEGs supported");for(var fe=0;fe<Q.length;fe++){var ve=Q[fe].components;for(var se in ve)ve[se].quantizationTable=A[ve[se].quantizationIdx],delete ve[se].quantizationIdx}this.width=j.samplesPerLine,this.height=j.scanLines,this.jfif=L,this.adobe=U,this.components=[];for(var fe=0;fe<j.componentsOrder.length;fe++){var I=j.components[j.componentsOrder[fe]];this.components.push({lines:d(j,I),scaleX:I.h/j.maxH,scaleY:I.v/j.maxV})}},getData:function(y,S){var w=this.width/y,N=this.height/S,v,O,F,L,U,ce,j,H,A,Q,Ne=0,ke,x,Ge,fe,se,D,k,_,ye,Ee,oe,ae=y*S*this.components.length;p(ae);var te=new Uint8Array(ae);switch(this.components.length){case 1:v=this.components[0];for(Q=0;Q<S;Q++){U=v.lines[0|Q*v.scaleY*N];for(A=0;A<y;A++)ke=U[0|A*v.scaleX*w],te[Ne++]=ke}break;case 2:v=this.components[0],O=this.components[1];for(Q=0;Q<S;Q++){U=v.lines[0|Q*v.scaleY*N],ce=O.lines[0|Q*O.scaleY*N];for(A=0;A<y;A++)ke=U[0|A*v.scaleX*w],te[Ne++]=ke,ke=ce[0|A*O.scaleX*w],te[Ne++]=ke}break;case 3:if(oe=!0,this.adobe&&this.adobe.transformCode)oe=!0;else if(typeof this.opts.colorTransform<"u")oe=!!this.opts.colorTransform;v=this.components[0],O=this.components[1],F=this.components[2];for(Q=0;Q<S;Q++){U=v.lines[0|Q*v.scaleY*N],ce=O.lines[0|Q*O.scaleY*N],j=F.lines[0|Q*F.scaleY*N];for(A=0;A<y;A++){if(!oe)_=U[0|A*v.scaleX*w],ye=ce[0|A*O.scaleX*w],Ee=j[0|A*F.scaleX*w];else ke=U[0|A*v.scaleX*w],x=ce[0|A*O.scaleX*w],Ge=j[0|A*F.scaleX*w],_=g(ke+1.402*(Ge-128)),ye=g(ke-0.3441363*(x-128)-0.71413636*(Ge-128)),Ee=g(ke+1.772*(x-128));te[Ne++]=_,te[Ne++]=ye,te[Ne++]=Ee}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(oe=!1,this.adobe&&this.adobe.transformCode)oe=!0;else if(typeof this.opts.colorTransform<"u")oe=!!this.opts.colorTransform;v=this.components[0],O=this.components[1],F=this.components[2],L=this.components[3];for(Q=0;Q<S;Q++){U=v.lines[0|Q*v.scaleY*N],ce=O.lines[0|Q*O.scaleY*N],j=F.lines[0|Q*F.scaleY*N],H=L.lines[0|Q*L.scaleY*N];for(A=0;A<y;A++){if(!oe)se=U[0|A*v.scaleX*w],D=ce[0|A*O.scaleX*w],k=j[0|A*F.scaleX*w],fe=H[0|A*L.scaleX*w];else ke=U[0|A*v.scaleX*w],x=ce[0|A*O.scaleX*w],Ge=j[0|A*F.scaleX*w],fe=H[0|A*L.scaleX*w],se=255-g(ke+1.402*(Ge-128)),D=255-g(ke-0.3441363*(x-128)-0.71413636*(Ge-128)),k=255-g(ke+1.772*(x-128));te[Ne++]=255-se,te[Ne++]=255-D,te[Ne++]=255-k,te[Ne++]=255-fe}}break;default:throw Error("Unsupported color mode")}return te},copyToImageData:function(y,S){var{width:w,height:N,data:v}=y,O=this.getData(w,N),F=0,L=0,U,ce,j,H,A,Q,Ne,ke,x;switch(this.components.length){case 1:for(ce=0;ce<N;ce++)for(U=0;U<w;U++)if(j=O[F++],v[L++]=j,v[L++]=j,v[L++]=j,S)v[L++]=255;break;case 3:for(ce=0;ce<N;ce++)for(U=0;U<w;U++)if(Ne=O[F++],ke=O[F++],x=O[F++],v[L++]=Ne,v[L++]=ke,v[L++]=x,S)v[L++]=255;break;case 4:for(ce=0;ce<N;ce++)for(U=0;U<w;U++)if(A=O[F++],Q=O[F++],j=O[F++],H=O[F++],Ne=255-g(A*(1-H/255)+H),ke=255-g(Q*(1-H/255)+H),x=255-g(j*(1-H/255)+H),v[L++]=Ne,v[L++]=ke,v[L++]=x,S)v[L++]=255;break;default:throw Error("Unsupported color mode")}}};var m=0,$=0;function p(E=0){var y=m+E;if(y>$){var S=Math.ceil((y-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}m=y}return l.resetMaxMemoryUsage=function(E){m=0,$=E},l.getBytesAllocated=function(){return m},l.requestMemoryAllocation=p,l}();if(typeof _a<"u")_a.exports=ch;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=ch;function ch(e,t={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...t},i=new Uint8Array(e),s=new Ua;s.opts=r,Ua.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{Ua.requestMemoryAllocation(a);var u={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(a):Buffer.alloc(a)};if(s.comments.length>0)u.comments=s.comments}catch(c){if(c instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+a);if(c instanceof ReferenceError){if(c.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw c}return s.copyToImageData(u,r.formatAsRGBA),u}});var fh=Oe((OM,hh)=>{var db=uh(),gb=lh();hh.exports={encode:db,decode:gb}});var Ca=Oe((PM,gh)=>{var mb=ze("util"),dh=ze("stream"),St=gh.exports=function(){dh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};mb.inherits(St,dh);St.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};St.prototype.write=function(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(e))n=e;else n=Buffer.from(e,t||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};St.prototype.end=function(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};St.prototype.destroySoon=St.prototype.end;St.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};St.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};St.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)};St.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);while(t<e.length){let i=this._buffers[n++],s=Math.min(i.length,e.length-t);if(i.copy(r,t,0,s),t+=s,s!==i.length)this._buffers[--n]=i.slice(s)}if(n>0)this._buffers.splice(0,n);this._buffered-=e.length,e.func.call(this,r)};St.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 ja=Oe((pb)=>{var wn=[{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]}];pb.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<wn.length;a++){let u=wn[a],c=s*u.x.length,l=o*u.y.length;for(let h=0;h<u.x.length;h++)if(u.x[h]<r)c++;else break;for(let h=0;h<u.y.length;h++)if(u.y[h]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};pb.getInterlaceIterator=function(e){return function(t,n,r){let i=t%wn[r].x.length,s=(t-i)/wn[r].x.length*8+wn[r].x[i],o=n%wn[r].y.length,a=(n-o)/wn[r].y.length*8+wn[r].y[o];return s*4+a*e*4}}});var Wa=Oe((AM,mh)=>{mh.exports=function(t,n,r){let i=t+n-r,s=Math.abs(i-t),o=Math.abs(i-n),a=Math.abs(i-r);if(s<=o&&s<=a)return t;if(o<=a)return n;return r}});var Ja=Oe((HM,wh)=>{var $b=ja(),kb=Wa();function ph(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var vr=wh.exports=function(e,t){let{width:n,height:r,interlace:i,bpp:s,depth:o}=e;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=$b.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:ph(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:ph(n,s,o),height:r,lineIndex:0});if(o===8)this._xComparison=s;else if(o===16)this._xComparison=s*2;else this._xComparison=1};vr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};vr.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let s=0;s<n;s++){let o=e[1+s],a=s>i?t[s-r]:0;t[s]=o+a}};vr.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let s=e[1+i],o=r?r[i]:0;t[i]=s+o}};vr.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+u)/2);t[o]=a+l}};vr.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=o>i&&s?s[o-r]:0,h=kb(c,u,l);t[o]=a+h}};vr.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error("Unrecognised filter type - "+t)}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 kh=Oe((LM,$h)=>{var yb=ze("util"),bh=Ca(),Eb=Ja(),vb=$h.exports=function(e){bh.call(this);let t=[],n=this;this._filter=new Eb(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};yb.inherits(vb,bh)});var Mr=Oe((GM,yh)=>{yh.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 Qa=Oe((UM,Eh)=>{var Ka=[];(function(){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)if(t&1)t=3988292384^t>>>1;else t=t>>>1;Ka[e]=t}})();var qa=Eh.exports=function(){this._crc=-1};qa.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=Ka[(this._crc^e[t])&255]^this._crc>>>8;return!0};qa.prototype.crc32=function(){return this._crc^-1};qa.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=Ka[(t^e[n])&255]^t>>>8;return t^-1}});var Ya=Oe((_M,vh)=>{var Ke=Mr(),Mb=Qa(),Qe=vh.exports=function(e,t){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[Ke.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ke.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ke.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ke.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ke.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ke.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};Qe.prototype.start=function(){this.read(Ke.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Qe.prototype._parseSignature=function(e){let t=Ke.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(e[s]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&n!==Ke.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Mb,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](t);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(t+4,this._skipChunk.bind(this))};Qe.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Qe.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error("Crc error - "+t+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Qe.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};Qe.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r=e[8],i=e[9],s=e[10],o=e[11],a=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ke.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(s!==0){this.error(Error("Unsupported compression method"));return}if(o!==0){this.error(Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Ke.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&Ke.COLORTYPE_PALETTE),color:Boolean(i&Ke.COLORTYPE_COLOR),alpha:Boolean(i&Ke.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Qe.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};Qe.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Qe.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};Qe.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ke.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 t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}if(this._colorType===Ke.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ke.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};Qe.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};Qe.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ke.GAMMA_DIVISION),this._handleChunkEnd()};Qe.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};Qe.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Ke.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(t);let n=e-t.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Qe.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};Qe.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Za=Oe((Ob)=>{var Mh=ja(),Sb=[function(){},function(e,t,n,r){if(r===t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],Ib=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function Nb(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let s=e[r];r++;let o,a,u,c,l,h,f,d;switch(t){default:throw Error("unrecognised depth");case 16:f=e[r],r++,n.push((s<<8)+f);break;case 4:f=s&15,d=s>>4,n.push(d,f);break;case 2:l=s&3,h=s>>2&3,f=s>>4&3,d=s>>6&3,n.push(d,f,h,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,h=s>>5&1,f=s>>6&1,d=s>>7&1,n.push(d,f,h,l,c,u,a,o);break}}return{get:function(s){while(n.length<s)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function Rb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++)for(let l=0;l<o;l++){let h=n(l,c,u);Sb[r](t,i,h,s),s+=r}return s}function Fb(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++){for(let l=0;l<o;l++){let h=i.get(r),f=n(l,c,u);Ib[r](t,h,f,s)}i.resetAfterLine()}}Ob.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=Nb(e,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,l=0,h,f;if(o)h=Mh.getImagePasses(n,r),f=Mh.getInterlaceIterator(n,r);else{let d=0;f=function(){let g=d;return d+=4,g},h=[{width:n,height:r}]}for(let d=0;d<h.length;d++)if(i===8)l=Rb(h[d],u,f,s,e,l);else Fb(h[d],u,f,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var za=Oe((jM,Sh)=>{function Tb(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=i[e[s]];if(!u)throw Error("index "+e[s]+" not in palette");for(let c=0;c<4;c++)t[s+c]=u[c];s+=4}}function Ab(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=!1;if(i.length===1){if(i[0]===e[s])u=!0}else if(i[0]===e[s]&&i[1]===e[s+1]&&i[2]===e[s+2])u=!0;if(u)for(let c=0;c<4;c++)t[s+c]=0;s+=4}}function Hb(e,t,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<r;u++)for(let c=0;c<n;c++){for(let l=0;l<4;l++)t[a+l]=Math.floor(e[a+l]*s/o+0.5);a+=4}}Sh.exports=function(e,t,n=!1){let{depth:r,width:i,height:s,colorType:o,transColor:a,palette:u}=t,c=e;if(o===3)Tb(e,c,i,s,u);else{if(a)Ab(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);Hb(e,c,i,s,r)}}return c}});var Rh=Oe((WM,Nh)=>{var Lb=ze("util"),Va=ze("zlib"),Ih=Ca(),Gb=kh(),Ub=Ya(),_b=Za(),Cb=za(),Gt=Nh.exports=function(e){Ih.call(this),this._parser=new Ub(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()};Lb.inherits(Gt,Ih);Gt.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};Gt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Va.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,Va.Z_MIN_CHUNK);this._inflate=Va.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};Gt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new Gb(this._bitmapInfo)};Gt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Gt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Gt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Gt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Gt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Gt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=_b.dataToBitMap(e,this._bitmapInfo);t=Cb(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Oh=Oe((JM,Fh)=>{var bt=Mr();Fh.exports=function(e,t,n,r){let i=[bt.COLORTYPE_COLOR_ALPHA,bt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let m=new ArrayBuffer(2);return new DataView(m).setInt16(0,256,!0),new Int16Array(m)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=bt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=bt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,h=0,f=r.bgColor||{};if(f.red===void 0)f.red=o;if(f.green===void 0)f.green=o;if(f.blue===void 0)f.blue=o;function d(){let g,m,$,p=o;switch(r.inputColorType){case bt.COLORTYPE_COLOR_ALPHA:p=s[l+3],g=s[l],m=s[l+1],$=s[l+2];break;case bt.COLORTYPE_COLOR:g=s[l],m=s[l+1],$=s[l+2];break;case bt.COLORTYPE_ALPHA:p=s[l+1],g=s[l],m=g,$=g;break;case bt.COLORTYPE_GRAYSCALE:g=s[l],m=g,$=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)p/=o,g=Math.min(Math.max(Math.round((1-p)*f.red+p*g),0),o),m=Math.min(Math.max(Math.round((1-p)*f.green+p*m),0),o),$=Math.min(Math.max(Math.round((1-p)*f.blue+p*$),0),o)}return{red:g,green:m,blue:$,alpha:p}}for(let g=0;g<n;g++)for(let m=0;m<t;m++){let $=d(s,l);switch(r.colorType){case bt.COLORTYPE_COLOR_ALPHA:case bt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[h]=$.red,c[h+1]=$.green,c[h+2]=$.blue,i)c[h+3]=$.alpha}else if(c.writeUInt16BE($.red,h),c.writeUInt16BE($.green,h+2),c.writeUInt16BE($.blue,h+4),i)c.writeUInt16BE($.alpha,h+6);break;case bt.COLORTYPE_ALPHA:case bt.COLORTYPE_GRAYSCALE:{let p=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(c[h]=p,i)c[h+1]=$.alpha}else if(c.writeUInt16BE(p,h),i)c.writeUInt16BE($.alpha,h+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,h+=u}return c}});var Ah=Oe((KM,Th)=>{var Ph=Wa();function jb(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Wb(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Jb(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=e[t+o]-a;r[i+o]=u}}function Kb(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=e[t+s]-o;i+=Math.abs(a)}return i}function qb(e,t,n,r,i){for(let s=0;s<n;s++){let o=t>0?e[t+s-n]:0,a=e[t+s]-o;r[i+s]=a}}function Qb(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=t>0?e[s-n]:0,a=e[s]-o;r+=Math.abs(a)}return r}function Yb(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=e[t+o]-(a+u>>1);r[i+o]=c}}function Zb(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=e[t+s]-(o+a>>1);i+=Math.abs(u)}return i}function zb(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=t>0&&o>=s?e[t+o-(n+s)]:0,l=e[t+o]-Ph(a,u,c);r[i+o]=l}}function Vb(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=t>0&&s>=r?e[t+s-(n+r)]:0,c=e[t+s]-Ph(o,a,u);i+=Math.abs(c)}return i}var Xb={0:jb,1:Jb,2:qb,3:Yb,4:zb},Bb={0:Wb,1:Kb,2:Qb,3:Zb,4:Vb};Th.exports=function(e,t,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType==="number")s=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let o=t*i,a=0,u=0,c=Buffer.alloc((o+1)*n),l=s[0];for(let h=0;h<n;h++){if(s.length>1){let f=1/0;for(let d=0;d<s.length;d++){let g=Bb[s[d]](e,u,o,i);if(g<f)l=s[d],f=g}}c[a]=l,a++,Xb[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var Xa=Oe((qM,Hh)=>{var xe=Mr(),xb=Qa(),Db=Oh(),e0=Ah(),t0=ze("zlib"),bn=Hh.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||t0.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:xe.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:xe.COLORTYPE_COLOR_ALPHA,[xe.COLORTYPE_GRAYSCALE,xe.COLORTYPE_COLOR,xe.COLORTYPE_COLOR_ALPHA,xe.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([xe.COLORTYPE_GRAYSCALE,xe.COLORTYPE_COLOR,xe.COLORTYPE_COLOR_ALPHA,xe.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")};bn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};bn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};bn.prototype.filterData=function(e,t,n){let r=Db(e,t,n,this._options),i=xe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return e0(r,t,n,this._options,i)};bn.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(xb.crc32(r.slice(4,r.length-4)),r.length-4),r};bn.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*xe.GAMMA_DIVISION),0),this._packChunk(xe.TYPE_gAMA,t)};bn.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(xe.TYPE_IHDR,n)};bn.prototype.packIDAT=function(e){return this._packChunk(xe.TYPE_IDAT,e)};bn.prototype.packIEND=function(){return this._packChunk(xe.TYPE_IEND,null)}});var _h=Oe((QM,Uh)=>{var n0=ze("util"),Lh=ze("stream"),r0=Mr(),i0=Xa(),Gh=Uh.exports=function(e){Lh.call(this);let t=e||{};this._packer=new i0(t),this._deflate=this._packer.createDeflate(),this.readable=!0};n0.inherits(Gh,Lh);Gh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(r0.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var qh=Oe((wi,Kh)=>{var Ch=ze("assert").ok,Sr=ze("zlib"),s0=ze("util"),jh=ze("buffer").kMaxLength;function Wn(e){if(!(this instanceof Wn))return new Wn(e);if(e&&e.chunkSize<Sr.Z_MIN_CHUNK)e.chunkSize=Sr.Z_MIN_CHUNK;if(Sr.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 o0(e){return new Wn(e)}function Wh(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Wn.prototype._processChunk=function(e,t,n){if(typeof n==="function")return Sr.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function h(g,m){if(r._hadError)return;let $=s-m;if(Ch($>=0,"have should not go down"),$>0){let p=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,p.length>o)p=p.slice(0,o);if(u.push(p),c+=p.length,o-=p.length,o===0)return!1}if(m===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(m===0)return a+=i-g,i=g,!0;return!1}Ch(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,s),f=f||this._writeState;while(!this._hadError&&h(f[0],f[1]));if(this._hadError)throw l;if(c>=jh)throw Wh(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+jh.toString(16)+" bytes");let d=Buffer.concat(u,c);return Wh(this),d};s0.inherits(Wn,Sr.Inflate);function a0(e,t){if(typeof t==="string")t=Buffer.from(t);if(!(t instanceof Buffer))throw TypeError("Not a string or buffer");let n=e._finishFlushFlag;if(n==null)n=Sr.Z_FINISH;return e._processChunk(t,n)}function Jh(e,t){return a0(new Wn(t),e)}Kh.exports=wi=Jh;wi.Inflate=Wn;wi.createInflate=o0;wi.inflateSync=Jh});var Ba=Oe((YM,Yh)=>{var Qh=Yh.exports=function(e){this._buffer=e,this._reads=[]};Qh.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};Qh.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 t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.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 Zh=Oe((l0)=>{var u0=Ba(),c0=Ja();l0.process=function(e,t){let n=[],r=new u0(e);return new c0(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Bh=Oe((zM,Xh)=>{var zh=!0,Vh=ze("zlib"),f0=qh();if(!Vh.deflateSync)zh=!1;var d0=Ba(),g0=Zh(),m0=Ya(),p0=Za(),w0=za();Xh.exports=function(e,t){if(!zh)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(S){n=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function u(){i.alpha=!0}let c;function l(S){c=S}let h=[];function f(S){h.push(S)}let d=new d0(e);if(new m0(t,{read:d.read.bind(d),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:f,simpleTransparency:u}).start(),d.process(),n)throw n;let m=Buffer.concat(h);h.length=0;let $;if(i.interlace)$=Vh.inflateSync(m);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=f0(m,{chunkSize:w,maxLength:w})}if(m=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let p=g0.process($,i);m=null;let E=p0.dataToBitMap(p,i);p=null;let y=w0(E,i,t.skipRescale);return i.data=y,i.gamma=c||0,i}});var tf=Oe((VM,ef)=>{var xh=!0,Dh=ze("zlib");if(!Dh.deflateSync)xh=!1;var b0=Mr(),$0=Xa();ef.exports=function(e,t){if(!xh)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new $0(t||{}),i=[];if(i.push(Buffer.from(b0.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let s=r.filterData(e.data,e.width,e.height),o=Dh.deflateSync(s,r.getDeflateOptions());if(s=null,!o||!o.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(o)),i.push(r.packIEND()),Buffer.concat(i)}});var nf=Oe((E0)=>{var k0=Bh(),y0=tf();E0.read=function(e,t){return k0(e,t||{})};E0.write=function(e,t){return y0(e,t)}});var sf=Oe((F0)=>{var S0=ze("util"),rf=ze("stream"),I0=Rh(),N0=_h(),R0=nf(),nt=F0.PNG=function(e){if(rf.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 I0(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(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new N0(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"))};S0.inherits(nt,rf);nt.sync=R0;nt.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};nt.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};nt.prototype.write=function(e){return this._parser.write(e),!0};nt.prototype.end=function(e){this._parser.end(e)};nt.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};nt.prototype._gamma=function(e){this.gamma=e};nt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};nt.bitblt=function(e,t,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+s>e.height)throw Error("bitblt reading outside image");if(o>t.width||a>t.height||o+i>t.width||a+s>t.height)throw Error("bitblt writing outside image");for(let u=0;u<s;u++)e.data.copy(t.data,(a+u)*t.width+o<<2,(r+u)*e.width+n<<2,(r+u)*e.width+n+i<<2)};nt.prototype.bitblt=function(e,t,n,r,i,s,o){return nt.bitblt(this,e,t,n,r,i,s,o),this};nt.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let i=0;i<3;i++){let s=e.data[r+i]/255;s=Math.pow(s,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(s*255)}}e.gamma=0}};nt.prototype.adjustGamma=function(){nt.adjustGamma(this)}});import{spawnSync as Gv}from"node:child_process";import{isMainThread as Uv}from"node:worker_threads";import{parseArgs as Ov}from"node:util";var Ve={name:"@kecan0406/ttheme",version:"1.1.2",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","fast-string-width":"^3.0.2","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{existsSync as mE,readFileSync as Mm}from"node:fs";import{styleText as As}from"node:util";import{stdout as Pl,stdin as $w}from"node:process";import kw from"node:readline";var gl=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),ml=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},pl=(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 iw=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,sw=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,wl=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ow=/\t{1,1000}/y,bl=/[\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,aw=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,uw=/\p{M}+/gu,cw={limit:1/0,ellipsis:""},$l=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?$l(i,cw,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,h=n.regularWidth??1,f=n.wideWidth??2,d=[[aw,h],[iw,0],[sw,a],[ow,u],[bl,c],[wl,f]],g=0,m=0,$=e.length,p=0,E=!1,y=$,S=Math.max(0,r-s),w=0,N=0,v=0,O=0;e:while(!0){if(N>w||m>=$&&m>g){let F=e.slice(w,N)||e.slice(g,m);p=0;for(let L of F.replaceAll(uw,"")){let U=L.codePointAt(0)||0;if(ml(U))O=2;else if(pl(U))O=f;else O=h;if(v+O>S)y=Math.min(y,Math.max(w,g)+p);if(v+O>r){E=!0;break e}p+=L.length,v+=O}w=N=0}if(m>=$)break e;for(let F=0,L=d.length;F<L;F++){let[U,ce]=d[F];if(U.lastIndex=m,U.test(e)){if(p=U===wl?gl(e.slice(m,U.lastIndex)):U===bl?1:U.lastIndex-m,O=p*ce,v+O>S)y=Math.min(y,m+Math.floor((S-v)/ce));if(v+O>r){E=!0;break e}v+=O,w=g,N=m,m=g=U.lastIndex;continue e}}m+=1}return{width:E?S:v,index:E?y:$,truncated:E,ellipsed:E&&r>=s}},kl=$l;var lw={limit:1/0,ellipsis:"",ellipsisWidth:0},hw=(e,t={})=>{return kl(e,lw,t).width},Ce=hw;var Fs="\x1B",Sl="›",fw=39,ga="\x07",Il="[",dw="]",Nl="m",ma=`${dw}8;;`,yl=new RegExp(`(?:\\${Il}(?<code>\\d+)m|\\${ma}(?<uri>.*)${ga})`,"y"),El=(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},vl=(e)=>`${Fs}${Il}${e}${Nl}`,Ml=(e)=>`${Fs}${ma}${e}${ga}`,da=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:Ce(o),u=r.next(),c=r.next(),l=0;while(!u.done){let h=u.value,f=Ce(h);if(a+f<=n)e[e.length-1]+=h;else e.push(h),a=0;if(h===Fs||h===Sl)i=!0,s=t.startsWith(ma,l+1);if(i){if(s){if(h===ga)i=!1,s=!1}else if(h===Nl)i=!1}else if(a+=f,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=h.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},gw=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Ce(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},mw=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let g=a.at(-1)??"",m=g.trimStart();if(g.length!==m.length)a[a.length-1]=m,u=Ce(m)}if(h!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let d=Ce(f);if(n.hard&&d>t){let g=t-u,m=1+Math.floor((d-g-1)/t);if(Math.floor((d-1)/t)<m)a.push("");da(a,f,t),u=Ce(a.at(-1)??"");continue}if(u+d>t&&u&&d){if(n.wordWrap===!1&&u<t){da(a,f,t),u=Ce(a.at(-1)??"");continue}a.push(""),u=0}if(u+d>t&&n.wordWrap===!1){da(a,f,t),u=Ce(a.at(-1)??"");continue}a[a.length-1]+=f,u+=d}if(n.trim!==!1)a=a.map((h)=>gw(h));let c=a.join(`
3
+ `),l=!1;for(let h=0;h<c.length;h++){let f=c[h];if(r+=f,!l){if(l=f>="\uD800"&&f<="\uDBFF",l)continue}else l=!1;if(f===Fs||f===Sl){yl.lastIndex=h+1;let g=yl.exec(c)?.groups;if(g?.code!==void 0){let m=Number.parseFloat(g.code);i=m===fw?void 0:m}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[h+1]===`
4
+ `){if(s)r+=Ml("");let d=i?El(i):void 0;if(i&&d)r+=vl(d)}else if(f===`
5
+ `){if(i&&El(i))r+=vl(i);if(s)r+=Ml(s)}}return r},pw=/\r?\n/;function ln(e,t,n){return String(e).normalize().split(pw).map((r)=>mw(r,t,n)).join(`
6
+ `)}var at=Rs(wa(),1);function mr(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?mr(s,t<0?-1:1,n):s}function Os(e,t,n,r){let i=r.split(`
7
+ `),s=0,o=e;for(let u of i){if(o<=u.length)break;o-=u.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let u=0;u<s;u++)a+=i[u].length+1;return a+o}var yw=["up","down","left","right","space","enter","cancel"],Ew=["January","February","March","April","May","June","July","August","September","October","November","December"],Xe={actions:new Set(yw),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:[...Ew],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,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 Tl(e,t){if(typeof e=="string")return Xe.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Tl(n,t))return!0;return!1}function vw(e,t){if(e===t)return;let n=e.split(`
8
8
  `),r=t.split(`
9
- `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var Vv=globalThis.process.platform.startsWith("win"),ma=Symbol("clack:cancel");function Be(e){return e===ma}function Ss(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Rs=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,wa=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function fi(e,t,n,r=n,i=n,s){let o=Rs(e??Nl);return fn(t,o-n.length,{hard:!0,trim:!1}).split(`
9
+ `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var Dv=globalThis.process.platform.startsWith("win"),$a=Symbol("clack:cancel");function Be(e){return e===$a}function Ps(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Hs=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,ya=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function fi(e,t,n,r=n,i=n,s){let o=Hs(e??Pl);return ln(t,o-n.length,{hard:!0,trim:!1}).split(`
10
10
  `).map((a,u,c)=>{let l=s?s(a,u):a;return u===0?`${r}${l}`:u===c.length-1?`${i}${l}`:`${n}${l}`}).join(`
11
- `)}function Ol(e,t){if("~standard"in e){let n=e["~standard"].validate(t);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 e(t)}class pt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=gw,output:r=Nl,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.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(ma);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=mw.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),Ss(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(at.cursor.show),this.output.off("resize",this.render),Ss(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(at.cursor.show),this.output.off("resize",this.render),Ss(this.input,!1),e(ma)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&Xe.aliases.has(t.name)&&this.emit("cursor",Xe.aliases.get(t.name)),Xe.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Ol(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")}Rl([e,t?.name,t?.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(`
12
- `),Ss(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=fn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(at.cursor.move(-999,e*-1))}render(){let e=fn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(at.cursor.hide);else{let t=bw(this._prevFrame,e),n=wa(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(at.cursor.move(0,s-i)),this.output.write(at.erase.lines(1));let o=e.split(`
11
+ `)}function Al(e,t){if("~standard"in e){let n=e["~standard"].validate(t);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 e(t)}class pt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=$w,output:r=Pl,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.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($a);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=kw.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),Ps(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(at.cursor.show),this.output.off("resize",this.render),Ps(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(at.cursor.show),this.output.off("resize",this.render),Ps(this.input,!1),e($a)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&Xe.aliases.has(t.name)&&this.emit("cursor",Xe.aliases.get(t.name)),Xe.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Al(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")}Tl([e,t?.name,t?.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(`
12
+ `),Ps(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=ln(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(at.cursor.move(-999,e*-1))}render(){let e=ln(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(at.cursor.hide);else{let t=vw(this._prevFrame,e),n=ya(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(at.cursor.move(0,s-i)),this.output.write(at.erase.lines(1));let o=e.split(`
14
14
  `);this.output.write(o[s]),this._prevFrame=e,this.output.write(at.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(at.cursor.move(0,a))}this.output.write(at.erase.down());let o=e.split(`
15
15
  `).slice(s);this.output.write(o.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(at.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function $w(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function kw(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function yw(e,t){if(t)return e?t:t[0]}var Ew=class extends pt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Ns(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${Ns("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??kw;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#r(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,u=this.options,c=a!==void 0&&a!==""&&u.some((l)=>!l.disabled&&(this.#e?this.#e(a,l):!0));if(n.name==="tab"&&o&&c){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=mr(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=yw(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(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#i(t){if(t!==this.#n){this.#n=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=$w(this.focusedValue,this.filteredOptions);this.#t=mr(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class ba extends pt{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",(t)=>{this.output.write(at.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var vw={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Sl(e){return[...e].map((t)=>vw[t])}function Mw(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)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 ga(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Is(e){return{year:ga(e.year),month:ga(e.month),day:ga(e.day)}}function pa(e,t){return new Date(e||2001,t||1,0).getDate()}function Fl(e){let{year:t,month:n,day:r}=Is(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function Il(e){let t=Fl(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Sw(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:pa(t.year,t.month)}}class Pl extends pt{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#h(this.#e)}#h(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#h(this.#e)),this._setValue(Il(this.#e)??void 0)}constructor(e){let t=e.format?{segments:Sl(e.format),separator:e.separator??"/"}:Mw(e.locale),n=e.separator??t.separator,r=e.format?Sl(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#n=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#u(),this.on("cursor",(a)=>this.#g(a)),this.on("key",(a,u)=>this.#m(a,u)),this.on("finalize",()=>this.#p(e))}#c(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#l(e){this.inlineError="",this.#o=null;let t=this.#c();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#f(e){let t=this.#c();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Sw(n.type,Is(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#i=!0,this.#o=null,this.#u()}#g(e){if(e)switch(e){case"right":return this.#l(1);case"left":return this.#l(-1);case"up":return this.#f(1);case"down":return this.#f(-1)}}#m(e,t){if(t?.name==="backspace"||t?.sequence===""||t?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let n=this.#c();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#l(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#u();return}if(t?.name==="tab"){this.inlineError="";let n=this.#c();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#c();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!i){let f=this.#o+e,d={...this.#e,[r.type]:f},g=this.#d(d,r);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=f,this.#o=null,this.#i=!1,this.#u(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.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.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#r.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let u=s.slice(0,a)+e+s.slice(a+1),c=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let f=Number.parseInt(e,10);u=`0${e}`,c=f<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!u.includes("_")){let f={...this.#e,[r.type]:u},d=this.#d(f,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=u;let l=u.includes("_")?void 0:Fl(this.#e);if(l){let{year:f,month:d}=l,g=pa(f,d);this.#e={year:String(Math.max(0,Math.min(9999,f))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#u();let h=u.indexOf("_");c?(this.#i=!0,this.#o=e):h>=0?this.#r.positionInSegment=h:o>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(a+1,r.len-1)}}#d(e,t){let{month:n,day:r}=Is(e);if(t.type==="month"&&(n<0||n>12))return Xe.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return Xe.date.messages.invalidDay(31,"any month")}#p(e){let{year:t,month:n,day:r}=Is(this.#e);if(t&&n&&r){let i=pa(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Il(this.#e)??e.defaultValue??void 0}}var Iw=class extends pt{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.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(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?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.#t&&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.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Nw=new Set(["up","down","left","right"]);class Tl extends pt{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
16
+ `)),this._prevFrame=e;return}}this.output.write(at.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function Mw(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function Sw(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Iw(e,t){if(t)return e?t:t[0]}var Nw=class extends pt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return As(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${As("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??Sw;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#r(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,u=this.options,c=a!==void 0&&a!==""&&u.some((l)=>!l.disabled&&(this.#e?this.#e(a,l):!0));if(n.name==="tab"&&o&&c){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=mr(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=Iw(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(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#i(t){if(t!==this.#n){this.#n=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=Mw(this.focusedValue,this.filteredOptions);this.#t=mr(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Ea extends pt{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",(t)=>{this.output.write(at.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Rw={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Fl(e){return[...e].map((t)=>Rw[t])}function Fw(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)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 ba(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Ts(e){return{year:ba(e.year),month:ba(e.month),day:ba(e.day)}}function ka(e,t){return new Date(e||2001,t||1,0).getDate()}function Hl(e){let{year:t,month:n,day:r}=Ts(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function Ol(e){let t=Hl(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Ow(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:ka(t.year,t.month)}}class Ll extends pt{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#h(this.#e)}#h(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#h(this.#e)),this._setValue(Ol(this.#e)??void 0)}constructor(e){let t=e.format?{segments:Fl(e.format),separator:e.separator??"/"}:Fw(e.locale),n=e.separator??t.separator,r=e.format?Fl(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#n=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#u(),this.on("cursor",(a)=>this.#g(a)),this.on("key",(a,u)=>this.#m(a,u)),this.on("finalize",()=>this.#p(e))}#c(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#l(e){this.inlineError="",this.#o=null;let t=this.#c();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#f(e){let t=this.#c();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Ow(n.type,Ts(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#i=!0,this.#o=null,this.#u()}#g(e){if(e)switch(e){case"right":return this.#l(1);case"left":return this.#l(-1);case"up":return this.#f(1);case"down":return this.#f(-1)}}#m(e,t){if(t?.name==="backspace"||t?.sequence===""||t?.sequence==="\b"||e===""||e==="\b"){this.inlineError="";let n=this.#c();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#l(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#u();return}if(t?.name==="tab"){this.inlineError="";let n=this.#c();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#c();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#i&&this.#o!==null&&!i){let f=this.#o+e,d={...this.#e,[r.type]:f},g=this.#d(d,r);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=f,this.#o=null,this.#i=!1,this.#u(),n.index<this.#t.length-1&&(this.#r.segmentIndex=n.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.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#r.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let u=s.slice(0,a)+e+s.slice(a+1),c=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let f=Number.parseInt(e,10);u=`0${e}`,c=f<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!u.includes("_")){let f={...this.#e,[r.type]:u},d=this.#d(f,r);if(d){this.inlineError=d;return}}this.inlineError="",this.#e[r.type]=u;let l=u.includes("_")?void 0:Hl(this.#e);if(l){let{year:f,month:d}=l,g=ka(f,d);this.#e={year:String(Math.max(0,Math.min(9999,f))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,d))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#u();let h=u.indexOf("_");c?(this.#i=!0,this.#o=e):h>=0?this.#r.positionInSegment=h:o>=0&&n.index<this.#t.length-1?(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0):this.#r.positionInSegment=Math.min(a+1,r.len-1)}}#d(e,t){let{month:n,day:r}=Ts(e);if(t.type==="month"&&(n<0||n>12))return Xe.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return Xe.date.messages.invalidDay(31,"any month")}#p(e){let{year:t,month:n,day:r}=Ts(this.#e);if(t&&n&&r){let i=ka(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Ol(this.#e)??e.defaultValue??void 0}}var Pw=class extends pt{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.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(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?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.#t&&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.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Tw=new Set(["up","down","left","right"]);class Gl extends pt{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
17
17
  `?`${t}█
18
- ${r}`:`${t}${Ns("inverse",n)}${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))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Ms(this._cursor,0,-1,t);return;case"down":this._cursor=Ms(this._cursor,0,1,t);return;case"left":this._cursor=Ms(this._cursor,-1,0,t);return;case"right":this._cursor=Ms(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
18
+ ${r}`:`${t}${As("inverse",n)}${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))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Os(this._cursor,0,-1,t);return;case"down":this._cursor=Os(this._cursor,0,1,t);return;case"left":this._cursor=Os(this._cursor,-1,0,t);return;case"right":this._cursor=Os(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
19
19
  `),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
20
20
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
21
- `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#n=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&Nw.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!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.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class $a extends pt{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,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?mr(t,1,this.options):t,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=mr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class ka extends pt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Ns("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as v,stripVTControlCharacters as iM}from"node:util";import wt from"node:process";var jl=Es(da(),1);function Rw(){if(wt.platform!=="win32")return wt.env.TERM!=="linux";return Boolean(wt.env.CI)||Boolean(wt.env.WT_SESSION)||Boolean(wt.env.TERMINUS_SUBLIME)||wt.env.ConEmuTask==="{cmd::Cmder}"||wt.env.TERM_PROGRAM==="Terminus-Sublime"||wt.env.TERM_PROGRAM==="vscode"||wt.env.TERM==="xterm-256color"||wt.env.TERM==="alacritty"||wt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ow=Rw();var ve=(e,t)=>Ow?e:t,Fw=ve("◆","*"),Pw=ve("■","x"),Tw=ve("▲","x"),ya=ve("◇","o"),Aw=ve("┌","T"),me=ve("│","|"),gn=ve("└","—"),uM=ve("┐","T"),cM=ve("┘","—"),Al=ve("●",">"),Hl=ve("○"," "),Hw=ve("◻","[•]"),Ll=ve("◼","[+]"),Gl=ve("◻","[ ]"),lM=ve("▪","•"),Ul=ve("─","-"),Lw=ve("╮","+"),Gw=ve("├","+"),Uw=ve("╯","+"),_w=ve("╰","+"),hM=ve("╭","+"),Cw=ve("●","•"),jw=ve("◆","*"),Ww=ve("▲","!"),Jw=ve("■","x"),Ea=(e)=>{switch(e){case"initial":case"active":return v("cyan",Fw);case"cancel":return v("red",Pw);case"error":return v("yellow",Tw);case"submit":return v("green",ya)}},Kw=(e)=>{switch(e){case"initial":case"active":return v("cyan",me);case"cancel":return v("red",me);case"error":return v("yellow",me);case"submit":return v("green",me)}};function qw(e,t){let n=[`${t?`${v("cyan",me)} `:""}${e.join(" • ")}`];return t&&n.push(v("cyan",gn)),n}var _l=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let u=r-1;u>=n;u--){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}else for(let u=n;u<r;u++){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},Cl=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Rs(r)-s,u=wa(r),c=v("dim","..."),l=Math.max(u-o,0),h=Math.max(Math.min(i,l),5),f=0;e>=h-3&&(f=Math.max(Math.min(e-h+3,t.length-h),0));let d=h<t.length&&f>0,g=h<t.length&&f+h<t.length,m=Math.min(f+h,t.length),$=[],w=0;d&&w++,g&&w++;let M=f+(d?1:0),y=m-(g?1:0);for(let p=M;p<y;p++){let N=t[p],E=N?n(N,p===e):"",F=fn(E,a,{hard:!0,trim:!1}).split(`
22
- `);$.push(F),w+=F.length}if(w>l){let p=0,N=0,E=w,F=e-M,O=l,L=()=>_l($,E,0,F,O),U=()=>_l($,E,F+1,$.length,O,!0);d?({lineCount:E,removals:p}=L(),E>O&&(g||(O-=1),{lineCount:E,removals:N}=U())):(g||(O-=1),{lineCount:E,removals:N}=U(),E>O&&(O-=1,{lineCount:E,removals:p}=L())),p>0&&(d=!0,$.splice(0,p)),N>0&&(g=!0,$.splice($.length-N,N))}let S=[];d&&S.push(c);for(let p of $)for(let N of p)S.push(N);return g&&S.push(c),S};var Ht=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new ba({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Xe.withGuide,i=`${Ea(this.state)} `,s=r?`${v("gray",me)} `:"",o=fi(e.output,e.message,s,i),a=`${r?`${v("gray",me)}
21
+ `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#n=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&Tw.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!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.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class va extends pt{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,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?mr(t,1,this.options):t,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=mr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Ma extends pt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${As("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as M,stripVTControlCharacters as uM}from"node:util";import wt from"node:process";var ql=Rs(wa(),1);function Aw(){if(wt.platform!=="win32")return wt.env.TERM!=="linux";return Boolean(wt.env.CI)||Boolean(wt.env.WT_SESSION)||Boolean(wt.env.TERMINUS_SUBLIME)||wt.env.ConEmuTask==="{cmd::Cmder}"||wt.env.TERM_PROGRAM==="Terminus-Sublime"||wt.env.TERM_PROGRAM==="vscode"||wt.env.TERM==="xterm-256color"||wt.env.TERM==="alacritty"||wt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Hw=Aw();var Me=(e,t)=>Hw?e:t,Lw=Me("◆","*"),Gw=Me("■","x"),Uw=Me("▲","x"),Sa=Me("◇","o"),_w=Me("┌","T"),me=Me("│","|"),fn=Me("└","—"),fM=Me("┐","T"),dM=Me("┘","—"),Ul=Me("●",">"),_l=Me("○"," "),Cw=Me("◻","[•]"),Cl=Me("◼","[+]"),jl=Me("◻","[ ]"),gM=Me("▪","•"),Wl=Me("─","-"),jw=Me("╮","+"),Ww=Me("├","+"),Jw=Me("╯","+"),Kw=Me("╰","+"),mM=Me("╭","+"),qw=Me("●","•"),Qw=Me("◆","*"),Yw=Me("▲","!"),Zw=Me("■","x"),Ia=(e)=>{switch(e){case"initial":case"active":return M("cyan",Lw);case"cancel":return M("red",Gw);case"error":return M("yellow",Uw);case"submit":return M("green",Sa)}},zw=(e)=>{switch(e){case"initial":case"active":return M("cyan",me);case"cancel":return M("red",me);case"error":return M("yellow",me);case"submit":return M("green",me)}};function Vw(e,t){let n=[`${t?`${M("cyan",me)} `:""}${e.join(" • ")}`];return t&&n.push(M("cyan",fn)),n}var Jl=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let u=r-1;u>=n;u--){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}else for(let u=n;u<r;u++){let c=e[u];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},Kl=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Hs(r)-s,u=ya(r),c=M("dim","..."),l=Math.max(u-o,0),h=Math.max(Math.min(i,l),5),f=0;e>=h-3&&(f=Math.max(Math.min(e-h+3,t.length-h),0));let d=h<t.length&&f>0,g=h<t.length&&f+h<t.length,m=Math.min(f+h,t.length),$=[],p=0;d&&p++,g&&p++;let E=f+(d?1:0),y=m-(g?1:0);for(let w=E;w<y;w++){let N=t[w],v=N?n(N,w===e):"",O=ln(v,a,{hard:!0,trim:!1}).split(`
22
+ `);$.push(O),p+=O.length}if(p>l){let w=0,N=0,v=p,O=e-E,F=l,L=()=>Jl($,v,0,O,F),U=()=>Jl($,v,O+1,$.length,F,!0);d?({lineCount:v,removals:w}=L(),v>F&&(g||(F-=1),{lineCount:v,removals:N}=U())):(g||(F-=1),{lineCount:v,removals:N}=U(),v>F&&(F-=1,{lineCount:v,removals:w}=L())),w>0&&(d=!0,$.splice(0,w)),N>0&&(g=!0,$.splice($.length-N,N))}let S=[];d&&S.push(c);for(let w of $)for(let N of w)S.push(N);return g&&S.push(c),S};var Ht=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Ea({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??Xe.withGuide,i=`${Ia(this.state)} `,s=r?`${M("gray",me)} `:"",o=fi(e.output,e.message,s,i),a=`${r?`${M("gray",me)}
23
23
  `:""}${o}
24
- `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${v("gray",me)} `:"";return`${a}${c}${v("dim",u)}`}case"cancel":{let c=r?`${v("gray",me)} `:"";return`${a}${c}${v(["strikethrough","dim"],u)}${r?`
25
- ${v("gray",me)}`:""}`}default:{let c=r?`${v("cyan",me)} `:"",l=r?v("cyan",gn):"";return`${a}${c}${this.value?`${v("green",Al)} ${t}`:`${v("dim",Hl)} ${v("dim",t)}`}${e.vertical?r?`
26
- ${v("cyan",me)} `:`
27
- `:` ${v("dim","/")} `}${this.value?`${v("dim",Hl)} ${v("dim",n)}`:`${v("green",Al)} ${n}`}
24
+ `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${M("gray",me)} `:"";return`${a}${c}${M("dim",u)}`}case"cancel":{let c=r?`${M("gray",me)} `:"";return`${a}${c}${M(["strikethrough","dim"],u)}${r?`
25
+ ${M("gray",me)}`:""}`}default:{let c=r?`${M("cyan",me)} `:"",l=r?M("cyan",fn):"";return`${a}${c}${this.value?`${M("green",Ul)} ${t}`:`${M("dim",_l)} ${M("dim",t)}`}${e.vertical?r?`
26
+ ${M("cyan",me)} `:`
27
+ `:` ${M("dim","/")} `}${this.value?`${M("dim",_l)} ${M("dim",n)}`:`${M("green",Ul)} ${n}`}
28
28
  ${l}
29
- `}}}}).prompt()};var Qw=[`${v("dim","↑/↓")} to navigate`,`${v("dim","Space:")} select`,`${v("dim","Enter:")} confirm`],di=(e,t)=>e.split(`
29
+ `}}}}).prompt()};var Xw=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Space:")} select`,`${M("dim","Enter:")} confirm`],di=(e,t)=>e.split(`
30
30
  `).map((n)=>t(n)).join(`
31
- `),Wl=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${v("gray",Gl)} ${di(o,(a)=>v(["strikethrough","gray"],a))}${i.hint?` ${v("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${v("cyan",Hw)} ${o}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${v("green",Ll)} ${di(o,(a)=>v("dim",a))}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${di(o,(a)=>v(["strikethrough","dim"],a))}`:s==="active-selected"?`${v("green",Ll)} ${o}${i.hint?` ${v("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${di(o,(a)=>v("dim",a))}`:`${v("dim",Gl)} ${di(o,(a)=>v("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new $a({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
32
- ${v("reset",v("dim",`Press ${v(["gray","bgWhite","inverse"]," space ")} to select, ${v("gray",v("bgWhite",v("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??Xe.withGuide,s=fi(e.output,e.message,i?`${Kw(this.state)} `:"",`${Ea(this.state)} `),o=`${i?`${v("gray",me)}
31
+ `),Ql=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${M("gray",jl)} ${di(o,(a)=>M(["strikethrough","gray"],a))}${i.hint?` ${M("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${M("cyan",Cw)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${M("green",Cl)} ${di(o,(a)=>M("dim",a))}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${di(o,(a)=>M(["strikethrough","dim"],a))}`:s==="active-selected"?`${M("green",Cl)} ${o}${i.hint?` ${M("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${di(o,(a)=>M("dim",a))}`:`${M("dim",jl)} ${di(o,(a)=>M("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new va({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
32
+ ${M("reset",M("dim",`Press ${M(["gray","bgWhite","inverse"]," space ")} to select, ${M("gray",M("bgWhite",M("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??Xe.withGuide,s=fi(e.output,e.message,i?`${zw(this.state)} `:"",`${Ia(this.state)} `),o=`${i?`${M("gray",me)}
33
33
  `:""}${s}
34
- `,a=this.value??[],u=(c,l)=>{if(c.disabled)return t(c,"disabled");let h=a.includes(c.value);return l&&h?t(c,"active-selected"):h?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"submitted")).join(v("dim",", "))||v("dim","none"),l=fi(e.output,c,i?`${v("gray",me)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"cancelled")).join(v("dim",", "));if(c.trim()==="")return`${o}${v("gray",me)}`;let l=fi(e.output,c,i?`${v("gray",me)} `:"");return`${o}${l}${i?`
35
- ${v("gray",me)}`:""}`}case"error":{let c=i?`${v("yellow",me)} `:"",l=this.error.split(`
36
- `).map((d,g)=>g===0?`${i?`${v("yellow",gn)} `:""}${v("yellow",d)}`:` ${d}`).join(`
34
+ `,a=this.value??[],u=(c,l)=>{if(c.disabled)return t(c,"disabled");let h=a.includes(c.value);return l&&h?t(c,"active-selected"):h?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"submitted")).join(M("dim",", "))||M("dim","none"),l=fi(e.output,c,i?`${M("gray",me)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:h})=>a.includes(h)).map((h)=>t(h,"cancelled")).join(M("dim",", "));if(c.trim()==="")return`${o}${M("gray",me)}`;let l=fi(e.output,c,i?`${M("gray",me)} `:"");return`${o}${l}${i?`
35
+ ${M("gray",me)}`:""}`}case"error":{let c=i?`${M("yellow",me)} `:"",l=this.error.split(`
36
+ `).map((d,g)=>g===0?`${i?`${M("yellow",fn)} `:""}${M("yellow",d)}`:` ${d}`).join(`
37
37
  `),h=o.split(`
38
38
  `).length,f=l.split(`
39
- `).length+1;return`${o}${c}${Cl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:h+f,style:u}).join(`
39
+ `).length+1;return`${o}${c}${Kl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:h+f,style:u}).join(`
40
40
  ${c}`)}
41
41
  ${l}
42
- `}default:{let c=i?`${v("cyan",me)} `:"",l=o.split(`
43
- `).length,h=r?qw(Qw,i):i?[v("cyan",gn)]:[],f=h.join(`
44
- `),d=h.length+1;return`${o}${c}${Cl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+d,style:u}).join(`
42
+ `}default:{let c=i?`${M("cyan",me)} `:"",l=o.split(`
43
+ `).length,h=r?Vw(Xw,i):i?[M("cyan",fn)]:[],f=h.join(`
44
+ `),d=h.length+1;return`${o}${c}${Kl({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+d,style:u}).join(`
45
45
  ${c}`)}
46
46
  ${f}
47
- `}}}}).prompt()};var dn={message:(e=[],{symbol:t=v("gray",me),secondarySymbol:n=v("gray",me),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??Xe.withGuide,u=a?n:"",c=a?`${t} `:"",l=a?`${n} `:"";for(let f=0;f<i;f++)o.push(u);let h=Array.isArray(e)?e:e.split(`
47
+ `}}}}).prompt()};var hn={message:(e=[],{symbol:t=M("gray",me),secondarySymbol:n=M("gray",me),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??Xe.withGuide,u=a?n:"",c=a?`${t} `:"",l=a?`${n} `:"";for(let f=0;f<i;f++)o.push(u);let h=Array.isArray(e)?e:e.split(`
48
48
  `);if(h.length>0){let[f,...d]=h;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let g of d)g.length>0?o.push(`${l}${g}`):o.push(a?n:"")}r.write(`${o.join(`
49
49
  `)}
50
- `)},info:(e,t)=>{dn.message(e,{...t,symbol:v("blue",Cw)})},success:(e,t)=>{dn.message(e,{...t,symbol:v("green",jw)})},step:(e,t)=>{dn.message(e,{...t,symbol:v("green",ya)})},warn:(e,t)=>{dn.message(e,{...t,symbol:v("yellow",Ww)})},warning:(e,t)=>{dn.warn(e,t)},error:(e,t)=>{dn.message(e,{...t,symbol:v("red",Jw)})}},pr=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${v("gray",gn)} `:"";n.write(`${r}${v("red",e)}
50
+ `)},info:(e,t)=>{hn.message(e,{...t,symbol:M("blue",qw)})},success:(e,t)=>{hn.message(e,{...t,symbol:M("green",Qw)})},step:(e,t)=>{hn.message(e,{...t,symbol:M("green",Sa)})},warn:(e,t)=>{hn.message(e,{...t,symbol:M("yellow",Yw)})},warning:(e,t)=>{hn.warn(e,t)},error:(e,t)=>{hn.message(e,{...t,symbol:M("red",Zw)})}},pr=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",fn)} `:"";n.write(`${r}${M("red",e)}
51
51
 
52
- `)},Os=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${v("gray",Aw)} `:"";n.write(`${r}${e}
53
- `)},va=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${v("gray",me)}
54
- ${v("gray",gn)} `:"";n.write(`${r}${e}
52
+ `)},Ls=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",_w)} `:"";n.write(`${r}${e}
53
+ `)},Na=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??Xe.withGuide?`${M("gray",me)}
54
+ ${M("gray",fn)} `:"";n.write(`${r}${e}
55
55
 
56
- `)};var Yw=(e)=>e,Zw=(e,t,n)=>{let r={hard:!0,trim:!1},i=fn(e,t,r).split(`
57
- `),s=i.reduce((u,c)=>Math.max(Ce(c),u),0),o=i.map(n).reduce((u,c)=>Math.max(Ce(c),u),0),a=t-(o-s);return fn(e,a,r)},jn=(e="",t="",n)=>{let r=n?.output??wt.stdout,i=n?.withGuide??Xe.withGuide,s=n?.format??Yw,o=["",...Zw(e,Rs(r)-6,s).split(`
58
- `).map(s),""],a=Ce(t),u=Math.max(o.reduce((f,d)=>{let g=Ce(d);return g>f?g:f},0),a)+2,c=o.map((f)=>`${v("gray",me)} ${f}${" ".repeat(u-Ce(f))}${v("gray",me)}`).join(`
59
- `),l=i?`${v("gray",me)}
60
- `:"",h=i?Gw:_w;r.write(`${l}${v("green",ya)} ${v("reset",t)} ${v("gray",Ul.repeat(Math.max(u-a-1,1))+Lw)}
56
+ `)};var Bw=(e)=>e,xw=(e,t,n)=>{let r={hard:!0,trim:!1},i=ln(e,t,r).split(`
57
+ `),s=i.reduce((u,c)=>Math.max(Ce(c),u),0),o=i.map(n).reduce((u,c)=>Math.max(Ce(c),u),0),a=t-(o-s);return ln(e,a,r)},Cn=(e="",t="",n)=>{let r=n?.output??wt.stdout,i=n?.withGuide??Xe.withGuide,s=n?.format??Bw,o=["",...xw(e,Hs(r)-6,s).split(`
58
+ `).map(s),""],a=Ce(t),u=Math.max(o.reduce((f,d)=>{let g=Ce(d);return g>f?g:f},0),a)+2,c=o.map((f)=>`${M("gray",me)} ${f}${" ".repeat(u-Ce(f))}${M("gray",me)}`).join(`
59
+ `),l=i?`${M("gray",me)}
60
+ `:"",h=i?Ww:Kw;r.write(`${l}${M("green",Sa)} ${M("reset",t)} ${M("gray",Wl.repeat(Math.max(u-a-1,1))+jw)}
61
61
  ${c}
62
- ${v("gray",h+Ul.repeat(u+2)+Uw)}
63
- `)};var fM={light:ve("─","-"),heavy:ve("━","="),block:ve("█","#")};var dM=[`${v("dim","↑/↓")} to navigate`,`${v("dim","Enter:")} confirm`];var gM=`${v("gray",me)} `;var Ma=(e)=>new ka({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Xe.withGuide,n=`${`${t?`${v("gray",me)}
64
- `:""}${Ea(this.state)} `}${e.message}
65
- `,r=e.placeholder&&e.placeholder.length>0?v("inverse",e.placeholder[0])+v("dim",e.placeholder.slice(1)):v(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${v("yellow",this.error)}`:"",a=t?`${v("yellow",me)} `:"",u=t?v("yellow",gn):"";return`${n.trim()}
62
+ ${M("gray",h+Wl.repeat(u+2)+Jw)}
63
+ `)};var pM={light:Me("─","-"),heavy:Me("━","="),block:Me("█","#")};var wM=[`${M("dim","↑/↓")} to navigate`,`${M("dim","Enter:")} confirm`];var bM=`${M("gray",me)} `;var Ra=(e)=>new Ma({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Xe.withGuide,n=`${`${t?`${M("gray",me)}
64
+ `:""}${Ia(this.state)} `}${e.message}
65
+ `,r=e.placeholder&&e.placeholder.length>0?M("inverse",e.placeholder[0])+M("dim",e.placeholder.slice(1)):M(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${M("yellow",this.error)}`:"",a=t?`${M("yellow",me)} `:"",u=t?M("yellow",fn):"";return`${n.trim()}
66
66
  ${a}${i}
67
67
  ${u}${o}
68
- `}case"submit":{let o=s?` ${v("dim",s)}`:"",a=t?v("gray",me):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${v(["strikethrough","dim"],s)}`:"",a=t?v("gray",me):"";return`${n}${a}${o}${s.trim()?`
69
- ${a}`:""}`}default:{let o=t?`${v("cyan",me)} `:"",a=t?v("cyan",gn):"";return`${n}${o}${i}
68
+ `}case"submit":{let o=s?` ${M("dim",s)}`:"",a=t?M("gray",me):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${M(["strikethrough","dim"],s)}`:"",a=t?M("gray",me):"";return`${n}${a}${o}${s.trim()?`
69
+ ${a}`:""}`}default:{let o=t?`${M("cyan",me)} `:"",a=t?M("cyan",fn):"";return`${n}${o}${i}
70
70
  ${a}
71
- `}}}}).prompt();function Sa(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function pn(e){return`\x1B[38;2;${Sa(e)}m`}function Fs(e,t){return`\x1B[48;2;${Sa(e)};38;2;${Sa(t)}m`}function Jl(e,t="\x1B[39m"){return`${e.map((n)=>`${pn(n)}■`).join(" ")}${t}`}function zw(e,t){if(e[t]!=="\x1B"||e[t+1]!=="[")return 0;let n=t+2;while(n<e.length&&!/[@-~]/.test(e[n]))n++;return n<e.length?n-t+1:0}function Kl(e,t){let n="",r=0,i=0;while(i<e.length){let s=zw(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=Ce(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r,rest:e.slice(i)}}function mn(e,t,n=!0){if(t<=0)return"";let r=Ce(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=Kl(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function ql(e,t,n){let r=n-Ce(t)-1;return r<=0?mn(e,n):`${mn(e,r)} ${t}`}function it(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if(Ce(s)<=t){r=s;continue}if(r)n.push(r);while(Ce(i)>t){let{head:o,rest:a}=Kl(i,t);n.push(o),i=a}r=i}if(r)n.push(r);return n}import{existsSync as Pd,readFileSync as Au}from"node:fs";import{join as Td}from"node:path";var Vw=/^#[0-9a-f]{6}$/;function br(e){return Vw.test(e)}function qe(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function et(e){let[t,n,r]=qe(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function ut(e,t){let n=et(e),r=et(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Ps(e,t){return Math.round(ut(e,t)*100)/100}function Xw(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Mt(e){let[t,n,r]=qe(e).map(Xw),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var wn=7,Ql=3,Ia=0.15,Yl=1.6,Ra=[1,2,3,4,5,6,9,10,11,12,13,14],Zl=[7,15],$r=[1,2,3,4,5,6],mi={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}},Oa=0.03,Wn=25,Ls=15,Gs=0.08;function Xt(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function Na(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=Xt(e,i);return ut(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Ps(s,r)}:1, needs ${n}:1`]:[]})}function zl(e,t){return Math.min(...t.map((n)=>ut(Xt(e,n),e.background)))}var Vl=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:wn,measure:({foreground:e,background:t})=>ut(e,t),check:({foreground:e,background:t})=>ut(e,t)<wn?[`foreground ${e} on ${t} is ${Ps(e,t)}:1, needs ${wn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Ql,measure:(e)=>zl(e,Ra),check:(e)=>Na(e,Ra,Ql)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Ia,measure:(e)=>et(Xt(e,0)),check:(e)=>{let t=Xt(e,0);return et(t)>Ia?[`ANSI 0 ${t} has luminance ${et(t).toFixed(3)}, needs <= ${Ia}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:wn,measure:(e)=>zl(e,Zl),check:(e)=>Na(e,Zl,wn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Yl,measure:(e)=>ut(Xt(e,8),e.background),check:(e)=>Na(e,[8],Yl)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:wn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:ut(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&ut(e,t)<wn?[`foreground ${e} on selection ${t} is ${Ps(e,t)}:1, needs ${wn}:1`]:[]}];function bn(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var kr=(e)=>e>8?e-8:e;function Us(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>$r.includes(kr(n))?[n,n>8?n-8:n+8]:[n]))}function gi(e,t){let n=Mt(Xt(e,t));return n.c<Oa?void 0:n}function Ts(e){let t=Us(e);return Ra.flatMap((n)=>{let r=gi(e,n),i=mi[kr(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=bn(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function As(e){let t=new Set(e.signatureSlots);return $r.flatMap((n)=>{let r=gi(e,n),i=gi(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:bn(r.h,i.h)}]})}function Hs(e){let t=Us(e);return[0,8].flatMap((n)=>$r.flatMap((r)=>$r.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=gi(e,s),u=gi(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return bn(a.h,u.h)<Ls&&Math.abs(a.l-u.l)<Gs?[[s,o]]:[]})))}var Bw=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Ts(e).map((t)=>t.over)),check:(e)=>Ts(e).map(({slot:t,hue:n,over:r})=>{let i=mi[kr(t)];return`ANSI ${t} ${Xt(e,t)} 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:Wn,measure:(e)=>Math.max(0,...As(e).map((t)=>t.gap)),check:(e)=>As(e).filter((t)=>t.gap>Wn).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${Wn}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>Hs(e).length,check:(e)=>Hs(e).map(([t,n])=>`ANSI ${t} ${Xt(e,t)} and ANSI ${n} ${Xt(e,n)} are within ${Ls}° hue and ${Gs} lightness`)}],_s=[...Vl,...Bw],Fa=_s.map((e)=>e.rule),Lt=_s.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function yr(e){return _s.map((t)=>Math.round(t.measure(e)*1000)/1000)}function Xl(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function Cs(e){return Xl(_s,e)}function Bl(e){return Xl(Vl,e)}function xl(e){return e.flatMap(Cs)}import{chmodSync as xw,copyFileSync as Dw,existsSync as Er,mkdirSync as eb,readFileSync as Pa,realpathSync as tb,renameSync as nb,rmSync as Dl,statSync as rb,writeFileSync as ib}from"node:fs";import{dirname as sb}from"node:path";function eh(e){return`${e}.ttheme.bak`}var ob=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Ta(e){let t=eh(e);if(Er(e)&&!Er(t)&&!ob.test(Pa(e,"utf8")))Dw(e,t)}function be(e,t){let n=Er(e)?tb(e):e;eb(sb(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(ib(r,t),Er(n))xw(r,rb(n).mode&4095);nb(r,n)}function pi(e,t){if((Er(e)?Pa(e,"utf8"):void 0)===t)return!1;return Ta(e),be(e,t),!0}function th(e,t){let n=eh(e),r=Er(n)?Pa(n,"utf8"):void 0;if(t===""&&r===void 0)return Dl(e,{force:!0}),"removed";if(be(e,t),r===void 0||r===t)return Dl(n,{force:!0}),"restored";return"kept backup"}import{createHash as nd}from"node:crypto";import{copyFileSync as A$,existsSync as bu,mkdirSync as H$,readdirSync as L$,readFileSync as oo,renameSync as rd,rmSync as Pr}from"node:fs";import{basename as id,isAbsolute as G$,join as V}from"node:path";var nf=Es(uh(),1),Ws=Es(ef(),1);import{deflateSync as S0}from"node:zlib";var $i=[137,80,78,71,13,10,26,10],rf=13,sf=3;function Ir(e){return e.length>=$i.length&&$i.every((t,n)=>e[n]===t)}function Kn(e){let t=Ws.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function qn(e,t){if(Ir(e)){let n=yn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return Kn(e)}if(e[0]===255&&e[1]===216){let n=nf.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:t/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function za(e){let t=new Ws.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Ws.PNG.sync.write(t)}function tf(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function yn(e){if(e.length<33||!Ir(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(16),r=t.getUint32(20);if(e[25]===4||e[25]===6)return{width:n,height:r,alpha:!0};let i=tf(e,"IDAT");return{width:n,height:r,alpha:tf(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function of(e,t=rf){let{width:n,height:r}=e,i=-1,s=-1;for(let o=0;o<e.height;o++)for(let a=0;a<e.width;a++)if((e.data[(o*e.width+a)*4+3]??0)>=t)n=Math.min(n,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return i<0?null:{x:n,y:r,w:i-n+1,h:s-r+1}}function Bt(e,t={x:0,y:0,w:e.width,h:e.height}){let n=0;for(let r=t.y;r<t.y+t.h;r++)for(let i=t.x;i<t.x+t.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<rf)n++;return Math.round(n*100/(t.w*t.h))}function af(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=N0(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function I0(e){let t=Math.abs(e);if(t<1)return(7*t*t*t-12*t*t+5.333333333333333)/6;if(t<2)return(-2.3333333333333335*t*t*t+12*t*t-20*t+10.666666666666666)/6;return 0}function Va(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,h)=>t+h),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,s=Math.max(1,i),o=2*s,a=Math.min(e,Math.ceil(2*o)+2),u=new Int32Array(r),c=new Float32Array(r*a);for(let l=0;l<r;l++){let h=t+(l+0.5)*i,f=Math.floor(h-o-0.5),d=Math.max(0,Math.min(e-a,f));u[l]=d;let g=0;for(let m=f;m<=Math.ceil(h+o-0.5);m++){let $=I0((m+0.5-h)/s),w=l*a+Math.min(e-1,Math.max(0,m))-d;c[w]=(c[w]??0)+$,g+=$}for(let m=l*a;m<(l+1)*a;m++)c[m]=(c[m]??0)/g}return{first:u,size:a,weights:c}}function uf(e,t,n,r,i,s){let o=Va(e,t.y,t.h,r),a=n*i,u=new Float32Array(a*r),c=new Map;for(let l=0;l<r;l++){let h=o.first[l]??0;for(let d of c.keys())if(d<h)c.delete(d);let f=l*a;for(let d=0;d<o.size;d++){let g=o.weights[l*o.size+d]??0;if(g===0)continue;let m=c.get(h+d);if(!m)m=new Float32Array(a),s(h+d,m),c.set(h+d,m);for(let $=0;$<a;$++)u[f+$]=(u[f+$]??0)+(m[$]??0)*g}}return u}function N0(e,t,n,r){let i=Va(e.width,t.x,t.w,n),s=e.data,o=uf(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let h=0;h<n;h++){let f=l+(i.first[h]??0),d=h*i.size,g=0,m=0,$=0,w=0;for(let M=0;M<i.size;M++){let y=(f+M)*4,S=(i.weights[d+M]??0)*(s[y+3]??0);g+=(s[y]??0)*S,m+=(s[y+1]??0)*S,$+=(s[y+2]??0)*S,w+=S}c[h*4]=g,c[h*4+1]=m,c[h*4+2]=$,c[h*4+3]=w}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function cf(e,t,n,r){let i=Va(e.width,t.x,t.w,n),s=e.data,o=uf(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let h=c+(i.first[l]??0),f=l*i.size,d=0;for(let g=0;g<i.size;g++)d+=(s[h+g]??0)*(i.weights[f+g]??0);u[l]=d}});return{width:n,height:r,data:o}}function Js(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,h)=>Math.exp(-((h-n)**2)/(2*t*t))),i=r.reduce((l,h)=>l+h,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=0;f<s;f++){let d=0;for(let g=-n;g<=n;g++)d+=(a[h+Math.min(s-1,Math.max(0,f+g))]??0)*(r[g+n]??0);u[h+f]=d/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=-n;f<=n;f++){let d=(r[f+n]??0)/i,g=Math.min(o-1,Math.max(0,l+f))*s;for(let m=0;m<s;m++)c[h+m]=(c[h+m]??0)+(u[g+m]??0)*d}}return{width:s,height:o,data:c}}function ki(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function yi(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var R0=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function O0(e){let t=4294967295;for(let n of e)t=(R0[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function bi(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE(O0(n.subarray(4,8+t.length)),8+t.length),n}function F0(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,h=s>0?e[u+c]??0:0,f=c>0&&s>0?e[u+c-1]??0:0,d=Math.abs(h-f),g=Math.abs(l-f),m=Math.abs(l+h-2*f);i[o+1+c]=(e[a+c]??0)-(d<=g&&d<=m?l:g<=m?h:f)&255}}return i}function lf(e,t,n){let r=Buffer.alloc(13);return r.writeUInt32BE(e.width,0),r.writeUInt32BE(e.height,4),r[8]=8,r[9]=t,Buffer.concat([Buffer.from($i),bi("IHDR",r),...n,bi("IDAT",S0(F0(e.data,e.width,e.height))),bi("IEND",new Uint8Array)])}function hf(e){let[t,n,r]=qe(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return bi("PLTE",i)}function Ei(e,t){return lf(e,sf,[hf(t),bi("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function Xa(e){return lf(e,0,[])}function ff(e,t){if(!Ir(e)||e[25]!==sf)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from($i)],i=$i.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?hf(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as E$,readFileSync as Qf}from"node:fs";import{basename as v$,join as Yf}from"node:path";/*!
71
+ `}}}}).prompt();function Fa(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function gn(e){return`\x1B[38;2;${Fa(e)}m`}function Gs(e,t){return`\x1B[48;2;${Fa(e)};38;2;${Fa(t)}m`}function Yl(e,t="\x1B[39m"){return`${e.map((n)=>`${gn(n)}■`).join(" ")}${t}`}function Dw(e,t){if(e[t]!=="\x1B"||e[t+1]!=="[")return 0;let n=t+2;while(n<e.length&&!/[@-~]/.test(e[n]))n++;return n<e.length?n-t+1:0}function Zl(e,t){let n="",r=0,i=0;while(i<e.length){let s=Dw(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=Ce(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r,rest:e.slice(i)}}function dn(e,t,n=!0){if(t<=0)return"";let r=Ce(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=Zl(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function zl(e,t,n){let r=n-Ce(t)-1;return r<=0?dn(e,n):`${dn(e,r)} ${t}`}function et(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if(Ce(s)<=t){r=s;continue}if(r)n.push(r);while(Ce(i)>t){let{head:o,rest:a}=Zl(i,t);n.push(o),i=a}r=i}if(r)n.push(r);return n}import{existsSync as Ud,readFileSync as Gu}from"node:fs";import{join as _d}from"node:path";var eb=/^#[0-9a-f]{6}$/;function br(e){return eb.test(e)}function qe(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function tt(e){let[t,n,r]=qe(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function ut(e,t){let n=tt(e),r=tt(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Us(e,t){return Math.round(ut(e,t)*100)/100}function tb(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Mt(e){let[t,n,r]=qe(e).map(tb),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var mn=7,Vl=3,Oa=0.15,Xl=1.6,Ta=[1,2,3,4,5,6,9,10,11,12,13,14],Bl=[7,15],$r=[1,2,3,4,5,6],mi={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}},Aa=0.03,jn=25,Ws=15,Js=0.08;function Xt(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function Pa(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=Xt(e,i);return ut(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Us(s,r)}:1, needs ${n}:1`]:[]})}function xl(e,t){return Math.min(...t.map((n)=>ut(Xt(e,n),e.background)))}var Dl=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:mn,measure:({foreground:e,background:t})=>ut(e,t),check:({foreground:e,background:t})=>ut(e,t)<mn?[`foreground ${e} on ${t} is ${Us(e,t)}:1, needs ${mn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Vl,measure:(e)=>xl(e,Ta),check:(e)=>Pa(e,Ta,Vl)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Oa,measure:(e)=>tt(Xt(e,0)),check:(e)=>{let t=Xt(e,0);return tt(t)>Oa?[`ANSI 0 ${t} has luminance ${tt(t).toFixed(3)}, needs <= ${Oa}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:mn,measure:(e)=>xl(e,Bl),check:(e)=>Pa(e,Bl,mn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Xl,measure:(e)=>ut(Xt(e,8),e.background),check:(e)=>Pa(e,[8],Xl)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:mn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:ut(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&ut(e,t)<mn?[`foreground ${e} on selection ${t} is ${Us(e,t)}:1, needs ${mn}:1`]:[]}];function pn(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var kr=(e)=>e>8?e-8:e;function Ks(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>$r.includes(kr(n))?[n,n>8?n-8:n+8]:[n]))}function gi(e,t){let n=Mt(Xt(e,t));return n.c<Aa?void 0:n}function _s(e){let t=Ks(e);return Ta.flatMap((n)=>{let r=gi(e,n),i=mi[kr(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=pn(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function Cs(e){let t=new Set(e.signatureSlots);return $r.flatMap((n)=>{let r=gi(e,n),i=gi(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:pn(r.h,i.h)}]})}function js(e){let t=Ks(e);return[0,8].flatMap((n)=>$r.flatMap((r)=>$r.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=gi(e,s),u=gi(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return pn(a.h,u.h)<Ws&&Math.abs(a.l-u.l)<Js?[[s,o]]:[]})))}var nb=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,..._s(e).map((t)=>t.over)),check:(e)=>_s(e).map(({slot:t,hue:n,over:r})=>{let i=mi[kr(t)];return`ANSI ${t} ${Xt(e,t)} 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:jn,measure:(e)=>Math.max(0,...Cs(e).map((t)=>t.gap)),check:(e)=>Cs(e).filter((t)=>t.gap>jn).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${jn}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>js(e).length,check:(e)=>js(e).map(([t,n])=>`ANSI ${t} ${Xt(e,t)} and ANSI ${n} ${Xt(e,n)} are within ${Ws}° hue and ${Js} lightness`)}],qs=[...Dl,...nb],Ha=qs.map((e)=>e.rule),Lt=qs.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function yr(e){return qs.map((t)=>Math.round(t.measure(e)*1000)/1000)}function eh(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function Qs(e){return eh(qs,e)}function th(e){return eh(Dl,e)}function nh(e){return e.flatMap(Qs)}import{chmodSync as rb,copyFileSync as ib,existsSync as Er,mkdirSync as sb,readFileSync as La,realpathSync as ob,renameSync as ab,rmSync as rh,statSync as ub,writeFileSync as cb}from"node:fs";import{dirname as lb}from"node:path";function ih(e){return`${e}.ttheme.bak`}var hb=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function Ga(e){let t=ih(e);if(Er(e)&&!Er(t)&&!hb.test(La(e,"utf8")))ib(e,t)}function be(e,t){let n=Er(e)?ob(e):e;sb(lb(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(cb(r,t),Er(n))rb(r,ub(n).mode&4095);ab(r,n)}function pi(e,t){if((Er(e)?La(e,"utf8"):void 0)===t)return!1;return Ga(e),be(e,t),!0}function sh(e,t){let n=ih(e),r=Er(n)?La(n,"utf8"):void 0;if(t===""&&r===void 0)return rh(e,{force:!0}),"removed";if(be(e,t),r===void 0||r===t)return rh(n,{force:!0}),"restored";return"kept backup"}import{createHash as od}from"node:crypto";import{copyFileSync as _$,existsSync as yu,mkdirSync as C$,readdirSync as j$,readFileSync as ho,renameSync as ad,rmSync as Tr}from"node:fs";import{basename as ud,isAbsolute as W$,join as V}from"node:path";var af=Rs(fh(),1),Zs=Rs(sf(),1);import{deflateSync as O0}from"node:zlib";var $i=[137,80,78,71,13,10,26,10],uf=13,cf=3;function Ir(e){return e.length>=$i.length&&$i.every((t,n)=>e[n]===t)}function Jn(e){let t=Zs.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Kn(e,t){if(Ir(e)){let n=$n(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return Jn(e)}if(e[0]===255&&e[1]===216){let n=af.decode(e,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:t/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function xa(e){let t=new Zs.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Zs.PNG.sync.write(t)}function of(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function $n(e){if(e.length<33||!Ir(e))return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(16),r=t.getUint32(20);if(e[25]===4||e[25]===6)return{width:n,height:r,alpha:!0};let i=of(e,"IDAT");return{width:n,height:r,alpha:of(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function lf(e,t=uf){let{width:n,height:r}=e,i=-1,s=-1;for(let o=0;o<e.height;o++)for(let a=0;a<e.width;a++)if((e.data[(o*e.width+a)*4+3]??0)>=t)n=Math.min(n,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return i<0?null:{x:n,y:r,w:i-n+1,h:s-r+1}}function Bt(e,t={x:0,y:0,w:e.width,h:e.height}){let n=0;for(let r=t.y;r<t.y+t.h;r++)for(let i=t.x;i<t.x+t.w;i++)if((e.data[(r*e.width+i)*4+3]??0)<uf)n++;return Math.round(n*100/(t.w*t.h))}function hf(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=T0(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function P0(e){let t=Math.abs(e);if(t<1)return(7*t*t*t-12*t*t+5.333333333333333)/6;if(t<2)return(-2.3333333333333335*t*t*t+12*t*t-20*t+10.666666666666666)/6;return 0}function Da(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,h)=>t+h),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,s=Math.max(1,i),o=2*s,a=Math.min(e,Math.ceil(2*o)+2),u=new Int32Array(r),c=new Float32Array(r*a);for(let l=0;l<r;l++){let h=t+(l+0.5)*i,f=Math.floor(h-o-0.5),d=Math.max(0,Math.min(e-a,f));u[l]=d;let g=0;for(let m=f;m<=Math.ceil(h+o-0.5);m++){let $=P0((m+0.5-h)/s),p=l*a+Math.min(e-1,Math.max(0,m))-d;c[p]=(c[p]??0)+$,g+=$}for(let m=l*a;m<(l+1)*a;m++)c[m]=(c[m]??0)/g}return{first:u,size:a,weights:c}}function ff(e,t,n,r,i,s){let o=Da(e,t.y,t.h,r),a=n*i,u=new Float32Array(a*r),c=new Map;for(let l=0;l<r;l++){let h=o.first[l]??0;for(let d of c.keys())if(d<h)c.delete(d);let f=l*a;for(let d=0;d<o.size;d++){let g=o.weights[l*o.size+d]??0;if(g===0)continue;let m=c.get(h+d);if(!m)m=new Float32Array(a),s(h+d,m),c.set(h+d,m);for(let $=0;$<a;$++)u[f+$]=(u[f+$]??0)+(m[$]??0)*g}}return u}function T0(e,t,n,r){let i=Da(e.width,t.x,t.w,n),s=e.data,o=ff(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let h=0;h<n;h++){let f=l+(i.first[h]??0),d=h*i.size,g=0,m=0,$=0,p=0;for(let E=0;E<i.size;E++){let y=(f+E)*4,S=(i.weights[d+E]??0)*(s[y+3]??0);g+=(s[y]??0)*S,m+=(s[y+1]??0)*S,$+=(s[y+2]??0)*S,p+=S}c[h*4]=g,c[h*4+1]=m,c[h*4+2]=$,c[h*4+3]=p}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function df(e,t,n,r){let i=Da(e.width,t.x,t.w,n),s=e.data,o=ff(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let h=c+(i.first[l]??0),f=l*i.size,d=0;for(let g=0;g<i.size;g++)d+=(s[h+g]??0)*(i.weights[f+g]??0);u[l]=d}});return{width:n,height:r,data:o}}function zs(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,h)=>Math.exp(-((h-n)**2)/(2*t*t))),i=r.reduce((l,h)=>l+h,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=0;f<s;f++){let d=0;for(let g=-n;g<=n;g++)d+=(a[h+Math.min(s-1,Math.max(0,f+g))]??0)*(r[g+n]??0);u[h+f]=d/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let h=l*s;for(let f=-n;f<=n;f++){let d=(r[f+n]??0)/i,g=Math.min(o-1,Math.max(0,l+f))*s;for(let m=0;m<s;m++)c[h+m]=(c[h+m]??0)+(u[g+m]??0)*d}}return{width:s,height:o,data:c}}function ki(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function yi(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var A0=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function H0(e){let t=4294967295;for(let n of e)t=(A0[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function bi(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE(H0(n.subarray(4,8+t.length)),8+t.length),n}function L0(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,h=s>0?e[u+c]??0:0,f=c>0&&s>0?e[u+c-1]??0:0,d=Math.abs(h-f),g=Math.abs(l-f),m=Math.abs(l+h-2*f);i[o+1+c]=(e[a+c]??0)-(d<=g&&d<=m?l:g<=m?h:f)&255}}return i}function gf(e,t,n){let r=Buffer.alloc(13);return r.writeUInt32BE(e.width,0),r.writeUInt32BE(e.height,4),r[8]=8,r[9]=t,Buffer.concat([Buffer.from($i),bi("IHDR",r),...n,bi("IDAT",O0(L0(e.data,e.width,e.height))),bi("IEND",new Uint8Array)])}function mf(e){let[t,n,r]=qe(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return bi("PLTE",i)}function Ei(e,t){return gf(e,cf,[mf(t),bi("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function eu(e){return gf(e,0,[])}function pf(e,t){if(!Ir(e)||e[25]!==cf)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from($i)],i=$i.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?mf(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as N$,readFileSync as Vf}from"node:fs";import{basename as R$,join as Xf}from"node:path";/*!
72
72
  * Copyright (c) Squirrel Chat et al., All rights reserved.
73
73
  * SPDX-License-Identifier: BSD-3-Clause
74
74
  *
@@ -94,9 +94,9 @@ ${a}
94
94
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
95
95
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
96
96
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97
- */function P0(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function T0(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
97
+ */function G0(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function U0(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
98
98
  `,o===t)i+=" ".repeat(s+n+2),i+=`^
99
- `}return i}class W extends Error{line;column;codeblock;constructor(e,t){let[n,r]=P0(t.toml,t.ptr),i=T0(t.toml,n,r);super(`Invalid TOML document: ${e}
99
+ `}return i}class W extends Error{line;column;codeblock;constructor(e,t){let[n,r]=G0(t.toml,t.ptr),i=U0(t.toml,n,r);super(`Invalid TOML document: ${e}
100
100
 
101
101
  ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(e,{toml:t.s,ptr:n??t.p})}}/*!
102
102
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -124,7 +124,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
124
124
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
125
125
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
126
126
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
127
- */function Ks(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)W.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,h=n===120?2:n===117?4:8;for(let f=0;f<h;f++,e.p++){let d=e.s.charCodeAt(e.p),g=d>=48&&d<=57?d-48:d>=65&&d<=70?d-65+10:d>=97&&d<=102?d-97+10:-1;if(g<0)W.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)W.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
127
+ */function Vs(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)W.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,h=n===120?2:n===117?4:8;for(let f=0;f<h;f++,e.p++){let d=e.s.charCodeAt(e.p),g=d>=48&&d<=57?d-48:d>=65&&d<=70?d-65+10:d>=97&&d<=102?d-97+10:-1;if(g<0)W.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)W.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
128
128
  `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else W.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)W.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}W.x("unfinished string",e,t)}/*!
129
129
  * Copyright (c) Squirrel Chat et al., All rights reserved.
130
130
  * SPDX-License-Identifier: BSD-3-Clause
@@ -151,7 +151,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
151
151
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
152
152
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
153
153
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
154
- */var A0=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class En extends Date{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match(A0);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}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 t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new En(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new En(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new En(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new En(e);return t.#t=!1,t.#e=null,t}}/*!
154
+ */var _0=/^(\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{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match(_0);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}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 t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new kn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new kn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new kn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new kn(e);return t.#t=!1,t.#e=null,t}}/*!
155
155
  * Copyright (c) Squirrel Chat et al., All rights reserved.
156
156
  * SPDX-License-Identifier: BSD-3-Clause
157
157
  *
@@ -177,7 +177,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
177
177
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
178
178
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
179
179
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
180
- */function ct(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function xa(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Mi(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||W.x("document contains excessively nested structures. aborting.",e);let i=r===91?mf(e):gf(e);return e.d++,i}if(r===34||r===39)return Ks(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)W.x("invalid value",e,n);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)W.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return qs(e,e.p,e.s.charCodeAt(++e.p),44-r,t);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return H0(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return L0(e,r,t);return qs(e,e.p,r,0,t)}function qs(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)W.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)W.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||xa(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return Ba(e,t,16,i);else if(s===98)return Ba(e,t,2,i);else if(s===111)return Ba(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else W.x("illegal leading zero",e,t)}else if(!ct(s))W.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!xa(s,i))){if(!o)o=1;if(s===95){if(!(o&1))W.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!ct(s))W.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))W.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):df(e,u,10,t)}function Ba(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!xa(i,r)))if(i===95){if(s&1)W.x("illegal underscore",e);s=3}else if(!ct(i,n))W.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)W.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return df(e,o,n,t)}function df(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;W.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function H0(e,t,n){let r=e.p++,i;if(!ct(t)||!ct(e.s.charCodeAt(e.p++))||!ct(e.s.charCodeAt(e.p++))||!ct(e.s.charCodeAt(e.p++)))return qs(e,e.p=r,t,0,n);if(e.p+=5,!ct(e.s.charCodeAt(e.p++)))W.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!ct(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return vi(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)W.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(ct(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return vi(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return vi(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return vi(e,s,2,i,r)}function L0(e,t,n){let r=e.p;if(!ct(t)||!ct(e.s.charCodeAt(++e.p)))return qs(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(ct(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return vi(e,i,4,!1,r)}function vi(e,t,n,r,i,s){if(e.ld){let o=new En(t,n,r);if(!o.isValid())W.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){W.x(o instanceof Error?o.message:""+o,e,i)}}/*!
180
+ */function ct(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function nu(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Mi(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||W.x("document contains excessively nested structures. aborting.",e);let i=r===91?$f(e):bf(e);return e.d++,i}if(r===34||r===39)return Vs(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)W.x("invalid value",e,n);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)W.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Xs(e,e.p,e.s.charCodeAt(++e.p),44-r,t);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return C0(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return j0(e,r,t);return Xs(e,e.p,r,0,t)}function Xs(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)W.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)W.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||nu(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return tu(e,t,16,i);else if(s===98)return tu(e,t,2,i);else if(s===111)return tu(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else W.x("illegal leading zero",e,t)}else if(!ct(s))W.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!nu(s,i))){if(!o)o=1;if(s===95){if(!(o&1))W.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!ct(s))W.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))W.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):wf(e,u,10,t)}function tu(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!nu(i,r)))if(i===95){if(s&1)W.x("illegal underscore",e);s=3}else if(!ct(i,n))W.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)W.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return wf(e,o,n,t)}function wf(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;W.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function C0(e,t,n){let r=e.p++,i;if(!ct(t)||!ct(e.s.charCodeAt(e.p++))||!ct(e.s.charCodeAt(e.p++))||!ct(e.s.charCodeAt(e.p++)))return Xs(e,e.p=r,t,0,n);if(e.p+=5,!ct(e.s.charCodeAt(e.p++)))W.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!ct(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return vi(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)W.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(ct(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return vi(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return vi(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return vi(e,s,2,i,r)}function j0(e,t,n){let r=e.p;if(!ct(t)||!ct(e.s.charCodeAt(++e.p)))return Xs(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(ct(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return vi(e,i,4,!1,r)}function vi(e,t,n,r,i,s){if(e.ld){let o=new kn(t,n,r);if(!o.isValid())W.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){W.x(o instanceof Error?o.message:""+o,e,i)}}/*!
181
181
  * Copyright (c) Squirrel Chat et al., All rights reserved.
182
182
  * SPDX-License-Identifier: BSD-3-Clause
183
183
  *
@@ -203,7 +203,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
203
203
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
204
204
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
205
205
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
206
- */function G0(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)W.x("control characters are not allowed in comments",e)}}function It(e,t,n){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(n||r!==35)break;G0(e)}}/*!
206
+ */function W0(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)W.x("control characters are not allowed in comments",e)}}function It(e,t,n){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(n||r!==35)break;W0(e)}}/*!
207
207
  * Copyright (c) Squirrel Chat et al., All rights reserved.
208
208
  * SPDX-License-Identifier: BSD-3-Clause
209
209
  *
@@ -229,7 +229,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
229
229
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
230
230
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
231
231
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
232
- */function Qs(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)W.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)W.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))W.x("illegal quoted key: multiline strings are not allowed",e);i.push(Ks(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)W.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));W.x("incomplete key-value: cannot find end of key",e,n)}function gf(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(It(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Qs(e);for(let h=0;h<c.length;h++){if(h)o=a?o[s]:o[s]=Object.create(null);if(s=c[h],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))W.x("trying to redefine an already defined value",e,u);let f=s==="__proto__";if(e.uk&&(f||s==="constructor")){o=e.uk!==1&&W.x("document contains an unsafe property",e,u);break}if(!a&&f)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)W.x("trying to redefine an already defined value",e,u);It(e,!0,!0);let l=Mi(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(It(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished table",e,t)}function mf(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(It(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Mi(e,93)),It(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished array",e,t)}/*!
232
+ */function Bs(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)W.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)W.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))W.x("illegal quoted key: multiline strings are not allowed",e);i.push(Vs(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)W.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));W.x("incomplete key-value: cannot find end of key",e,n)}function bf(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(It(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Bs(e);for(let h=0;h<c.length;h++){if(h)o=a?o[s]:o[s]=Object.create(null);if(s=c[h],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))W.x("trying to redefine an already defined value",e,u);let f=s==="__proto__";if(e.uk&&(f||s==="constructor")){o=e.uk!==1&&W.x("document contains an unsafe property",e,u);break}if(!a&&f)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)W.x("trying to redefine an already defined value",e,u);It(e,!0,!0);let l=Mi(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(It(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished table",e,t)}function $f(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(It(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Mi(e,93)),It(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)W.x("expected comma or end of structure",e,e.p-1)}W.x("unfinished array",e,t)}/*!
233
233
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
234
  * SPDX-License-Identifier: BSD-3-Clause
235
235
  *
@@ -255,7 +255,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
255
255
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
256
256
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
257
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
- */function pf(e,t,n,r,i){let s=n,o=r,a,u=!1,c;for(let l=0;l<t.length;l++){if(l){if(s=u?s[a]:s[a]=Object.create(null),o=(c=o[a]).c,i===0&&(c.t===1||c.t===2))return null;if(c.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(a=t[l],(u=Object.hasOwn(s,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!u){let h=a==="__proto__";if(e.uk&&(h||a==="constructor"))return!1;if(h)Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0});o[a]={t:l<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==i&&!(i===1&&c.t===3))return null;if(i===2){if(!c.d)c.d=!0,s[a]=[];s[a].push(s=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}}if(c.d)return null;if(c.d=!0,i===1)s=u?s[a]:s[a]=Object.create(null);else if(i===0&&u)return null;return[a,s,c.c]}function wf(e,t,n){if(t===null||e.uk===2)W.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Da(e,t={}){let n={s:e,p:0,d:t.maxDepth??1000,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),s,o=!1,a=r,u=i;if(e.charCodeAt(0)===65279)n.p++;It(n);while(n.p<e.length){if(e.charCodeAt(n.p)===91){let c=e.charCodeAt(++n.p)===91;s=n.p+=+c,o=!1;let l=Qs(n,93);if(c){if(e.charCodeAt(n.p)!==93)W.x("expected end of table array declaration",n);n.p++}let h=pf(n,l,r,i,c?2:1);if(!h)wf(n,h,s),o=!0;else u=h[2],a=h[1]}else{s=n.p;let c=Qs(n),l=pf(n,c,a,u,0);if(!l&&!o)wf(n,l,s);It(n,!0,!0);let h=Mi(n,void 0);if(l&&!o)l[1][l[0]]=h}if(It(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))W.x("each key-value declaration must be followed by an end-of-line",n);It(n)}return r}/*!
258
+ */function kf(e,t,n,r,i){let s=n,o=r,a,u=!1,c;for(let l=0;l<t.length;l++){if(l){if(s=u?s[a]:s[a]=Object.create(null),o=(c=o[a]).c,i===0&&(c.t===1||c.t===2))return null;if(c.t===2){let h=s.length-1;s=s[h],o=o[h].c}}if(a=t[l],(u=Object.hasOwn(s,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!u){let h=a==="__proto__";if(e.uk&&(h||a==="constructor"))return!1;if(h)Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0});o[a]={t:l<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==i&&!(i===1&&c.t===3))return null;if(i===2){if(!c.d)c.d=!0,s[a]=[];s[a].push(s=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}}if(c.d)return null;if(c.d=!0,i===1)s=u?s[a]:s[a]=Object.create(null);else if(i===0&&u)return null;return[a,s,c.c]}function yf(e,t,n){if(t===null||e.uk===2)W.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function ru(e,t={}){let n={s:e,p:0,d:t.maxDepth??1000,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),s,o=!1,a=r,u=i;if(e.charCodeAt(0)===65279)n.p++;It(n);while(n.p<e.length){if(e.charCodeAt(n.p)===91){let c=e.charCodeAt(++n.p)===91;s=n.p+=+c,o=!1;let l=Bs(n,93);if(c){if(e.charCodeAt(n.p)!==93)W.x("expected end of table array declaration",n);n.p++}let h=kf(n,l,r,i,c?2:1);if(!h)yf(n,h,s),o=!0;else u=h[2],a=h[1]}else{s=n.p;let c=Bs(n),l=kf(n,c,a,u,0);if(!l&&!o)yf(n,l,s);It(n,!0,!0);let h=Mi(n,void 0);if(l&&!o)l[1][l[0]]=h}if(It(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))W.x("each key-value declaration must be followed by an end-of-line",n);It(n)}return r}/*!
259
259
  * Copyright (c) Squirrel Chat et al., All rights reserved.
260
260
  * SPDX-License-Identifier: BSD-3-Clause
261
261
  *
@@ -281,7 +281,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
281
281
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
282
282
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
283
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
- */var $S=!!"".isWellFormed;/*!
284
+ */var vS=!!"".isWellFormed;/*!
285
285
  * Copyright (c) Squirrel Chat et al., All rights reserved.
286
286
  * SPDX-License-Identifier: BSD-3-Clause
287
287
  *
@@ -307,78 +307,78 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new W(
307
307
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
308
308
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
309
309
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
310
- */import{readdirSync as U0,rmSync as _0,statSync as C0}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as j0}from"node:net";import{homedir as W0}from"node:os";import{join as Ii}from"node:path";import{setTimeout as J0}from"node:timers/promises";var vn=100,$t=25000000,K0=536870912,Ni=["safe","questionable","explicit"],Qn=["nudity","underwear"],nu=["comic","monochrome","sketch","chibi"],Mf=["off","5","10","25","50","100"],Sf=["off","720","1080","1440","1800","2560"],If={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},q0={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},Q0=/^(?:rating|score|width|height|filetype|dimension):/,Si={safe:"s",questionable:"q",explicit:"e"},Nf=8191,Y0=20000,Z0=5000,bf=3000,$f=8,z0=3000,Rf=60000,kf=3,V0=3,X0="https://static.zerochan.net",Of="https://s1.zerochan.net",ru=`ttheme/${Ve.version} (+${Ve.homepage})`,B0=["orig","tile","thumb","cut"],Ff=new Map,x0=f$(process.env.TTHEME_FIND_HOSTS),D0=h$(process.env.TTHEME_FIND_CUTOUTS);j0(z0);function yf(e){try{return U0(e)}catch{return[]}}function Nr(e){return e.startsWith("//")?`https:${e}`:e}function Sn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function Ri(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function e$(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function tu(e,t,n){let r=Nr(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Sn(r)}}function Pf(e,t){let n=Nr(String(t.preview??""));if(!t.file||!n||!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:t.file,preview:n,ext:t.ext,owner:String(t.owner??""),artist:t.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(t.md5??""),source:String(e.source??""),tags:t.tags.split(/\s+/).filter(Boolean),solo:t.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:t.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<r*i)}]}function t$(e){let t=e$(e);return Ri(e).flatMap((n)=>{let r=Nr(String(n.file_url??"")),i=String(n.tags??"");return Pf(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Sn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((s)=>t.get(s)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[tu(n.jpeg_url,n.jpeg_width,n.jpeg_height),tu(n.sample_url,n.sample_width,n.sample_height)]})})}function n$(e){return Ri(e).flatMap((t)=>{let n=Nr(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return Pf(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Sn(n)).toLowerCase(),owner:"",artist:String(t.tag_string_artist??"").split(/\s+/)[0]??"",md5:t.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>tu(s.url,s.width,s.height)).filter((s)=>s.ext==="jpg"||s.ext==="png").sort((s,o)=>o.width*o.height-s.width*s.height)})})}function r$(e){return(Array.isArray(e)?e:[]).map((t)=>String(t).toLowerCase().replace(/\s+/g,"_"))}function i$(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function s$(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=r$(i.tags),a=Nr(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Sn(a),preview:`${Of}/${i$(i.tag??i.primary)}.600.${s}.jpg`,owner:"",artist:"",score:0,rating:o.some((u)=>If.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,solo:o.includes("solo"),family:0,smaller:[]}]})}function o$(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function a$(e){return Ri(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function u$(e){return Ri(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function c$(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function l$(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function h$(e){let t=new Map;for(let n of(e??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)t.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return t}function f$(e){let t=new Map;for(let n of(e??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let s=new URL(n.slice(r+1));if(i&&s.protocol==="https:")t.set(i,s.origin)}catch{}}return t}function Zs(e,t,n,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let s=t.filter((o)=>i.includes(o));return s.length>0?s:[...n]}function Zn(e){return Zs(e,Ni,["safe"])}function Rr(e){return Zs(e,Qn,Qn,"none")}function zs(e){return Zs(e,nu,[],"none")}function Oi(e){let t=ee.map((n)=>n.name);return Zs(e,t,t)}function iu(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function Fi(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function su(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function ou(e){let t=x0.get(e.key),n=D0.get(e.key);return{...e,origin:t??e.origin,moved:t!==void 0&&t!==e.origin,cutouts:n??e.cutouts,vouched:e.vouched&&n===void 0}}function Tf(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function Af(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function Ef(e){let t=ou(e),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...t,scored:!0,narrow:({score:r,size:i})=>[...r>0?[`score:>=${r}`]:[],...Af(i)],cutouts:Tf(t.cutouts),ratings:su([Si.safe],[Si.questionable],[Si.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Si[i]}`;let s=Ni.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${Si[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(vn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${t.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/post/show/${r}`,parse:t$,count:c$}}function d$(e){let t=ou(e),n=su(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...Af(i),...s?["filetype:png"]:[]],cutouts:Tf(t.cutouts),ratings:n,rate:(r)=>r.length===Ni.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(vn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${t.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/posts/${r}`,parse:n$,count:l$}}function eu(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function vf(e){let t=e.split(/\s+/),n=t.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:t.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function g$(e){let t=ou(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:su(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${eu(n)}?${new URLSearchParams({json:"",l:String(vn),p:String(r+1),...vf(n)})}`,countUrl:(n)=>`${t.origin}/${eu(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:s$,count:o$,counts:(n)=>eu(n).split(",").length===1&&!("d"in vf(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Of,X0).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function m$(e){let t=Ys(`https://${e}`);return ee.find((n)=>Ys(n.origin)===t)}function au(e){return e.split(/\s+/).filter((t)=>t&&!Q0.test(t)).length}function Vs(e,t){let n=e.trim();if(/^\d+$/.test(n))return{site:t,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=ee.find((u)=>u.key===r[1]||u.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let s=m$(i.host),o=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return s&&o>0?{site:s,id:o}:void 0}var ee=[d$({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),Ef({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Ef({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),g$({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ut=ee.find((e)=>e.key==="danbooru"),xt=134217728;function _t(e,t){let n=ee.indexOf(e);return(n===-1?ee.length:n)*xt+t}function Ys(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function Xs(e,t,n=t){return t.mirror&&n===t?{site:Ut,url:t.mirror.file}:{site:e,url:n.file}}function Bs(e,t){return t.mirror?{site:Ut,url:t.mirror.preview}:{site:e,url:t.preview}}function xs(e,t=Qn){return e.tags.filter((n)=>t.some((r)=>If[r].has(n)))}function Hf(e,t){return e.tags.filter((n)=>t.some((r)=>q0[r].has(n)))}function Ds(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function Dt(e){return[e,...e.smaller].find((t)=>t.width*t.height<=$t)}function Lf(e){let t=new Map;for(let[n,r]of[...e].sort(([i],[s])=>i<s?-1:1)){if(r==="")continue;t.set(r,[...t.get(r)??[],n])}return t}function Or(){return Ii(process.env.XDG_CACHE_HOME??Ii(W0(),".cache"),"ttheme")}function Nt(e){return Ii(Or(),e.key)}function Gf(e=K0,t=Or()){let n=[],r=0;for(let i of yf(t))for(let s of B0){let o=Ii(t,i,s);for(let a of yf(o)){let u=Ii(o,a);try{let{size:c,mtimeMs:l}=C0(u);n.push({path:u,size:c,at:l}),r+=c}catch{}}}n.sort((i,s)=>i.at-s.at);for(let i of n){if(r<=e)return;try{_0(i.path,{force:!0}),r-=i.size}catch{}}}function p$(e,t){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let n=e===null?Number.NaN:Date.parse(e);return Number.isNaN(n)?Rf:Math.max(0,n-t)}function Mn(e){return Ff.get(e.key)??0}function w$(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function b$(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function $$(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Yn(e,t,n,r={},i=Y0){let s=t;for(let o=1,a=0;;o++){let u=Mn(e)-Date.now();if(u>0)await J0(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":ru,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(h){if(o<kf&&!n.aborted&&w$(h))continue;throw h}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<V0){await c.body?.cancel(),s=$$(s,l),a++,o--;continue}if(c.status===429&&o<kf){await c.body?.cancel();let h=p$(c.headers.get("retry-after"),Date.now());if(h>Rf)throw Error(`${e.name} asks to wait ${Math.ceil(h/1000)}s`);Ff.set(e.key,Math.max(Mn(e),Date.now()+h));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(b$(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function uu(e,t,n){try{return await(await Yn(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function Uf(e,t,n,r){return e.parse(await uu(e,e.postsUrl(t,n),r))}async function cu(e,t,n){return e.count(await uu(e,e.countUrl(t),n))}async function Pi(e,t,n){let[r]=e.parse(await uu(e,e.postUrl(t),n));return r}function k$(e){let t=new URLSearchParams({limit:String(2*vn),only:"md5,tag_string,file_url",tags:`md5:${e.join(",")}`});return`${Ut.origin}/posts.json?${t}`}function y$(e){return new Map(Ri(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:String(t.tag_string??"").split(/\s+/).filter(Boolean),file:Nr(String(t.file_url??""))}]]:[]}))}function _f(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=Sn(r.file)}}}async function Cf(e,t){let n=new Map;if(Mn(Ut)>Date.now())return n;for(let r=0;r<e.length;r+=vn){let i=await(await Yn(Ut,k$(e.slice(r,r+vn)),t,{},Z0)).text();for(let[s,o]of y$(i))n.set(s,o)}return n}async function eo(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Yn(e,r,n,{Range:`bytes=0-${Nf}`}),s=yn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Sn(r),s}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${e.name} keeps no png or jpg of ${t.id}`)}async function jf(e,t){if(Mn(Ut)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String($f)}),s=`${Ut.origin}/autocomplete.json?${i}`;return a$(await(await Yn(Ut,s,t,{},bf)).text())}catch(i){if(t.aborted)throw i}let n=ee.find((i)=>i.key==="yande"),r=new URLSearchParams({name:e,order:"count",limit:String($f)});return u$(await(await Yn(n,`${n.origin}/tag.json?${r}`,t,{},bf)).text())}async function Wf(e,t,n){let r=await Yn(e,t,n,{Range:`bytes=0-${Nf}`});return yn(new Uint8Array(await r.arrayBuffer()))}async function to(e,t,n,r){let i=await Yn(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:h,value:f}=await o.read();if(h)break;a.push(f),u+=f.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let h of a)c.set(h,l),l+=h.length;return c}var Vn=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Ti="Original",M$=1e6,Ct="_groups.toml",Jf=3,Kf=8,lu="[a-z0-9]+(?:-[a-z0-9]+)*",S$=new RegExp(`^(?:(${lu})@(${lu})/)?(${lu})$`),Zf=["background","foreground","cursor","selection"];function de(e,t){throw Error(`${e}: ${t}`)}function zn(e,t,n){if(typeof n!=="string"||!br(n))de(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Ai(e,t,n){if(typeof n!=="string"||n.length===0)de(e,`${t} must be a non-empty string`);return n}function en(e){return e.replace("@","--").replace("/","--")}function Me(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function ro(e){return e.slice(e.indexOf("/")+1)}function jt(e){let t=S$.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function hu(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 no(e,t,n){let r=Ai(e,t,n),i=hu(r);if(i)de(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function qf(e,t,n){let r=Ai(e,t,n),i=jt(r);if(i)de(e,`${t} "${r}" ${i}`);return r}function Fr(e){return e&&typeof e==="object"?e:{}}function I$(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)de(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>zn(e,`ghostty.icon_screen[${s}]`,i))}function N$(e,t,n){let r=Fr(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:zn(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:I$(e,r.icon_screen,n)}}function R$(e){return new Map([...Zf.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function O$(e,t,n){if(!Array.isArray(t)||t.length!==Jf)de(e,`meta.signature must name exactly ${Jf} palette slots`);let r=R$(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Ai(e,u,a),l=r.get(c);if(l===void 0)de(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${Zf.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)de(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function F$(e,t,n){if(t===void 0)return;if(!n)de(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))de(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=ee.find((u)=>u.key===i);if(!o)de(e,`meta.booru_sites.${i} is not a find site — use ${ee.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))de(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))de(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function P$(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>Kf)de(e,`[[picture]] holds 1 to ${Kf} pictures`);return t.map((n,r)=>{let i=Fr(n),s=`picture[${r}]`,o=ee.find((l)=>l.key===i.site);if(!o)de(e,`${s}.site must be one of ${ee.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)de(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))de(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!Vn.includes(u))de(e,`${s}.position must be one of ${Vn.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))de(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function zf(e,t){try{return Da(t)}catch(n){de(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
- `)[0]}`)}}function T$(e){let n=zf(Ct,Qf(Yf(e,Ct),"utf8")).group;if(!Array.isArray(n)||n.length===0)de(Ct,"needs at least one [[group]] table");return n.map((r)=>{let i=Fr(r);return{name:no(Ct,"group.name",i.name),native:i.native===void 0?void 0:no(Ct,"group.native",i.native),lead:Ai(Ct,"group.lead",i.lead)}})}function fu(e,t,n){let r=zf(e,t),i=Fr(r.meta),s=Fr(r.colors),o=Fr(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)de(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=qf(e,"meta.name",i.name);if(u!==n.name)de(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let O of["order","role"])if(c&&i[O]!==void 0)de(e,`meta.${O} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")de(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let h=i.base===void 0?void 0:qf(e,"meta.base",i.base);if(h!==void 0&&!c)de(e,"meta.base is for market palettes");let f=h===void 0?void 0:n.bases?.get(h),d=c&&i.group===void 0?f?.group??Ti:no(e,"meta.group",i.group),g=n.groups.get(d);if(!g&&!(c&&(d===Ti||n.open)))de(e,`meta.group "${d}" has no [[group]] table in ${Ct}`);let m=zn(e,"colors.background",s.background),$=zn(e,"colors.foreground",s.foreground),w=zn(e,"colors.cursor",s.cursor),M=zn(e,"colors.selection_background",s.selection_background),y=a.map((O,L)=>zn(e,`colors.ansi[${L}]`,O)),S=O$(e,i.signature,{background:m,foreground:$,cursor:w,selection:M,ansi:y}),p=i.booru===void 0?void 0:Ai(e,"meta.booru",i.booru);if(p!==void 0&&/[\s\p{Cc}]/u.test(p))de(e,`meta.booru must be a single booru tag, got ${JSON.stringify(p)}`);let N=F$(e,i.booru_sites,p),E=Array.isArray(o.waive)?o.waive.map(String):[];if(E.length>0&&typeof o.reason!=="string")de(e,"contrast.waive needs a contrast.reason explaining why");let F=P$(e,r.picture);return{name:u,...h?{base:h}:{},group:d,native:g?.native,lead:!c&&g?.lead===u,order:c?f?.order??M$:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?h??"original":no(e,"meta.ansi_source",i.ansi_source),...p?{booru:p}:{},...N?{booruSites:N}:{},background:m,foreground:$,cursor:w,selectionBackground:M,ansi:y,signature:S.colors,signatureSlots:S.names,ghostty:N$(e,r.ghostty,{background:m,cursor:w,selectionBackground:M}),waive:E,waiveReason:typeof o.reason==="string"?o.reason:void 0,...F?{pictures:F}:{}}}function Vf(e){let t=T$(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)de(Ct,"group.name must be unique");let r=E$(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>fu(s,Qf(Yf(e,s),"utf8"),{name:v$(s,".toml"),groups:n})).sort((s,o)=>s.order-o.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 t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)de(Ct,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))de(Ct,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function Xf(e){return e.filter((t)=>t.role===void 0)}function Xn(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>Me(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(Me(r.name)!==void 0)-Number(Me(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var io={width:2560,height:1550},U$=2560,_$=0.1,C$=0.99,j$=2,tn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},W$=et(gu("#19161e","#9b86c8",0.2)),J$="shelf",ao="originals",K$="images.json",du=1;function gu(e,t,n){let r=qe(e),i=qe(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function q$(e,t){if(t==="background"||t==="foreground"||t==="cursor")return e[t];if(t==="selection"&&e.selection)return e.selection;let n=/^ansi(\d|1[0-5])$/.exec(t),r=n?e.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${t}`);return r}function Bf(e){if(e(1))return 1;let t=0,n=1;for(let r=0;r<40;r++){let i=(t+n)/2;if(e(i))t=i;else n=i}return t}function xf(e,t){let n=q$(e,t),i=Bf((c)=>Bl({name:e.name,background:gu(e.background,n,c),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),s=Bf((c)=>et(gu(e.background,n,c))<=W$),o=Math.floor(Math.min(i,s)*1000)/1000,a=qe(e.background),u=Math.hypot(...qe(n).map((c,l)=>(c-(a[l]??0))*o));return{slot:t,color:n,cap:i,matched:s,opacity:o,reach:u}}function Tr(e,t){let n=xf(e,"cursor");if(n.opacity>=_$)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>xf(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function Q$(e){return of(e)??{x:0,y:0,w:e.width,h:e.height}}function $u(e,t){if(e<=0||t<=0)return io;let n=Math.min(1,io.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function sd(e,t,n,r){if(r<tn.stands){let u=e.w*n>e.h*t?{x:e.x+(e.w-e.h*t/n)/2,y:e.y,w:e.h*t/n,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*n/t};return{crop:u,at:{x:0,y:0,w:t,h:n},focus:(u.y-e.y+u.h/2)/e.h}}let i=Math.max(tn.tall*n,tn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>tn.widest*t)s=tn.widest*t,i=s*e.h/e.w;let o=tn.headroom*n,a=Math.min(1,(n-o)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*a},at:{x:t*(1-tn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function od(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function Y$(e,t){let n=new Uint32Array(256),r=Math.max(1,Math.floor(t.w*t.h/400000)),i=0;for(let o=0;o<t.w*t.h;o+=r){let a=((t.y+Math.floor(o/t.w))*e.width+t.x+o%t.w)*4;if((e.data[a+3]??0)>=128){let u=Math.round(od(e.data,a));n[u]=(n[u]??0)+1,i++}}let s=0;for(let o=0;o<256&&i>0;o++)if(s+=n[o]??0,s>=i*C$)return Math.min(j$,Math.max(1,255/Math.max(1,o)));return 1}function Z$(e,t){let n=new Uint8Array(e.width*e.height);for(let r=0;r<n.length;r++){let i=r*4;n[r]=Math.round(Math.min(255,od(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function so(e,t,n,r){let i=new Float32Array(n*r),s=Math.max(0,Math.round(t.at.x)),o=Math.max(0,Math.round(t.at.y)),a=Math.min(n,Math.round(t.at.x+t.at.w)),u=Math.min(r,Math.round(t.at.y+t.at.h));if(a>s&&u>o){let c=t.crop.w/t.at.w,l=t.crop.h/t.at.h,h={x:t.crop.x+(s-t.at.x)*c,y:t.crop.y+(o-t.at.y)*l,w:(a-s)*c,h:(u-o)*l},f=cf(e,h,a-s,u-o);for(let d=o;d<u;d++)i.set(f.data.subarray((d-o)*(a-s),(d-o+1)*(a-s)),d*n+s)}return{width:n,height:r,data:i}}function ad(e){let t=Q$(e);return{box:t,clear:Bt(e,t),ink:Z$(e,Y$(e,t))}}function ud(e,t,n,r){let{box:i,clear:s,ink:o}=ad(e),a=sd(i,t,n,s),u=Math.min(1,U$/Math.max(i.w,i.h)),c={x:0,y:0,w:Math.round(i.w*u),h:Math.round(i.h*u)},l=so(o,{crop:i,at:c,focus:a.focus},c.w,c.h),h=so(o,a,t,n);return{figure:ki(Js(l,r*c.w*a.crop.w/(i.w*a.at.w))),fill:ki(Js(h,r)),focus:a.focus}}function z$(e,t,n,r){let i=qe(t),s=qe(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function cd(e,t,n,r,i,s){let{box:o,clear:a,ink:u}=ad(e),c=so(u,sd(o,r,i,a),r,i);return z$(ki(Js(c,s)),t.background,n.color,n.opacity)}function je(e){return V(e,"ttheme","backgrounds")}function mu(e){return V(e,K$)}function Bn(e){try{return oo(e,"utf8")}catch{return}}function In(e){try{return L$(e)}catch{return[]}}function nt(e){let t=Bn(mu(e));if(t===void 0)return X$(e);let n=JSON.parse(t);if(n.version!==du)throw Error(`${mu(e)} is version ${n.version} — this ttheme reads version ${du}`);return n}function V$(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${t.pictures.length}`,`background-image = ${V(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(`
312
- `)}function xn(e,t,n){be(mu(e),`${JSON.stringify(t,null,2)}
313
- `);for(let r of n){let i=t.palettes[r],s=V(e,`${en(r)}.conf`);if(i)be(s,V$(e,i));else Pr(s,{force:!0})}}function ld(e,t){return In(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function ku(e,t){for(let n of ld(e,t))Pr(V(e,n),{force:!0})}function hd(e,t){ku(e,t.stem);for(let n of[t.original,t.cut])if(n)Pr(V(e,n),{force:!0})}function Df(e,t,n,r){let i=id(/^background-image\s*=\s*(.*?)\s*$/m.exec(t??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let s=i.slice(0,i.indexOf("@")),o=r??/^# image (\S+)$/m.exec(t??"")?.[1]??`picture_${s.slice(e.length+1)}`,a=/^# from (.+)$/m.exec(t??"")?.[1],u=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(t??"")?.[1]??1),c=n.find((l)=>l.startsWith(`${e}-${o}.`));return{key:o,stem:s,fill:i,opacity:Number.isFinite(u)?u:1,...a?{from:a}:{},...c?{original:V(ao,c)}:{}}}function ed(e,t){if(bu(e))rd(e,t)}function X$(e){let t={version:du,palettes:{}};if(!bu(e))return t;let n=In(V(e,ao)),r=In(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=V(e,J$);for(let s of new Set([...r,...In(i)])){let o=[],a=Df(s,Bn(V(e,`${s}.conf`)),n);if(a)ed(V(e,`${s}.tune.conf`),V(e,`${a.stem}.tune.conf`)),ed(V(e,`${s}.off.conf`),V(e,`${a.stem}.off.conf`)),o.push(a);for(let u of In(V(i,s))){let c=V(i,s,u),l=Df(s,Bn(V(c,".conf")),n,u);if(!l)continue;for(let h of In(c)){let f=h===".tune.conf"||h===".off.conf"?`${l.stem}${h}`:`${s}${h}`;if(h!==".conf")rd(V(c,h),V(e,f))}Pr(c,{recursive:!0}),o.push(l)}if(In(V(i,s)).length===0)Pr(V(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(In(i).length===0)Pr(i,{recursive:!0,force:!0});return xn(e,t,Object.keys(t.palettes)),t}function td(e,t,n){return t.startsWith("~/")?V(n,t.slice(2)):G$(t)?t:V(e,t)}function fd(e,t,n){let r=new Map,i=(a,u)=>{let c=Bn(a);if(c===void 0)return!1;for(let l of c.split(`
314
- `)){let h=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(h?.[1]==="config-file"&&u<4)i(td(e,h[2].replace(/^\?/,""),n),u+1);else if(h&&/^background-image(?:-fit|-opacity)?$/.test(h[1]))r.set(h[1],h[2])}return!0};if(!i(V(e,`${en(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:td(e,s,n),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function Dn(e){return`${e.site}_${e.id}`}function dd(e,t,n){let r=je(e),i=nt(r),s=i.palettes[t];if(!s||s.pictures.length<2)throw Error(`${t} has no other image`);let o=s.pictures.length,a=(s.pictures.findIndex((u)=>u.key===s.active)+n+o)%o;return s.active=s.pictures[a].key,xn(r,i,[t]),{key:s.active,at:a+1,of:o}}function gd(e,t){let n=je(e),r=nt(n),i=r.palettes[t];if(!i)throw Error(`${t} has no image`);let s=i.pictures.findIndex((u)=>u.key===i.active),[o]=i.pictures.splice(s,1);hd(n,o);let a=i.pictures[s%Math.max(i.pictures.length,1)];if(a)i.active=a.key;else delete r.palettes[t];return xn(n,r,[t]),{key:o.key,left:i.pictures.length}}function md(e,t,n,r){let i=Ei(n.figure,r),s=Ei(n.fill,r),o=`${en(e)}.${nd("sha1").update(t).update(i).update(s).digest("hex").slice(0,8)}`,a=`${o}@fill-${Math.round(n.focus*100)}.png`;return{stem:o,fill:a,files:[[`${o}.png`,i],[a,s]]}}function pu(e,t){return V(ao,`${en(e)}-${t}`)}function yu(e,t){return t.map(([n,r])=>{let i=V(e,n);return be(i,r),i})}function uo(e,t,n,r,i,s,o){let a=je(e),u=t.name,c=Dn(i),l=nt(a),h=l.palettes[u]??{active:c,pictures:[]},f=$u(s.width,s.height),d=md(u,c,ud(r,f.width,f.height,o),n.color),g=pu(u,c),m={key:c,stem:d.stem,fill:d.fill,opacity:n.opacity,tone:n.color,blur:o,window:f,...i.from?{from:i.from}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},$=h.pictures.find((M)=>M.key===c);if($)hd(a,$);H$(V(a,ao),{recursive:!0});let w=yu(a,[...d.files,[m.original,i.bytes],...m.cut?[[m.cut,Xa(yi(r))]]:[]]);return h.pictures=$?h.pictures.map((M)=>M===$?m:M):[...h.pictures,m],h.active=c,l.palettes[u]=h,xn(a,l,[u]),[...w,V(a,`${en(u)}.conf`)]}function pd(e,t,n){let r=je(e),i=nt(r),s=i.palettes[t];if(s?.pictures.some((o)=>o.key===n)&&s.active!==n)s.active=n,xn(r,i,[t])}function Eu(e,t){let n=nt(je(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var wu="top-right";function B$(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),h=n*t>=r*e!==!o,f=h?u(i*n/100):u(i*r*e/(100*t)),d=h?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-f)/2),m=u(l*(r-d)/2);if(a>=0){if(f>n)g=u((n-f)/2);if(d>r)m=Math.max(r-d,Math.min(0,u(r/2)-u(a*d/100)))}return{x:g,y:m,w:f,h:d}}function vu(e,t){let n=Bn(V(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=id(r("background-image")),s=/@(\d+)-/.exec(i)?.[1],o=/@fill-\d+\.png$/.test(i)?"fill":s?Number(s):r("background-image-fit")==="cover"?"fill":100,a=r("background-image-position").replace("center-center","center")||"center",u=Number(r("background-image-opacity")||1);return{...o!=="fill"?{size:o}:{},...a!==wu?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Mu(e,t,n,r,i){let s=n.size??"fill",o=n.position??wu,a=n.opacity??t.opacity;if(s==="fill"&&o===wu&&a===t.opacity)return;let u=Vn.indexOf(o)+1,c=V(e,`${t.stem}.png`),l=V(e,t.fill),h=!0,f=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!f)l=c,h=!1;else if(typeof s==="number"){if(!t.tone)throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=yi(Kn(new Uint8Array(oo(c)))),{width:m,height:$}=f?io:g,w=f?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,M=B$(g.width,g.height,m,$,s,u,!1,w);l=V(e,`${t.stem}@${s}-${o}${f?`-${m}x${$}`:""}.png`);let y={x:0,y:0,w:g.width,h:g.height};be(l,Ei(ki(so(g,{crop:y,at:M,focus:w},m,$)),t.tone)),h=f}let d=V(e,`${t.stem}.tune.conf`);return be(d,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${h?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
- `)),d}function wd(e){let t=new Map;for(let[n,r]of Object.entries(nt(je(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function x$(e){try{let t=yn(new Uint8Array(oo(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function co(e,t,n,r,i,s,o,a,u){let c=je(e),l=n.window??x$(V(c,n.fill))??io,h=md(t,n.key,ud(r,l.width,l.height,s),i.color),f={...n,stem:h.stem,fill:h.fill,opacity:i.opacity,tone:i.color,blur:s,window:l,...u?{cut:`${pu(t,n.key)}.cut.png`}:{}};if(u)be(V(c,`${pu(t,n.key)}.cut.png`),Xa(yi(r)));if(h.stem===n.stem)return f;yu(c,h.files),Mu(c,f,vu(c,n),o,a);let d=V(c,`${n.stem}.off.conf`);if(bu(d))A$(d,V(c,`${f.stem}.off.conf`));return f}function bd(e,t){let n=je(e),r=nt(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((h)=>h.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;xn(n,r,[...i]);for(let o of s)ku(n,o)}function D$(e,t,n,r){let i=(u)=>u.replace(/^background-image-opacity = (\S+)$/m,(c,l)=>Number(l)===n.opacity?`background-image-opacity = ${r.opacity}`:c);if(n.tone===r.color){let u=V(e,`${n.stem}.tune.conf`),c=Bn(u);if(c!==void 0)be(u,i(c));return{...n,opacity:r.opacity}}let s=ld(e,n.stem).filter((u)=>u.endsWith(".png")).map((u)=>{let c=new Uint8Array(oo(V(e,u)));return[u,ff(c,r.color)??Ei(yi(Kn(c)),r.color)]}),o=(u)=>s.find(([c])=>c===u)?.[1]??new Uint8Array,a=`${en(t)}.${nd("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;yu(e,s.map(([u,c])=>[a+u.slice(n.stem.length),c]));for(let u of["tune","off"]){let c=Bn(V(e,`${n.stem}.${u}.conf`));if(c!==void 0)be(V(e,`${a}.${u}.conf`),i(c.split(n.stem).join(a)))}return{...n,stem:a,fill:a+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function $d(e,t){let n=je(e),r=nt(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o),c=a.pictures.filter((l)=>u&&l.tone&&(l.tone!==u.color||l.opacity!==u.opacity));if(!u||c.length===0)continue;a.pictures=a.pictures.map((l)=>{if(!c.includes(l))return l;let h=D$(n,o,l,u);if(h.stem!==l.stem)s.push(l.stem);return h}),i.push(o)}if(i.length>0){xn(n,r,i);for(let o of s)ku(n,o)}return i}function Rt(e){let{slot:t,color:n,opacity:r}=Tr({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:yr(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function kt(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}:{}}}var ek=6,tk=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function lo(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...tk]){let o=t(s);if(i.length===ek||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function De(e){return e.filter((t)=>t.default!==!0)}function Hi(){return{version:Ve.version,gate:Lt,placement:tn,palettes:[]}}function nk(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Hi(),palettes:e.map(Rt)}}var Su={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(nk(e),null,2)}
316
- `}]}};import{existsSync as ck,readdirSync as lk,readFileSync as hk}from"node:fs";import{basename as fk,join as fo}from"node:path";import{existsSync as rk,readFileSync as kd}from"node:fs";import{homedir as yd}from"node:os";import{isAbsolute as Ed,join as er,resolve as ik}from"node:path";var Z="official",Wt="ttheme-market.json",Ar="ttheme-market",sk=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,ok=/^[\w.-]{1,100}$/,ak=/^\w[\w.+/-]{0,199}$/;function Rn(e){return er(e,"ttheme","installed.json")}function Ze(e){return e??[Z]}function Hr(e){try{let{markets:t}=JSON.parse(kd(Rn(e),"utf8"));return Ze(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[Z]}}function Ae(e){return Ed(e)}function lt(e){return e!==Z&&!Ae(e)}function Nn(e){let t=e.indexOf("#");return lt(e)&&t>=0?e.slice(0,t):e}function Iu(e){let t=e.indexOf("#");return lt(e)&&t>=0?e.slice(t+1):void 0}function Lr(e,t){return Nn(e)===Nn(t)}function On(e,t){return!Ae(e)&&(t?.[e]??e===Z)}function uk(e){return!ak.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function Fn(e,t=process.cwd()){if(e===Z)return Z;if(e==="~"||e.startsWith("~/"))return er(yd(),e.slice(1));if(e.startsWith(".")||Ed(e))return ik(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!sk.test(s)||!o||!ok.test(o)||a.length>0||i.length>0||r!==void 0&&uk(r))throw Error(`${e} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${s.toLowerCase()}/${o}${r===void 0?"":`#${r}`}`}function vd(e){let t=Iu(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Nn(e)}/${t}/${Wt}`}function Md(e){return e.slice(0,e.indexOf("/"))}function Nu(e){return er(e,"ttheme","markets")}function Ot(e,t){return er(Nu(e),`${Nn(t).replace("/","--")}.json`)}function ho(e){return er(e,"ttheme","market")}function Ru(e,t){return er(ho(e),t)}function Ou(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return jt(`${e}@${t}/x`)}function ht({owner:e,name:t}){return`${e}@${t}`}function Jt(e){let t=er(e,Wt);if(!rk(t))throw Error(`${e} has no ${Wt} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(kd(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Ou(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function Se(e){if(e===Z)return"the ttheme catalog";if(!Ae(e))return`github.com/${e}`;let t=yd();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var nn="tt1:",Sd=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function tr(e,t=!0){return Hr(e).filter(Ae).flatMap((n)=>{try{let r=Jt(n);return[{dir:n,...r,id:ht(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
- `);return[]}})}function rn(e){return fo(e,"palettes")}function Fu(e,t){let n=Me(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=tr(e,!1).find((i)=>i.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);return fo(rn(r.dir),`${ro(t)}.toml`)}function dk(e,t){let n=new Map;for(let i of t)if(i.group!==Ti&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!Me(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function Ft(e,t,n){let r=ro(e),{native:i,...s}=fu(`${r}.toml`,t,dk(r,n)),o=Me(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function Pn(e,t,n,r=!0){let i=rn(e);return(ck(i)?lk(i).sort():[]).filter((s)=>s.endsWith(".toml")).flatMap((s)=>{try{let o=hk(fo(i,s),"utf8");return[Rt(Ft(`${t}/${fk(s,".toml")}`,o,n))]}catch(o){if(r)process.stderr.write(`ttheme: skipping ${fo(i,s)} — ${o.message}
318
- `);return[]}})}function go(e,t,n=!0){return tr(e,n).flatMap(({dir:r,id:i})=>Pn(r,i,t,n))}function Pu(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==Ti?{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:n??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var We=(e)=>JSON.stringify(e);function Tu(e){let t=["[meta]",`name = ${We(ro(e.name))}`,...e.base?[`base = ${We(e.base)}`]:[],...e.group?[`group = ${We(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${We(e.ansiSource)}`]:[],...e.booru?[`booru = ${We(e.booru)}`]:[],`signature = [${e.signature.map(We).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(We).join(", ")}]`)]:[],"","[colors]",`background = ${We(e.background)}`,`foreground = ${We(e.foreground)}`,`cursor = ${We(e.cursor)}`,`selection_background = ${We(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${We(n)},`),"",...e.ansi.slice(8).map((n)=>` ${We(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(We).join(", ")}]`,`reason = ${We(e.reason??"")}`);for(let n of e.pictures??[]){if(t.push("","[[picture]]",`site = ${We(n.site)}`,`id = ${n.id}`),n.size!==void 0)t.push(`size = ${typeof n.size==="number"?n.size:We(n.size)}`);if(n.position!==void 0)t.push(`position = ${We(n.position)}`);if(n.opacity!==void 0)t.push(`opacity = ${n.opacity}`)}return`${t.join(`
310
+ */import{readdirSync as J0,rmSync as K0,statSync as q0}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Q0}from"node:net";import{homedir as Y0}from"node:os";import{join as Ii}from"node:path";import{setTimeout as Z0}from"node:timers/promises";var yn=100,$t=25000000,z0=536870912,Ni=["safe","questionable","explicit"],qn=["nudity","underwear"],ou=["comic","monochrome","sketch","chibi"],Rf=["off","5","10","25","50","100"],Ff=["off","720","1080","1440","1800","2560"],Of={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},V0={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},X0=/^(?:rating|score|width|height|filetype|dimension):/,Si={safe:"s",questionable:"q",explicit:"e"},Pf=8191,B0=20000,x0=5000,Ef=3000,vf=8,D0=3000,Tf=60000,Mf=3,e$=3,t$="https://static.zerochan.net",Af="https://s1.zerochan.net",au=`ttheme/${Ve.version} (+${Ve.homepage})`,n$=["orig","tile","thumb","cut"],Hf=new Map,r$=w$(process.env.TTHEME_FIND_HOSTS),i$=p$(process.env.TTHEME_FIND_CUTOUTS);Q0(D0);function Sf(e){try{return J0(e)}catch{return[]}}function Nr(e){return e.startsWith("//")?`https:${e}`:e}function vn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function Ri(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function s$(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function su(e,t,n){let r=Nr(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:vn(r)}}function Lf(e,t){let n=Nr(String(t.preview??""));if(!t.file||!n||!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:t.file,preview:n,ext:t.ext,owner:String(t.owner??""),artist:t.artist,score:Number(e.score)||0,rating:String(e.rating??""),md5:String(t.md5??""),source:String(e.source??""),tags:t.tags.split(/\s+/).filter(Boolean),solo:t.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:t.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<r*i)}]}function o$(e){let t=s$(e);return Ri(e).flatMap((n)=>{let r=Nr(String(n.file_url??"")),i=String(n.tags??"");return Lf(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||vn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((s)=>t.get(s)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[su(n.jpeg_url,n.jpeg_width,n.jpeg_height),su(n.sample_url,n.sample_width,n.sample_height)]})})}function a$(e){return Ri(e).flatMap((t)=>{let n=Nr(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return Lf(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||vn(n)).toLowerCase(),owner:"",artist:String(t.tag_string_artist??"").split(/\s+/)[0]??"",md5:t.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>su(s.url,s.width,s.height)).filter((s)=>s.ext==="jpg"||s.ext==="png").sort((s,o)=>o.width*o.height-s.width*s.height)})})}function u$(e){return(Array.isArray(e)?e:[]).map((t)=>String(t).toLowerCase().replace(/\s+/g,"_"))}function c$(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function l$(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=u$(i.tags),a=Nr(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:vn(a),preview:`${Af}/${c$(i.tag??i.primary)}.600.${s}.jpg`,owner:"",artist:"",score:0,rating:o.some((u)=>Of.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,solo:o.includes("solo"),family:0,smaller:[]}]})}function h$(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function f$(e){return Ri(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function d$(e){return Ri(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function g$(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function m$(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function p$(e){let t=new Map;for(let n of(e??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)t.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return t}function w$(e){let t=new Map;for(let n of(e??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let s=new URL(n.slice(r+1));if(i&&s.protocol==="https:")t.set(i,s.origin)}catch{}}return t}function Ds(e,t,n,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let s=t.filter((o)=>i.includes(o));return s.length>0?s:[...n]}function Yn(e){return Ds(e,Ni,["safe"])}function Rr(e){return Ds(e,qn,qn,"none")}function eo(e){return Ds(e,ou,[],"none")}function Fi(e){let t=ee.map((n)=>n.name);return Ds(e,t,t)}function uu(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function Oi(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function cu(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function lu(e){let t=r$.get(e.key),n=i$.get(e.key);return{...e,origin:t??e.origin,moved:t!==void 0&&t!==e.origin,cutouts:n??e.cutouts,vouched:e.vouched&&n===void 0}}function Gf(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function Uf(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function If(e){let t=lu(e),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...t,scored:!0,narrow:({score:r,size:i})=>[...r>0?[`score:>=${r}`]:[],...Uf(i)],cutouts:Gf(t.cutouts),ratings:cu([Si.safe],[Si.questionable],[Si.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Si[i]}`;let s=Ni.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${Si[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(yn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${t.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/post/show/${r}`,parse:o$,count:g$}}function b$(e){let t=lu(e),n=cu(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...Uf(i),...s?["filetype:png"]:[]],cutouts:Gf(t.cutouts),ratings:n,rate:(r)=>r.length===Ni.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(yn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${t.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/posts/${r}`,parse:a$,count:m$}}function iu(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function Nf(e){let t=e.split(/\s+/),n=t.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:t.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function $$(e){let t=lu(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:cu(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${iu(n)}?${new URLSearchParams({json:"",l:String(yn),p:String(r+1),...Nf(n)})}`,countUrl:(n)=>`${t.origin}/${iu(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:l$,count:h$,counts:(n)=>iu(n).split(",").length===1&&!("d"in Nf(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Af,t$).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function k$(e){let t=xs(`https://${e}`);return ee.find((n)=>xs(n.origin)===t)}function hu(e){return e.split(/\s+/).filter((t)=>t&&!X0.test(t)).length}function to(e,t){let n=e.trim();if(/^\d+$/.test(n))return{site:t,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=ee.find((u)=>u.key===r[1]||u.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let s=k$(i.host),o=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return s&&o>0?{site:s,id:o}:void 0}var ee=[b$({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),If({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),If({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),$$({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ut=ee.find((e)=>e.key==="danbooru"),xt=134217728;function _t(e,t){let n=ee.indexOf(e);return(n===-1?ee.length:n)*xt+t}function xs(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function no(e,t,n=t){return t.mirror&&n===t?{site:Ut,url:t.mirror.file}:{site:e,url:n.file}}function ro(e,t){return t.mirror?{site:Ut,url:t.mirror.preview}:{site:e,url:t.preview}}function io(e,t=qn){return e.tags.filter((n)=>t.some((r)=>Of[r].has(n)))}function _f(e,t){return e.tags.filter((n)=>t.some((r)=>V0[r].has(n)))}function so(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function Dt(e){return[e,...e.smaller].find((t)=>t.width*t.height<=$t)}function Cf(e){let t=new Map;for(let[n,r]of[...e].sort(([i],[s])=>i<s?-1:1)){if(r==="")continue;t.set(r,[...t.get(r)??[],n])}return t}function Fr(){return Ii(process.env.XDG_CACHE_HOME??Ii(Y0(),".cache"),"ttheme")}function Nt(e){return Ii(Fr(),e.key)}function jf(e=z0,t=Fr()){let n=[],r=0;for(let i of Sf(t))for(let s of n$){let o=Ii(t,i,s);for(let a of Sf(o)){let u=Ii(o,a);try{let{size:c,mtimeMs:l}=q0(u);n.push({path:u,size:c,at:l}),r+=c}catch{}}}n.sort((i,s)=>i.at-s.at);for(let i of n){if(r<=e)return;try{K0(i.path,{force:!0}),r-=i.size}catch{}}}function y$(e,t){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let n=e===null?Number.NaN:Date.parse(e);return Number.isNaN(n)?Tf:Math.max(0,n-t)}function En(e){return Hf.get(e.key)??0}function E$(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function v$(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function M$(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Qn(e,t,n,r={},i=B0){let s=t;for(let o=1,a=0;;o++){let u=En(e)-Date.now();if(u>0)await Z0(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":au,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(h){if(o<Mf&&!n.aborted&&E$(h))continue;throw h}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<e$){await c.body?.cancel(),s=M$(s,l),a++,o--;continue}if(c.status===429&&o<Mf){await c.body?.cancel();let h=y$(c.headers.get("retry-after"),Date.now());if(h>Tf)throw Error(`${e.name} asks to wait ${Math.ceil(h/1000)}s`);Hf.set(e.key,Math.max(En(e),Date.now()+h));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(v$(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function fu(e,t,n){try{return await(await Qn(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function Wf(e,t,n,r){return e.parse(await fu(e,e.postsUrl(t,n),r))}async function du(e,t,n){return e.count(await fu(e,e.countUrl(t),n))}async function Pi(e,t,n){let[r]=e.parse(await fu(e,e.postUrl(t),n));return r}function S$(e){let t=new URLSearchParams({limit:String(2*yn),only:"md5,tag_string,file_url",tags:`md5:${e.join(",")}`});return`${Ut.origin}/posts.json?${t}`}function I$(e){return new Map(Ri(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:String(t.tag_string??"").split(/\s+/).filter(Boolean),file:Nr(String(t.file_url??""))}]]:[]}))}function Jf(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=vn(r.file)}}}async function Kf(e,t){let n=new Map;if(En(Ut)>Date.now())return n;for(let r=0;r<e.length;r+=yn){let i=await(await Qn(Ut,S$(e.slice(r,r+yn)),t,{},x0)).text();for(let[s,o]of I$(i))n.set(s,o)}return n}async function oo(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Qn(e,r,n,{Range:`bytes=0-${Pf}`}),s=$n(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=vn(r),s}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${e.name} keeps no png or jpg of ${t.id}`)}async function qf(e,t){if(En(Ut)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(vf)}),s=`${Ut.origin}/autocomplete.json?${i}`;return f$(await(await Qn(Ut,s,t,{},Ef)).text())}catch(i){if(t.aborted)throw i}let n=ee.find((i)=>i.key==="yande"),r=new URLSearchParams({name:e,order:"count",limit:String(vf)});return d$(await(await Qn(n,`${n.origin}/tag.json?${r}`,t,{},Ef)).text())}async function Qf(e,t,n){let r=await Qn(e,t,n,{Range:`bytes=0-${Pf}`});return $n(new Uint8Array(await r.arrayBuffer()))}async function ao(e,t,n,r){let i=await Qn(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:h,value:f}=await o.read();if(h)break;a.push(f),u+=f.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let h of a)c.set(h,l),l+=h.length;return c}var zn=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Ti="Original",F$=1e6,Ct="_groups.toml",Yf=3,Zf=8,gu="[a-z0-9]+(?:-[a-z0-9]+)*",O$=new RegExp(`^(?:(${gu})@(${gu})/)?(${gu})$`),Bf=["background","foreground","cursor","selection"];function de(e,t){throw Error(`${e}: ${t}`)}function Zn(e,t,n){if(typeof n!=="string"||!br(n))de(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Ai(e,t,n){if(typeof n!=="string"||n.length===0)de(e,`${t} must be a non-empty string`);return n}function en(e){return e.replace("@","--").replace("/","--")}function $e(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function Pr(e){return e.slice(e.indexOf("/")+1)}function jt(e){let t=O$.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function Hi(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 uo(e,t,n){let r=Ai(e,t,n),i=Hi(r);if(i)de(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function zf(e,t,n){let r=Ai(e,t,n),i=jt(r);if(i)de(e,`${t} "${r}" ${i}`);return r}function Or(e){return e&&typeof e==="object"?e:{}}function P$(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)de(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Zn(e,`ghostty.icon_screen[${s}]`,i))}function T$(e,t,n){let r=Or(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Zn(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:P$(e,r.icon_screen,n)}}function A$(e){return new Map([...Bf.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function H$(e,t,n){if(!Array.isArray(t)||t.length!==Yf)de(e,`meta.signature must name exactly ${Yf} palette slots`);let r=A$(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Ai(e,u,a),l=r.get(c);if(l===void 0)de(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${Bf.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)de(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function L$(e,t,n){if(t===void 0)return;if(!n)de(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))de(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=ee.find((u)=>u.key===i);if(!o)de(e,`meta.booru_sites.${i} is not a find site — use ${ee.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))de(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))de(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function G$(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>Zf)de(e,`[[picture]] holds 1 to ${Zf} pictures`);return t.map((n,r)=>{let i=Or(n),s=`picture[${r}]`,o=ee.find((l)=>l.key===i.site);if(!o)de(e,`${s}.site must be one of ${ee.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)de(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))de(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!zn.includes(u))de(e,`${s}.position must be one of ${zn.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))de(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function xf(e,t){try{return ru(t)}catch(n){de(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
+ `)[0]}`)}}function U$(e){let n=xf(Ct,Vf(Xf(e,Ct),"utf8")).group;if(!Array.isArray(n)||n.length===0)de(Ct,"needs at least one [[group]] table");return n.map((r)=>{let i=Or(r);return{name:uo(Ct,"group.name",i.name),native:i.native===void 0?void 0:uo(Ct,"group.native",i.native),lead:Ai(Ct,"group.lead",i.lead)}})}function mu(e,t,n){let r=xf(e,t),i=Or(r.meta),s=Or(r.colors),o=Or(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)de(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=zf(e,"meta.name",i.name);if(u!==n.name)de(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let F of["order","role"])if(c&&i[F]!==void 0)de(e,`meta.${F} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")de(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let h=i.base===void 0?void 0:zf(e,"meta.base",i.base);if(h!==void 0&&!c)de(e,"meta.base is for market palettes");let f=h===void 0?void 0:n.bases?.get(h),d=c&&i.group===void 0?f?.group??Ti:uo(e,"meta.group",i.group),g=n.groups.get(d);if(!g&&!(c&&(d===Ti||n.open)))de(e,`meta.group "${d}" has no [[group]] table in ${Ct}`);let m=Zn(e,"colors.background",s.background),$=Zn(e,"colors.foreground",s.foreground),p=Zn(e,"colors.cursor",s.cursor),E=Zn(e,"colors.selection_background",s.selection_background),y=a.map((F,L)=>Zn(e,`colors.ansi[${L}]`,F)),S=H$(e,i.signature,{background:m,foreground:$,cursor:p,selection:E,ansi:y}),w=i.booru===void 0?void 0:Ai(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))de(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let N=L$(e,i.booru_sites,w),v=Array.isArray(o.waive)?o.waive.map(String):[];if(v.length>0&&typeof o.reason!=="string")de(e,"contrast.waive needs a contrast.reason explaining why");let O=G$(e,r.picture);return{name:u,...h?{base:h}:{},group:d,native:g?.native,lead:!c&&g?.lead===u,order:c?f?.order??F$:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?h??"original":uo(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...N?{booruSites:N}:{},background:m,foreground:$,cursor:p,selectionBackground:E,ansi:y,signature:S.colors,signatureSlots:S.names,ghostty:T$(e,r.ghostty,{background:m,cursor:p,selectionBackground:E}),waive:v,waiveReason:typeof o.reason==="string"?o.reason:void 0,...O?{pictures:O}:{}}}function Df(e){let t=U$(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)de(Ct,"group.name must be unique");let r=N$(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>mu(s,Vf(Xf(e,s),"utf8"),{name:R$(s,".toml"),groups:n})).sort((s,o)=>s.order-o.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 t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)de(Ct,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))de(Ct,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function ed(e){return e.filter((t)=>t.role===void 0)}function Vn(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>$e(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number($e(r.name)!==void 0)-Number($e(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||t((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var co={width:2560,height:1550},J$=2560,K$=0.1,q$=0.99,Q$=2,tn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Y$=tt(wu("#19161e","#9b86c8",0.2)),Z$="shelf",fo="originals",z$="images.json",pu=1;function wu(e,t,n){let r=qe(e),i=qe(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function V$(e,t){if(t==="background"||t==="foreground"||t==="cursor")return e[t];if(t==="selection"&&e.selection)return e.selection;let n=/^ansi(\d|1[0-5])$/.exec(t),r=n?e.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${t}`);return r}function td(e){if(e(1))return 1;let t=0,n=1;for(let r=0;r<40;r++){let i=(t+n)/2;if(e(i))t=i;else n=i}return t}function nd(e,t){let n=V$(e,t),i=td((c)=>th({name:e.name,background:wu(e.background,n,c),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),s=td((c)=>tt(wu(e.background,n,c))<=Y$),o=Math.floor(Math.min(i,s)*1000)/1000,a=qe(e.background),u=Math.hypot(...qe(n).map((c,l)=>(c-(a[l]??0))*o));return{slot:t,color:n,cap:i,matched:s,opacity:o,reach:u}}function Ar(e,t){let n=nd(e,"cursor");if(n.opacity>=K$)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>nd(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function X$(e){return lf(e)??{x:0,y:0,w:e.width,h:e.height}}function Eu(e,t){if(e<=0||t<=0)return co;let n=Math.min(1,co.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function cd(e,t,n,r){if(r<tn.stands){let u=e.w*n>e.h*t?{x:e.x+(e.w-e.h*t/n)/2,y:e.y,w:e.h*t/n,h:e.h}:{x:e.x,y:e.y,w:e.w,h:e.w*n/t};return{crop:u,at:{x:0,y:0,w:t,h:n},focus:(u.y-e.y+u.h/2)/e.h}}let i=Math.max(tn.tall*n,tn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>tn.widest*t)s=tn.widest*t,i=s*e.h/e.w;let o=tn.headroom*n,a=Math.min(1,(n-o)/i);return{crop:{x:e.x,y:e.y,w:e.w,h:e.h*a},at:{x:t*(1-tn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function ld(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function B$(e,t){let n=new Uint32Array(256),r=Math.max(1,Math.floor(t.w*t.h/400000)),i=0;for(let o=0;o<t.w*t.h;o+=r){let a=((t.y+Math.floor(o/t.w))*e.width+t.x+o%t.w)*4;if((e.data[a+3]??0)>=128){let u=Math.round(ld(e.data,a));n[u]=(n[u]??0)+1,i++}}let s=0;for(let o=0;o<256&&i>0;o++)if(s+=n[o]??0,s>=i*q$)return Math.min(Q$,Math.max(1,255/Math.max(1,o)));return 1}function x$(e,t){let n=new Uint8Array(e.width*e.height);for(let r=0;r<n.length;r++){let i=r*4;n[r]=Math.round(Math.min(255,ld(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function lo(e,t,n,r){let i=new Float32Array(n*r),s=Math.max(0,Math.round(t.at.x)),o=Math.max(0,Math.round(t.at.y)),a=Math.min(n,Math.round(t.at.x+t.at.w)),u=Math.min(r,Math.round(t.at.y+t.at.h));if(a>s&&u>o){let c=t.crop.w/t.at.w,l=t.crop.h/t.at.h,h={x:t.crop.x+(s-t.at.x)*c,y:t.crop.y+(o-t.at.y)*l,w:(a-s)*c,h:(u-o)*l},f=df(e,h,a-s,u-o);for(let d=o;d<u;d++)i.set(f.data.subarray((d-o)*(a-s),(d-o+1)*(a-s)),d*n+s)}return{width:n,height:r,data:i}}function hd(e){let t=X$(e);return{box:t,clear:Bt(e,t),ink:x$(e,B$(e,t))}}function fd(e,t,n,r){let{box:i,clear:s,ink:o}=hd(e),a=cd(i,t,n,s),u=Math.min(1,J$/Math.max(i.w,i.h)),c={x:0,y:0,w:Math.round(i.w*u),h:Math.round(i.h*u)},l=lo(o,{crop:i,at:c,focus:a.focus},c.w,c.h),h=lo(o,a,t,n);return{figure:ki(zs(l,r*c.w*a.crop.w/(i.w*a.at.w))),fill:ki(zs(h,r)),focus:a.focus}}function D$(e,t,n,r){let i=qe(t),s=qe(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function dd(e,t,n,r,i,s){let{box:o,clear:a,ink:u}=hd(e),c=lo(u,cd(o,r,i,a),r,i);return D$(ki(zs(c,s)),t.background,n.color,n.opacity)}function je(e){return V(e,"ttheme","backgrounds")}function bu(e){return V(e,z$)}function Xn(e){try{return ho(e,"utf8")}catch{return}}function Mn(e){try{return j$(e)}catch{return[]}}function rt(e){let t=Xn(bu(e));if(t===void 0)return tk(e);let n=JSON.parse(t);if(n.version!==pu)throw Error(`${bu(e)} is version ${n.version} — this ttheme reads version ${pu}`);return n}function ek(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${t.pictures.length}`,`background-image = ${V(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(`
312
+ `)}function Bn(e,t,n){be(bu(e),`${JSON.stringify(t,null,2)}
313
+ `);for(let r of n){let i=t.palettes[r],s=V(e,`${en(r)}.conf`);if(i)be(s,ek(e,i));else Tr(s,{force:!0})}}function gd(e,t){return Mn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function vu(e,t){for(let n of gd(e,t))Tr(V(e,n),{force:!0})}function md(e,t){vu(e,t.stem);for(let n of[t.original,t.cut])if(n)Tr(V(e,n),{force:!0})}function rd(e,t,n,r){let i=ud(/^background-image\s*=\s*(.*?)\s*$/m.exec(t??"")?.[1]??"");if(!i.startsWith(`${e}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(e.length)))return;let s=i.slice(0,i.indexOf("@")),o=r??/^# image (\S+)$/m.exec(t??"")?.[1]??`picture_${s.slice(e.length+1)}`,a=/^# from (.+)$/m.exec(t??"")?.[1],u=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(t??"")?.[1]??1),c=n.find((l)=>l.startsWith(`${e}-${o}.`));return{key:o,stem:s,fill:i,opacity:Number.isFinite(u)?u:1,...a?{from:a}:{},...c?{original:V(fo,c)}:{}}}function id(e,t){if(yu(e))ad(e,t)}function tk(e){let t={version:pu,palettes:{}};if(!yu(e))return t;let n=Mn(V(e,fo)),r=Mn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=V(e,Z$);for(let s of new Set([...r,...Mn(i)])){let o=[],a=rd(s,Xn(V(e,`${s}.conf`)),n);if(a)id(V(e,`${s}.tune.conf`),V(e,`${a.stem}.tune.conf`)),id(V(e,`${s}.off.conf`),V(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Mn(V(i,s))){let c=V(i,s,u),l=rd(s,Xn(V(c,".conf")),n,u);if(!l)continue;for(let h of Mn(c)){let f=h===".tune.conf"||h===".off.conf"?`${l.stem}${h}`:`${s}${h}`;if(h!==".conf")ad(V(c,h),V(e,f))}Tr(c,{recursive:!0}),o.push(l)}if(Mn(V(i,s)).length===0)Tr(V(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(Mn(i).length===0)Tr(i,{recursive:!0,force:!0});return Bn(e,t,Object.keys(t.palettes)),t}function sd(e,t,n){return t.startsWith("~/")?V(n,t.slice(2)):W$(t)?t:V(e,t)}function pd(e,t,n){let r=new Map,i=(a,u)=>{let c=Xn(a);if(c===void 0)return!1;for(let l of c.split(`
314
+ `)){let h=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(h?.[1]==="config-file"&&u<4)i(sd(e,h[2].replace(/^\?/,""),n),u+1);else if(h&&/^background-image(?:-fit|-opacity)?$/.test(h[1]))r.set(h[1],h[2])}return!0};if(!i(V(e,`${en(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:sd(e,s,n),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function xn(e){return`${e.site}_${e.id}`}function wd(e,t,n){let r=je(e),i=rt(r),s=i.palettes[t];if(!s||s.pictures.length<2)throw Error(`${t} has no other image`);let o=s.pictures.length,a=(s.pictures.findIndex((u)=>u.key===s.active)+n+o)%o;return s.active=s.pictures[a].key,Bn(r,i,[t]),{key:s.active,at:a+1,of:o}}function bd(e,t){let n=je(e),r=rt(n),i=r.palettes[t];if(!i)throw Error(`${t} has no image`);let s=i.pictures.findIndex((u)=>u.key===i.active),[o]=i.pictures.splice(s,1);md(n,o);let a=i.pictures[s%Math.max(i.pictures.length,1)];if(a)i.active=a.key;else delete r.palettes[t];return Bn(n,r,[t]),{key:o.key,left:i.pictures.length}}function $d(e,t,n,r){let i=Ei(n.figure,r),s=Ei(n.fill,r),o=`${en(e)}.${od("sha1").update(t).update(i).update(s).digest("hex").slice(0,8)}`,a=`${o}@fill-${Math.round(n.focus*100)}.png`;return{stem:o,fill:a,files:[[`${o}.png`,i],[a,s]]}}function $u(e,t){return V(fo,`${en(e)}-${t}`)}function Mu(e,t){return t.map(([n,r])=>{let i=V(e,n);return be(i,r),i})}function go(e,t,n,r,i,s,o){let a=je(e),u=t.name,c=xn(i),l=rt(a),h=l.palettes[u]??{active:c,pictures:[]},f=Eu(s.width,s.height),d=$d(u,c,fd(r,f.width,f.height,o),n.color),g=$u(u,c),m={key:c,stem:d.stem,fill:d.fill,opacity:n.opacity,tone:n.color,blur:o,window:f,...i.from?{from:i.from}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},$=h.pictures.find((E)=>E.key===c);if($)md(a,$);C$(V(a,fo),{recursive:!0});let p=Mu(a,[...d.files,[m.original,i.bytes],...m.cut?[[m.cut,eu(yi(r))]]:[]]);return h.pictures=$?h.pictures.map((E)=>E===$?m:E):[...h.pictures,m],h.active=c,l.palettes[u]=h,Bn(a,l,[u]),[...p,V(a,`${en(u)}.conf`)]}function kd(e,t,n){let r=je(e),i=rt(r),s=i.palettes[t];if(s?.pictures.some((o)=>o.key===n)&&s.active!==n)s.active=n,Bn(r,i,[t])}function Su(e,t){let n=rt(je(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var ku="top-right";function nk(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),h=n*t>=r*e!==!o,f=h?u(i*n/100):u(i*r*e/(100*t)),d=h?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-f)/2),m=u(l*(r-d)/2);if(a>=0){if(f>n)g=u((n-f)/2);if(d>r)m=Math.max(r-d,Math.min(0,u(r/2)-u(a*d/100)))}return{x:g,y:m,w:f,h:d}}function Iu(e,t){let n=Xn(V(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=ud(r("background-image")),s=/@(\d+)-/.exec(i)?.[1],o=/@fill-\d+\.png$/.test(i)?"fill":s?Number(s):r("background-image-fit")==="cover"?"fill":100,a=r("background-image-position").replace("center-center","center")||"center",u=Number(r("background-image-opacity")||1);return{...o!=="fill"?{size:o}:{},...a!==ku?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Nu(e,t,n,r,i){let s=n.size??"fill",o=n.position??ku,a=n.opacity??t.opacity;if(s==="fill"&&o===ku&&a===t.opacity)return;let u=zn.indexOf(o)+1,c=V(e,`${t.stem}.png`),l=V(e,t.fill),h=!0,f=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!f)l=c,h=!1;else if(typeof s==="number"){if(!t.tone)throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=yi(Jn(new Uint8Array(ho(c)))),{width:m,height:$}=f?co:g,p=f?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,E=nk(g.width,g.height,m,$,s,u,!1,p);l=V(e,`${t.stem}@${s}-${o}${f?`-${m}x${$}`:""}.png`);let y={x:0,y:0,w:g.width,h:g.height};be(l,Ei(ki(lo(g,{crop:y,at:E,focus:p},m,$)),t.tone)),h=f}let d=V(e,`${t.stem}.tune.conf`);return be(d,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${h?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
+ `)),d}function yd(e){let t=new Map;for(let[n,r]of Object.entries(rt(je(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function rk(e){try{let t=$n(new Uint8Array(ho(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function mo(e,t,n,r,i,s,o,a,u){let c=je(e),l=n.window??rk(V(c,n.fill))??co,h=$d(t,n.key,fd(r,l.width,l.height,s),i.color),f={...n,stem:h.stem,fill:h.fill,opacity:i.opacity,tone:i.color,blur:s,window:l,...u?{cut:`${$u(t,n.key)}.cut.png`}:{}};if(u)be(V(c,`${$u(t,n.key)}.cut.png`),eu(yi(r)));if(h.stem===n.stem)return f;Mu(c,h.files),Nu(c,f,Iu(c,n),o,a);let d=V(c,`${n.stem}.off.conf`);if(yu(d))_$(d,V(c,`${f.stem}.off.conf`));return f}function Ed(e,t){let n=je(e),r=rt(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((h)=>h.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;Bn(n,r,[...i]);for(let o of s)vu(n,o)}function ik(e,t,n,r){let i=(u)=>u.replace(/^background-image-opacity = (\S+)$/m,(c,l)=>Number(l)===n.opacity?`background-image-opacity = ${r.opacity}`:c);if(n.tone===r.color){let u=V(e,`${n.stem}.tune.conf`),c=Xn(u);if(c!==void 0)be(u,i(c));return{...n,opacity:r.opacity}}let s=gd(e,n.stem).filter((u)=>u.endsWith(".png")).map((u)=>{let c=new Uint8Array(ho(V(e,u)));return[u,pf(c,r.color)??Ei(yi(Jn(c)),r.color)]}),o=(u)=>s.find(([c])=>c===u)?.[1]??new Uint8Array,a=`${en(t)}.${od("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;Mu(e,s.map(([u,c])=>[a+u.slice(n.stem.length),c]));for(let u of["tune","off"]){let c=Xn(V(e,`${n.stem}.${u}.conf`));if(c!==void 0)be(V(e,`${a}.${u}.conf`),i(c.split(n.stem).join(a)))}return{...n,stem:a,fill:a+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function vd(e,t){let n=je(e),r=rt(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o),c=a.pictures.filter((l)=>u&&l.tone&&(l.tone!==u.color||l.opacity!==u.opacity));if(!u||c.length===0)continue;a.pictures=a.pictures.map((l)=>{if(!c.includes(l))return l;let h=ik(n,o,l,u);if(h.stem!==l.stem)s.push(l.stem);return h}),i.push(o)}if(i.length>0){Bn(n,r,i);for(let o of s)vu(n,o)}return i}function Rt(e){let{slot:t,color:n,opacity:r}=Ar({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:yr(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function kt(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}:{}}}var sk=6,ok=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function po(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...ok]){let o=t(s);if(i.length===sk||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function De(e){return e.filter((t)=>t.default!==!0)}function Li(){return{version:Ve.version,gate:Lt,placement:tn,palettes:[]}}function ak(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Li(),palettes:e.map(Rt)}}var Ru={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(ak(e),null,2)}
316
+ `}]}};import{existsSync as gk,readdirSync as Fd,readFileSync as mk}from"node:fs";import{basename as Od,join as Gi}from"node:path";import{existsSync as uk,readFileSync as Md}from"node:fs";import{homedir as Sd}from"node:os";import{isAbsolute as Id,join as Dn,resolve as ck}from"node:path";var Z="official",Wt="ttheme-market.json",Hr="ttheme-market",lk=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,hk=/^[\w.-]{1,100}$/,fk=/^\w[\w.+/-]{0,199}$/;function In(e){return Dn(e,"ttheme","installed.json")}function Ze(e){return e??[Z]}function Lr(e){try{let{markets:t}=JSON.parse(Md(In(e),"utf8"));return Ze(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[Z]}}function Ae(e){return Id(e)}function lt(e){return e!==Z&&!Ae(e)}function Sn(e){let t=e.indexOf("#");return lt(e)&&t>=0?e.slice(0,t):e}function Fu(e){let t=e.indexOf("#");return lt(e)&&t>=0?e.slice(t+1):void 0}function Gr(e,t){return Sn(e)===Sn(t)}function Nn(e,t){return!Ae(e)&&(t?.[e]??e===Z)}function dk(e){return!fk.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function Rn(e,t=process.cwd()){if(e===Z)return Z;if(e==="~"||e.startsWith("~/"))return Dn(Sd(),e.slice(1));if(e.startsWith(".")||Id(e))return ck(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!lk.test(s)||!o||!hk.test(o)||a.length>0||i.length>0||r!==void 0&&dk(r))throw Error(`${e} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${s.toLowerCase()}/${o}${r===void 0?"":`#${r}`}`}function Nd(e){let t=Fu(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Sn(e)}/${t}/${Wt}`}function Rd(e){return e.slice(0,e.indexOf("/"))}function Ou(e){return Dn(e,"ttheme","markets")}function Ft(e,t){return Dn(Ou(e),`${Sn(t).replace("/","--")}.json`)}function wo(e){return Dn(e,"ttheme","market")}function Pu(e,t){return Dn(wo(e),t)}function Tu(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return jt(`${e}@${t}/x`)}function ht({owner:e,name:t}){return`${e}@${t}`}function Jt(e){let t=Dn(e,Wt);if(!uk(t))throw Error(`${e} has no ${Wt} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Md(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Tu(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function Se(e){if(e===Z)return"the ttheme catalog";if(!Ae(e))return`github.com/${e}`;let t=Sd();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var nn="tt1:",Pd=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function er(e,t=!0){return Lr(e).filter(Ae).flatMap((n)=>{try{let r=Jt(n);return[{dir:n,...r,id:ht(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
+ `);return[]}})}function bo(e){return Gi(e,"palettes")}function Fn(e){let t=bo(e);if(!gk(t))return[];let n=[],r=[];for(let i of Fd(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of Fd(Gi(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:Gi(t,i.name,s),slug:Od(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Gi(t,i.name),slug:Od(i.name,".toml")})}return[...n,...r]}function Ui(e,t){let n=t.get(e.slug);if(n)return`${e.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=e.catalog===void 0?void 0:Hi(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function Au(e,t){let n=$e(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=er(e,!1).find((s)=>s.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=Pr(t);return Fn(r.dir).find((s)=>s.slug===i)?.path??Gi(bo(r.dir),`${i}.toml`)}function pk(e,t){let n=new Map;for(let i of t)if(i.group!==Ti&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!$e(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function Ot(e,t,n){let r=Pr(e),{native:i,...s}=mu(`${r}.toml`,t,pk(r,n)),o=$e(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function On(e,t,n,r=!0){let i=new Map;return Fn(e).flatMap((s)=>{try{let o=Ui(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Rt(Ot(`${t}/${s.slug}`,mk(s.path,"utf8"),n));return[s.catalog?{...a,catalog:s.catalog}:a]}catch(o){if(r)process.stderr.write(`ttheme: skipping ${s.path} — ${o.message}
318
+ `);return[]}})}function $o(e,t,n=!0){return er(e,n).flatMap(({dir:r,id:i})=>On(r,i,t,n))}function Hu(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==Ti?{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:n??"kept from the palette"}:{},...e.pictures?{pictures:e.pictures}:{}}}var We=(e)=>JSON.stringify(e);function Lu(e){let t=["[meta]",`name = ${We(Pr(e.name))}`,...e.base?[`base = ${We(e.base)}`]:[],...e.group?[`group = ${We(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${We(e.ansiSource)}`]:[],...e.booru?[`booru = ${We(e.booru)}`]:[],`signature = [${e.signature.map(We).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(We).join(", ")}]`)]:[],"","[colors]",`background = ${We(e.background)}`,`foreground = ${We(e.foreground)}`,`cursor = ${We(e.cursor)}`,`selection_background = ${We(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${We(n)},`),"",...e.ansi.slice(8).map((n)=>` ${We(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(We).join(", ")}]`,`reason = ${We(e.reason??"")}`);for(let n of e.pictures??[]){if(t.push("","[[picture]]",`site = ${We(n.site)}`,`id = ${n.id}`),n.size!==void 0)t.push(`size = ${typeof n.size==="number"?n.size:We(n.size)}`);if(n.position!==void 0)t.push(`position = ${We(n.position)}`);if(n.opacity!==void 0)t.push(`opacity = ${n.opacity}`)}return`${t.join(`
319
319
  `)}
320
- `}class Id{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 t=new TextEncoder().encode(e);if(t.length>255)throw Error(`"${e}" is too long to share`);this.u8(t.length),this.bytes.push(...t)}color(e){let t=Number.parseInt(e.slice(1),16);this.u8(t>>16),this.u8(t>>8),this.u8(t)}done(){return Buffer.from(this.bytes).toString("base64url")}}class Nd{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(),t=this.bytes.subarray(this.at,this.at+e);if(t.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(t)}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 Rd(e){let t=new Id;t.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])t.color(r);for(let r of e.signature)t.u8(Sd.indexOf(r));t.str(e.base),t.str(e.group),t.str(e.ansiSource),t.str(e.booru),t.u16((e.waive??[]).reduce((r,i)=>r|1<<Fa.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(ee.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:Vn.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${nn}${t.done()}`}function Od(e){if(!e.startsWith(nn))throw Error(`a share code starts with ${nn}`);let t=e.slice(nn.length);if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error("the share code holds characters it never uses — was it copied whole?");let n=new Nd(new Uint8Array(Buffer.from(t,"base64url"))),r=n.str(),[i,s,o,a,...u]=Array.from({length:20},()=>n.color()),c=[n.u8(),n.u8(),n.u8()].map((M)=>Sd[M]??`slot${M}`),l=n.str(),h=n.str(),f=n.str(),d=n.str(),g=n.u16(),m=n.str(),$=Fa.filter((M,y)=>g&1<<y),w=Array.from({length:n.u8()},()=>{let M=ee[n.u8()]?.key??"unknown",y=n.u32(),S=n.u16(),p=n.u8(),N=n.u16();return{site:M,id:y,...S===1?{size:"fill"}:S>1?{size:S}:{},...p>0?{position:Vn[p-1]??"unknown"}:{},...N>0?{opacity:(N-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(br))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...h?{group:h}:{},...f?{ansiSource:f}:{},...d?{booru:d}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...$.length>0?{waive:$,reason:m}:{},...w.length>0?{pictures:w}:{}}}function Fd(e,t){let n=e.indexOf("ansi = ["),r=e.indexOf("]",n);if(n<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,s=e.slice(n,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>We(t.ansi[i++]));return(e.slice(0,n)+s+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${We(t.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${We(t.selectionBackground)}`)}function Li(e){let t=yr(kt(e)),n=new Set(e.waived??[]),r=Math.max(...Lt.map((i)=>i.label.length));return Lt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var Ad="https://kecan0406.github.io/ttheme/manifest.json",gk=20000;function Pt(e){return Td(e,"ttheme","catalog.json")}function mo(e,t){be(Pt(e),`${JSON.stringify(t,null,2)}
321
- `)}function Le(e,t=!0){let n=Hr(e),r=Pt(e),i=Hi();if(n.includes(Z)){if(!Pd(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=Kt(Au(r,"utf8"))}let s=n.filter(lt).flatMap((o)=>mk(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function Tn(e,t){return Hu(Au(Ot(e,t),"utf8"))}function Gr(e,t){return ht({owner:Md(e),name:t.name})}function mk(e,t,n){let r=Ot(e,t);if(!Pd(r))return[];try{let i=Tn(e,t);return po(i,Gr(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
322
- `);return[]}}function Hu(e){let t=Kt(e),n=Ou(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>Me(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function po(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function Kt(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=Hd(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function Hd(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=jt(e.name)??(e.base===void 0?void 0:jt(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&br(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.ansiSource]){let r=typeof n==="string"?hu(n):"has a field that is not text";if(r)return r}return}function Ld(e){return Td(e,"ttheme","kept.json")}function wo(e,t){be(Ld(e),`${JSON.stringify({palettes:t},null,2)}
323
- `)}function sn(e){try{let{palettes:t}=JSON.parse(Au(Ld(e),"utf8"));return Array.isArray(t)?t.filter((n)=>Hd(n)===void 0):[]}catch{return[]}}function _e(e,t,n=!0){let r=[...t.palettes,...go(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...sn(e).filter((s)=>!i.has(s.name))]}}function An(e){return _e(e,Le(e))}class bo extends Error{}class $o extends Error{}async function Gi(e,t,n=gk,r){let i;try{let s=AbortSignal.timeout(n);i=await fetch(e,{signal:r?AbortSignal.any([s,r]):s})}catch(s){throw Error(`cannot reach ${e} — ${s instanceof Error?s.message:String(s)}`)}if(i.status===404)throw new bo(`nothing at ${e}`);if(i.status===403||i.status===429)throw new $o(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function Ui(e){let t=new Set(e.waived??[]),n=e.gate??yr(kt(e));return Lt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function nr(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${Lu(e,[t])}`);return n}function Lu(e,t){let n=t.map((o)=>o.toLowerCase()),r=e.filter((o)=>n.some((a)=>o.name.includes(a))),i=e.filter((o)=>!r.includes(o)&&n.some((a)=>o.group.toLowerCase().includes(a))),s=[...r,...i].map((o)=>o.name).slice(0,3);return s.length>0?`did you mean: ${s.join(", ")}?`:"`ttheme list` shows what is there"}function Gd(e,t){let n=t.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function Ud(e,t,n){let r=n.toLowerCase(),i=(s)=>s.name===t.name?0:s.group===t.group?1:2;return e.filter((s)=>s.booru?.toLowerCase().includes(r)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function _d(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as dy}from"node:child_process";import{existsSync as Fo,mkdirSync as Pg,readdirSync as Lg,readFileSync as rc,rmSync as Tg}from"node:fs";import{basename as Gg,join as ln}from"node:path";import{execFileSync as Tk,spawn as Ak}from"node:child_process";import{existsSync as Tt,mkdirSync as Hk,readFileSync as Jr,realpathSync as Lk,rmSync as Ku,utimesSync as Gk,writeFileSync as Uk}from"node:fs";import{homedir as Kr}from"node:os";import{dirname as _k,join as Pe}from"node:path";var pk=["black","red","green","yellow","blue","magenta","cyan","white"];function Cd(e,t){return[e,...pk.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
324
- `)}var _i={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...Ur(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}'`,"",Cd("[colors.normal]",e.ansi.slice(0,8)),Cd("[colors.bright]",e.ansi.slice(8,16))].join(`
325
- `);return[{path:`alacritty/themes/${pe(e.name)}.toml`,content:t}]}};var Ci={id:"ghostty",emit(e){let t=[...Ur(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"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(`
326
- `);return[{path:`ghostty/themes/${pe(e.name)}`,content:t}]}};function Hn(e){let[t,n,r]=qe(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function jd(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,Hn(t)])),"Background Color":Hn(e.background),"Bold Color":Hn(e.foreground),"Cursor Color":Hn(e.cursor),"Cursor Text Color":Hn(e.background),"Foreground Color":Hn(e.foreground),"Selected Text Color":Hn(e.foreground),"Selection Color":Hn(e.selectionBackground)}}function wk(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Wd(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:pe(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...wk(t.get(o.name)),...jd(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
327
- `}function bk(e,t){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(t).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
328
- `)}var ji={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let t=['<?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(jd(e)).map(([n,r])=>bk(n,r)),"</dict>","</plist>",""].join(`
329
- `);return[{path:`iterm2/${pe(e.name)}.itermcolors`,content:t}]}};var Wi={id:"kitty",emit(e){let t=[...Ur(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((n,r)=>`color${r} ${n}`),""].join(`
330
- `);return[{path:`kitty/themes/${pe(e.name)}.conf`,content:t}]}};function Jd(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).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).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(`
331
- `)}var $k=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],kk=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Ki=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",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:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{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:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{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",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, in your local market — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"The palette to start from — the default one when left out"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in $EDITOR — the contrast gate advises, never refuses",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:"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:$k,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},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Ji(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function Gu(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var yk=[["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 market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function qi(e,t=!1){let n=Ki.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=kk.filter(({section:o})=>n.some((a)=>a.section===o)),i=[...t?["ttheme alone lists every installed palette, grouped, with previews"]:[],e?"ttheme help <command> describes one command · ttheme --version prints the version":"ttheme help <command> describes one · ttheme help all lists every command with what it does","https://kecan0406.github.io/ttheme"];if(!e){let o=n.filter((u)=>u.start),a=Math.max(...r.map(({title:u})=>u.length));return["Usage: ttheme <command>","",Ve.description,"","Start here",...Gu(o.map((u)=>[Ji(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
332
- `)}let s=Math.max(...n.map((o)=>Ji(o).length));return["Usage: ttheme <command>","",Ve.description,...r.flatMap(({section:o,title:a})=>["",a,...Gu(n.filter((u)=>u.section===o).map((u)=>[Ji(u),u.about]),s)]),"","Examples",...Gu(yk),"",...i].join(`
333
- `)}import{readFileSync as Ek}from"node:fs";import{join as vk}from"node:path";var ko=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],_r={ghostty:"Ghostty",kitty:"kitty",alacritty:"Alacritty",wezterm:"WezTerm",iterm2:"iTerm2","windows-terminal":"Windows Terminal",warp:"Warp"},Yd="# ttheme begin",Zd="# ttheme end",Qi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Yi(e,t){let n=`${Yd}
320
+ `}class Td{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 t=new TextEncoder().encode(e);if(t.length>255)throw Error(`"${e}" is too long to share`);this.u8(t.length),this.bytes.push(...t)}color(e){let t=Number.parseInt(e.slice(1),16);this.u8(t>>16),this.u8(t>>8),this.u8(t)}done(){return Buffer.from(this.bytes).toString("base64url")}}class Ad{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(),t=this.bytes.subarray(this.at,this.at+e);if(t.length!==e)throw Error("the share code is cut short");return this.at+=e,new TextDecoder("utf-8",{fatal:!0}).decode(t)}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 Hd(e){let t=new Td;t.str(e.name);for(let r of[e.background,e.foreground,e.cursor,e.selection,...e.ansi])t.color(r);for(let r of e.signature)t.u8(Pd.indexOf(r));t.str(e.base),t.str(e.group),t.str(e.ansiSource),t.str(e.booru),t.u16((e.waive??[]).reduce((r,i)=>r|1<<Ha.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(ee.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:zn.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${nn}${t.done()}`}function Ld(e){if(!e.startsWith(nn))throw Error(`a share code starts with ${nn}`);let t=e.slice(nn.length);if(!/^[A-Za-z0-9_-]+$/.test(t))throw Error("the share code holds characters it never uses — was it copied whole?");let n=new Ad(new Uint8Array(Buffer.from(t,"base64url"))),r=n.str(),[i,s,o,a,...u]=Array.from({length:20},()=>n.color()),c=[n.u8(),n.u8(),n.u8()].map((E)=>Pd[E]??`slot${E}`),l=n.str(),h=n.str(),f=n.str(),d=n.str(),g=n.u16(),m=n.str(),$=Ha.filter((E,y)=>g&1<<y),p=Array.from({length:n.u8()},()=>{let E=ee[n.u8()]?.key??"unknown",y=n.u32(),S=n.u16(),w=n.u8(),N=n.u16();return{site:E,id:y,...S===1?{size:"fill"}:S>1?{size:S}:{},...w>0?{position:zn[w-1]??"unknown"}:{},...N>0?{opacity:(N-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(br))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...h?{group:h}:{},...f?{ansiSource:f}:{},...d?{booru:d}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...$.length>0?{waive:$,reason:m}:{},...p.length>0?{pictures:p}:{}}}function Gd(e,t){let n=e.indexOf("ansi = ["),r=e.indexOf("]",n);if(n<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,s=e.slice(n,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>We(t.ansi[i++]));return(e.slice(0,n)+s+e.slice(r)).replace(/^(foreground\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${We(t.foreground)}`).replace(/^(selection_background\s*=\s*)"#[0-9a-fA-F]{6}"/m,(o,a)=>`${a}${We(t.selectionBackground)}`)}function _i(e){let t=yr(kt(e)),n=new Set(e.waived??[]),r=Math.max(...Lt.map((i)=>i.label.length));return Lt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var Cd="https://kecan0406.github.io/ttheme/manifest.json",wk=20000;function Pt(e){return _d(e,"ttheme","catalog.json")}function ko(e,t){be(Pt(e),`${JSON.stringify(t,null,2)}
321
+ `)}function Le(e,t=!0){let n=Lr(e),r=Pt(e),i=Li();if(n.includes(Z)){if(!Ud(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=Kt(Gu(r,"utf8"))}let s=n.filter(lt).flatMap((o)=>bk(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function Pn(e,t){return Uu(Gu(Ft(e,t),"utf8"))}function Ur(e,t){return ht({owner:Rd(e),name:t.name})}function bk(e,t,n){let r=Ft(e,t);if(!Ud(r))return[];try{let i=Pn(e,t);return yo(i,Ur(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
322
+ `);return[]}}function Uu(e){let t=Kt(e),n=Tu(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>$e(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function yo(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function Kt(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=jd(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function jd(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=jt(e.name)??(e.base===void 0?void 0:jt(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&br(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.catalog??"-",e.ansiSource]){let r=typeof n==="string"?Hi(n):"has a field that is not text";if(r)return r}return}function Wd(e){return _d(e,"ttheme","kept.json")}function Eo(e,t){be(Wd(e),`${JSON.stringify({palettes:t},null,2)}
323
+ `)}function rn(e){try{let{palettes:t}=JSON.parse(Gu(Wd(e),"utf8"));return Array.isArray(t)?t.filter((n)=>jd(n)===void 0):[]}catch{return[]}}function _e(e,t,n=!0){let r=[...t.palettes,...$o(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...rn(e).filter((s)=>!i.has(s.name))]}}function Tn(e){return _e(e,Le(e))}class vo extends Error{}class Mo extends Error{}async function Ci(e,t,n=wk,r){let i;try{let s=AbortSignal.timeout(n);i=await fetch(e,{signal:r?AbortSignal.any([s,r]):s})}catch(s){throw Error(`cannot reach ${e} — ${s instanceof Error?s.message:String(s)}`)}if(i.status===404)throw new vo(`nothing at ${e}`);if(i.status===403||i.status===429)throw new Mo(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function ji(e){let t=new Set(e.waived??[]),n=e.gate??yr(kt(e));return Lt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function tr(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${_u(e,[t])}`);return n}function _u(e,t){let n=t.map((o)=>o.toLowerCase()),r=e.filter((o)=>n.some((a)=>o.name.includes(a))),i=e.filter((o)=>!r.includes(o)&&n.some((a)=>o.group.toLowerCase().includes(a))),s=[...r,...i].map((o)=>o.name).slice(0,3);return s.length>0?`did you mean: ${s.join(", ")}?`:"`ttheme list` shows what is there"}function Jd(e,t){let n=t.toLowerCase();return e.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function Kd(e,t,n){let r=n.toLowerCase(),i=(s)=>s.name===t.name?0:s.group===t.group?1:2;return e.filter((s)=>s.booru?.toLowerCase().includes(r)).map((s,o)=>({p:s,at:o})).sort((s,o)=>i(s.p)-i(o.p)||s.at-o.at).map(({p:s})=>s)}function qd(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as py}from"node:child_process";import{existsSync as sc,mkdirSync as Ug,readdirSync as wy,readFileSync as ac,rmSync as _g}from"node:fs";import{basename as by,join as ar,relative as $y}from"node:path";import{execFileSync as Lk,spawn as Gk}from"node:child_process";import{existsSync as Tt,mkdirSync as Uk,readFileSync as Kr,realpathSync as _k,rmSync as Yu,utimesSync as Ck,writeFileSync as jk}from"node:fs";import{homedir as qr}from"node:os";import{dirname as Wk,join as Pe}from"node:path";var $k=["black","red","green","yellow","blue","magenta","cyan","white"];function Qd(e,t){return[e,...$k.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
324
+ `)}var Wi={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[..._r(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}'`,"",Qd("[colors.normal]",e.ansi.slice(0,8)),Qd("[colors.bright]",e.ansi.slice(8,16))].join(`
325
+ `);return[{path:`alacritty/themes/${pe(e.name)}.toml`,content:t}]}};var Ji={id:"ghostty",emit(e){let t=[..._r(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"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(`
326
+ `);return[{path:`ghostty/themes/${pe(e.name)}`,content:t}]}};function An(e){let[t,n,r]=qe(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function Yd(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,An(t)])),"Background Color":An(e.background),"Bold Color":An(e.foreground),"Cursor Color":An(e.cursor),"Cursor Text Color":An(e.background),"Foreground Color":An(e.foreground),"Selected Text Color":An(e.foreground),"Selection Color":An(e.selectionBackground)}}function kk(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Zd(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:pe(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...kk(t.get(o.name)),...Yd(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
327
+ `}function yk(e,t){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(t).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
328
+ `)}var Ki={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(e){let t=['<?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(Yd(e)).map(([n,r])=>yk(n,r)),"</dict>","</plist>",""].join(`
329
+ `);return[{path:`iterm2/${pe(e.name)}.itermcolors`,content:t}]}};var qi={id:"kitty",emit(e){let t=[..._r(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((n,r)=>`color${r} ${n}`),""].join(`
330
+ `);return[{path:`kitty/themes/${pe(e.name)}.conf`,content:t}]}};function zd(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).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).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(`
331
+ `)}var Ek=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],vk=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Yi=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",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:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{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:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{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, catalog, installed"}}},{name:"add",args:["<palette...>"],about:"Install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, in your local market — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"The palette to start from — the default one when left out"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in $EDITOR — the contrast gate advises, never refuses",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:"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:Ek,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},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Qi(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function Cu(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var Mk=[["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 market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function Zi(e,t=!1){let n=Yi.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=vk.filter(({section:o})=>n.some((a)=>a.section===o)),i=[...t?["ttheme alone lists every installed palette, grouped, with previews"]:[],e?"ttheme help <command> describes one command · ttheme --version prints the version":"ttheme help <command> describes one · ttheme help all lists every command with what it does","https://kecan0406.github.io/ttheme"];if(!e){let o=n.filter((u)=>u.start),a=Math.max(...r.map(({title:u})=>u.length));return["Usage: ttheme <command>","",Ve.description,"","Start here",...Cu(o.map((u)=>[Qi(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
332
+ `)}let s=Math.max(...n.map((o)=>Qi(o).length));return["Usage: ttheme <command>","",Ve.description,...r.flatMap(({section:o,title:a})=>["",a,...Cu(n.filter((u)=>u.section===o).map((u)=>[Qi(u),u.about]),s)]),"","Examples",...Cu(Mk),"",...i].join(`
333
+ `)}import{readFileSync as Sk}from"node:fs";import{join as Ik}from"node:path";var So=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Cr={ghostty:"Ghostty",kitty:"kitty",alacritty:"Alacritty",wezterm:"WezTerm",iterm2:"iTerm2","windows-terminal":"Windows Terminal",warp:"Warp"},xd="# ttheme begin",Dd="# ttheme end",zi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Vi(e,t){let n=`${xd}
334
334
  ${t}
335
- ${Zd}
336
- `;if(Qi.test(e))return e.replace(Qi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
335
+ ${Dd}
336
+ `;if(zi.test(e))return e.replace(zi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
337
337
  `)}
338
- ${n}`}function Zi(e){let t=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(t===e)return e;return t.trim()===""?"":t.replace(/\n*$/,`
339
- `)}function rr(e,t){let n=e.replace(Qi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function yo(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 zd(e,t,n=""){let r=[];if(!rr(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!rr(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${pe(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
340
- `)}function Vd(e){return`source ${e}/ttheme.zsh`}var Mk="# ttheme settings — uncomment a line to change it; exported variables win over this file",Cr={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_BG_BLUR:{doc:"# soften the background pictures behind the text: a blur radius in screen pixels, 0 keeps them sharp — changing it draws every picture again (default 0)",default:"0"},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 posts tagged solo, the character alone, by danbooru or zerochan; 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_MIN_SCORE:{doc:"# the lowest score find lists: off, or a number such as 5, 10, 25, 50 or 100 — danbooru, konachan and yande.re filter by it, zerochan keeps no score (default off)",default:"off"},TTHEME_FIND_MIN_SIZE:{doc:"# the shortest side a picture find lists must reach, in pixels: off, or a number such as 720, 1080, 1440, 1800 or 2560 (default off)",default:"off"},TTHEME_FIND_SITES:{doc:"# the sites find mixes in its all tab: any of danbooru, konachan, yande.re and zerochan (default all four)",default:"danbooru konachan yande.re zerochan"},TTHEME_FIND_HIDE:{doc:"# the kinds of picture find leaves out by tag: comic, monochrome, sketch, chibi, or none to keep them all (default none)",default:"none"},TTHEME_FIND_HIDE_TAGS:{doc:'# more tags find leaves out, spaced — e.g. "cosplay multiple_girls" (default none)',default:""},TTHEME_FIND_PNG:{doc:"# on lists PNG originals only — a zerochan post counts only where danbooru holds the same file (default off)",default:"off"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://danbooru.donmai.us" (default none)',default:""}};function Uu(e){return Cr[e]?.default}function _u(e,t){let n=`: \${${e}:=${t}}`;return Uu(e)===t?`# ${n}`:n}function Xd(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function Sk(e,t){if(Xd(t).test(e))return e;let n=Cr[t];return`${e.replace(/\n*$/,`
338
+ ${n}`}function Xi(e){let t=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(t===e)return e;return t.trim()===""?"":t.replace(/\n*$/,`
339
+ `)}function nr(e,t){let n=e.replace(zi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Io(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 eg(e,t,n=""){let r=[];if(!nr(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!nr(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${pe(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
340
+ `)}function tg(e){return`source ${e}/ttheme.zsh`}var Nk="# ttheme settings — uncomment a line to change it; exported variables win over this file",jr={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_BG_BLUR:{doc:"# soften the background pictures behind the text: a blur radius in screen pixels, 0 keeps them sharp — changing it draws every picture again (default 0)",default:"0"},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 posts tagged solo, the character alone, by danbooru or zerochan; 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_MIN_SCORE:{doc:"# the lowest score find lists: off, or a number such as 5, 10, 25, 50 or 100 — danbooru, konachan and yande.re filter by it, zerochan keeps no score (default off)",default:"off"},TTHEME_FIND_MIN_SIZE:{doc:"# the shortest side a picture find lists must reach, in pixels: off, or a number such as 720, 1080, 1440, 1800 or 2560 (default off)",default:"off"},TTHEME_FIND_SITES:{doc:"# the sites find mixes in its all tab: any of danbooru, konachan, yande.re and zerochan (default all four)",default:"danbooru konachan yande.re zerochan"},TTHEME_FIND_HIDE:{doc:"# the kinds of picture find leaves out by tag: comic, monochrome, sketch, chibi, or none to keep them all (default none)",default:"none"},TTHEME_FIND_HIDE_TAGS:{doc:'# more tags find leaves out, spaced — e.g. "cosplay multiple_girls" (default none)',default:""},TTHEME_FIND_PNG:{doc:"# on lists PNG originals only — a zerochan post counts only where danbooru holds the same file (default off)",default:"off"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://danbooru.donmai.us" (default none)',default:""}};function ju(e){return jr[e]?.default}function Wu(e,t){let n=`: \${${e}:=${t}}`;return ju(e)===t?`# ${n}`:n}function ng(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function Rk(e,t){if(ng(t).test(e))return e;let n=jr[t];return`${e.replace(/\n*$/,`
341
341
  `)}
342
342
  ${n.doc}
343
- ${_u(t,n.default)}
344
- `}var Bd=Object.keys(Cr),Ik=8;function jr(e){let t="";try{t=Ek(vk(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??Cr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(Ik,Math.max(0,r)):0}function Cu(){let e=Object.entries(Cr).map(([t,n])=>`${n.doc}
345
- ${_u(t,n.default)}`);return`${[Mk,...e].join(`
343
+ ${Wu(t,n.default)}
344
+ `}var rg=Object.keys(jr),Fk=8;function Wr(e){let t="";try{t=Sk(Ik(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??jr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(Fk,Math.max(0,r)):0}function Ju(){let e=Object.entries(jr).map(([t,n])=>`${n.doc}
345
+ ${Wu(t,n.default)}`);return`${[Nk,...e].join(`
346
346
 
347
347
  `)}
348
- `}function xd(e,t,n){let r=_u(t,n),i=Xd(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
348
+ `}function ig(e,t,n){let r=Wu(t,n),i=ng(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
349
349
  `)}
350
350
  ${r}
351
- `}function Dd(e){if(e==="")return Cu();return Object.keys(Cr).reduce(Sk,e)}function eg(e,t,n=""){return[...e?[`include themes/${pe(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!rr(n,r.split(" ")[0]))].join(`
352
- `)}function tg(e){let t=e.replace(Qi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var Nk=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Kd=/^[ \t]*\[/m,qd=/^[ \t]*import[ \t]*=/m,Rk=/^[ \t]*general[ \t]*[.=]/m;function Ok(e){return e?`[general]
353
- import = ["${e}"]`:""}function zi(e,t){let n=e.replace(Qi,""),r=Nk.exec(n);if(!r){let u=n.search(Kd),c=u<0?n:n.slice(0,u);if(Rk.test(n)||qd.test(c))return;return Yi(e,Ok(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(Kd);if(qd.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
351
+ `}function sg(e){if(e==="")return Ju();return Object.keys(jr).reduce(Rk,e)}function og(e,t,n=""){return[...e?[`include themes/${pe(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!nr(n,r.split(" ")[0]))].join(`
352
+ `)}function ag(e){let t=e.replace(zi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var Ok=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Vd=/^[ \t]*\[/m,Xd=/^[ \t]*import[ \t]*=/m,Pk=/^[ \t]*general[ \t]*[.=]/m;function Tk(e){return e?`[general]
353
+ import = ["${e}"]`:""}function Bi(e,t){let n=e.replace(zi,""),r=Ok.exec(n);if(!r){let u=n.search(Vd),c=u<0?n:n.slice(0,u);if(Pk.test(n)||Xd.test(c))return;return Vi(e,Tk(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(Vd);if(Xd.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
354
354
  `:"";return`${n.slice(0,i)}
355
- ${Yd}
356
- ${a}${Zd}${s}`}var Qd=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Fk=/^return config[ \t]*$/gm;function ng(e){return`dofile(${JSON.stringify(e)})(config)`}var rg=`local wezterm = require 'wezterm'
355
+ ${xd}
356
+ ${a}${Dd}${s}`}var Bd=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Ak=/^return config[ \t]*$/gm;function ug(e){return`dofile(${JSON.stringify(e)})(config)`}var cg=`local wezterm = require 'wezterm'
357
357
  local config = wezterm.config_builder()
358
358
 
359
- `;function ig(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${rg}return config
360
- `?"":t}function Vi(e,t){let n=`-- ttheme begin
359
+ `;function lg(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${cg}return config
360
+ `?"":t}function xi(e,t){let n=`-- ttheme begin
361
361
  ${t}
362
362
  -- ttheme end
363
- `;if(Qd.test(e))return e.replace(Qd,n);if(e==="")return`${rg}${n}
363
+ `;if(Bd.test(e))return e.replace(Bd,n);if(e==="")return`${cg}${n}
364
364
  return config
365
- `;let r=[...e.matchAll(Fk)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
366
- ${e.slice(r.index)}`}var sg="[appearance.themes]";function og(e){let t=e.findIndex((r)=>r.trim()===sg);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function Eo(e){let t=e.split(`
367
- `),n=og(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function ag(e){return`{ custom = { name = "${e}", path = "${pe(e)}.yaml" } }`}function vo(e,t){let n=e.split(`
368
- `),r=og(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
365
+ `;let r=[...e.matchAll(Ak)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
366
+ ${e.slice(r.index)}`}var hg="[appearance.themes]";function fg(e){let t=e.findIndex((r)=>r.trim()===hg);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function No(e){let t=e.split(`
367
+ `),n=fg(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function dg(e){return`{ custom = { name = "${e}", path = "${pe(e)}.yaml" } }`}function Ro(e,t){let n=e.split(`
368
+ `),r=fg(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
369
369
  `)}
370
- ${sg}
370
+ ${hg}
371
371
  theme = ${t}
372
372
  `;let i=n.findIndex((s,o)=>o>r[0]&&o<r[1]&&/^theme\s*=/.test(s));if(i>=0)n.splice(i,1,...t===void 0?[]:[`theme = ${t}`]);else if(t!==void 0)n.splice(r[0]+1,0,`theme = ${t}`);return n.join(`
373
- `)}function ju(e,t,n=[]){for(let c of e)for(let l of[c.name,c.group,c.native??"",c.ansiSource])if(/["$`\\]/.test(l))throw Error(`${c.name}: "${l}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((c)=>c.name.length)),i=(c,l)=>` ${c.name.padEnd(r)} "${l}"`,s=(c)=>c.map((l)=>l.name).join(" "),o=De(e),a=(c)=>`'${c.replaceAll("'","'\\''")}'`,u=Ki.filter((c)=>c.section!=="setup"&&!c.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Ve.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${t??""}`,"","# 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=(${u.map((c)=>c.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((c)=>c.shell).map((c)=>c.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((c)=>` ${c.name} ${a(c.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((c)=>` ${c.name} ${a(c.about)}`),")",`typeset -g TTHEME_HELP=${a(qi(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${a(qi(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Bd.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Cu().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((c)=>i(c,[c.background,c.foreground,c.cursor,c.selection,...c.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(Xn(o))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((c)=>i(c,c.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((c)=>i(c,lo(c).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((c)=>i(c,c.ansiSource)),")",""].join(`
374
- `)}var Wu={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:ju(e.map(Rt))}]}};var Pk=["black","red","green","yellow","blue","magenta","cyan","white"];function ug(e,t){return[` ${e}:`,...Pk.map((n,r)=>` ${n}: "${t[r]}"`)]}var Xi={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${et(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...ug("normal",e.ansi.slice(0,8)),...ug("bright",e.ansi.slice(8,16)),""].join(`
375
- `);return[{path:`warp/themes/${pe(e.name)}.yaml`,content:t}]}};var cg=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,Bi={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${pe(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 = ${cg(e.ansi.slice(0,8))}`,`brights = ${cg(e.ansi.slice(8,16))}`,""].join(`
376
- `);return[{path:`wezterm/colors/${pe(e.name)}.toml`,content:t}]}},Wr=(e)=>JSON.stringify(e);function lg(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Wr(e.path)}`,`local COLORS = ${Wr(e.colors)}`,`local BACKGROUNDS = ${Wr(e.backgrounds)}`,`local STARTUP = ${e.startup?Wr(pe(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Wr(t.name)}] = ${Wr(t.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)):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(`
377
- `)}var hg=["black","red","green","yellow","blue","purple","cyan","white"];function fg(e){return{name:pe(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(hg.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(hg.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function Ju(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:pe(n)}]}:{},schemes:e.map(fg)};return`${JSON.stringify(r,null,2)}
378
- `}var xi={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${pe(e.name)}.json`,content:`${JSON.stringify(fg(e),null,2)}
379
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Ju(e)}]}};function pe(e){return`ttheme-${en(e)}`}function Ur(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var Ck={ghostty:Ci,kitty:Wi,alacritty:_i,wezterm:Bi,iterm2:ji,"windows-terminal":xi,warp:Xi},dg="ttheme-default";function on(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let t=(n,r)=>Tk(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?t("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")t("defaults",["write",e,"Default Bookmark Guid","-string",n])},running:()=>{try{return t("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function ft(e){return e.off?void 0:an(e)}function Di(e,t){if(!e.terminals.includes("iterm2"))return e;let n=t.read();return n&&!n.startsWith("ttheme-")?{...e,itermBase:n}:e}function or(e,t){if(!e.terminals.includes("iterm2"))return!1;let n=t.read(),r=ft(e)?dg:n===dg?e.itermBase:void 0;if(!r||r===n)return!1;return t.write(r),!0}function ue(){return process.env.XDG_CONFIG_HOME??Pe(Kr(),".config")}function es(e){return Pe(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ie(e){let t=Rn(e);if(!Tt(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Jr(t,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${t} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>ko.includes(r)),...n.author?{author:n.author}:{},...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},...Array.isArray(n.markets)?{markets:n.markets.filter((r)=>typeof r==="string")}:{},...n.updates&&typeof n.updates==="object"?{updates:Object.fromEntries(Object.entries(n.updates).filter((r)=>typeof r[1]==="boolean"))}:{},palettes:n.palettes}}function yt(e,t){be(Rn(e),`${JSON.stringify(t,null,2)}
380
- `)}function gg(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>Me(o)??[]))].filter((o)=>!e.palettes.some((a)=>Me(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Lu(De(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function mg(e,t){let n=e==="wezterm"?"colors":"themes";return(Ck[e].emit?.(t)??[]).flatMap((r)=>{let[,i,s]=r.path.split("/");return i===n&&s!==void 0?[{file:s,content:r.content}]:[]})}function Mo(e){return process.platform==="darwin"?Pe(e,".warp","themes"):Pe(process.env.XDG_DATA_HOME??Pe(e,".local","share"),"warp-terminal","themes")}function ir(e,t,n){if(e==="warp")return Mo(n);return Pe(t,e,e==="wezterm"?"colors":"themes")}function So(e,t){return process.platform==="darwin"?Pe(e,".warp","settings.toml"):Pe(t,"warp-terminal","settings.toml")}var qu='"dark"';function Qu(e){return Pe(e,"ttheme","warp.base")}var jk="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 Wk(e,t,n,r){let i=So(t,e);if(!Tt(i))return;let s=Qu(e),o=Jr(i,"utf8"),a=Eo(o),u=a?.includes(`path = "${pe("")}`)===!0,c;if(n){if(!u&&!Tt(s))Hk(_k(s),{recursive:!0}),Uk(s,a??"");c=ag(n)}else{if(!u)return;c=Tt(s)&&Jr(s,"utf8")||qu,Ku(s,{force:!0})}let l=vo(o,c);if(l===o)return;if(r)Ta(i),Ak(process.execPath,["-e",jk,Lk(i),l,o],{detached:!0,stdio:"ignore"}).unref();else pi(i,l);return i}function pg(e){return Pe(e,"ttheme","kitty.py")}function qr(e,t){let n=Pe(t,".wezterm.lua");return Tt(n)?n:Pe(e,"wezterm","wezterm.lua")}function Io(e){return Pe(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Yu(e){return[Pe(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Pe(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Pe(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Tt(t))}function Jk(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Jr(t,"utf8"))?.[1];if(n)return n}return}function an(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function sr(e,t){return e==="ghostty"?Pe(t,"ghostty","config"):Pe(t,"kitty","kitty.conf")}function wg(e,t,n,r){return e==="ghostty"?zd(Pe(t,"ttheme"),n,r):eg(n,pg(t),r)}function qt(e){return Tt(e)?Jr(e,"utf8"):""}function ar(e){return Pe(e,"alacritty","alacritty.toml")}function Kk(e,t){return t?Pe(e,"alacritty","themes",`${pe(t)}.toml`):void 0}function bg(e,t,n,r){let i=je(e),s=t.map(kt),o=new Map;for(let u of s){let c=fd(i,u.name,r);if(c)o.set(u.name,c)}let a=new Set(De(t).map((u)=>u.name));return Wd(s.filter((u)=>a.has(u.name)),o,s.find((u)=>u.name===ft(n)),n.itermBase)}function Qt(e,t=Kr()){let n=ie(e);if(!n.terminals.includes("iterm2"))return;be(es(t),bg(e,gg(An(e),n.palettes),n,t))}function rt(e,t,n,r=Kr()){nt(je(e));let i=gg(_e(e,t),n.palettes);$d(e,new Map(i.map((f)=>[f.name,f.backdrop]))),wo(e,i);let s=[],o=(f,d)=>{if(s.push(f),Tt(f)&&Jr(f,"utf8")===d)return!1;return be(f,d),!0},a=(f,d)=>{s.push(f),pi(f,d)},u=ft(n),c=!1;for(let f of n.terminals){if(f==="iterm2"){o(es(r),bg(e,i,n,r));continue}if(f==="windows-terminal"){if(n.wtHome){let w=Yu(n.wtHome),M=i.map(kt),y=Ju(M,n.wtProfile??Jk(w),u);if(o(Io(n.wtHome),y)){let S=new Date;for(let p of w)Gk(p,S,S);c=w.length>0}}continue}let d=u!==void 0&&f==="warp"&&!Tt(Pe(Mo(r),`${pe(u)}.yaml`)),g=f==="warp"?Wk(e,r,u,d):void 0;for(let w of i)for(let{file:M,content:y}of mg(f,kt(w)))o(Pe(ir(f,e,r),M),y);if(f==="warp"){if(g)s.push(g);continue}if(f==="wezterm"){let w=Pe(e,"ttheme","wezterm.lua");o(w,lg({path:w,colors:ir("wezterm",e,r),backgrounds:je(e),...u?{startup:u}:{},palettes:i.map(kt)}));let M=qr(e,r),y=Vi(qt(M),ng(w));if(y!==void 0)a(M,y);continue}if(f==="alacritty"){let w=ar(e),M=zi(qt(w),Kk(e,u));if(M!==void 0)a(w,M);continue}if(f==="kitty")o(pg(e),Jd({themes:ir("kitty",e,r),backgrounds:je(e)}));let m=sr(f,e),$=qt(m);a(m,Yi($,wg(f,e,u,$)))}let l=Pe(e,"ttheme","palettes.zsh"),h=ju(i,u,n.terminals);if(c||qt(l)!==h)be(l,h),Ku(`${l}.zwc`,{force:!0});return s.push(l),s}function $g(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function qk(e){return[...new Set(e.split(`
381
- `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function kg(e,t,n=Kr()){let r=ft(t),i=(o)=>$g(o,n),s=[];for(let o of t.terminals){if(o==="iterm2"){s.push(`Write ${i(es(n))} — a "ttheme · <palette>" profile per palette`);continue}if(o==="windows-terminal"){if(t.wtHome)s.push(`Write ${Io(t.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(s.push(`Write ${i(ir(o,e,n))}/${pe("*")} — a theme file per palette`),o==="warp"){let c=So(n,e);if(r&&Tt(c))s.push(`Edit ${i(c)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(o==="wezterm"){let c=qr(e,n);if(Vi(qt(c),"")!==void 0)s.push(`Edit ${i(c)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(o==="alacritty"){let c=ar(e);if(zi(qt(c),void 0)!==void 0)s.push(`Edit ${i(c)} — a ttheme block: general.import`);continue}let a=sr(o,e),u=qt(a);s.push(`Edit ${i(a)} — a ttheme block: ${qk(wg(o,e,r,u))}`)}return s}function yg(e,t,n=Kr()){let r=[],i=(s)=>$g(s,n);if(t.includes("ghostty")){let s=sr("ghostty",e);if(rr(qt(s),"command"))r.push(`${i(s)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(t.includes("kitty")){let s=qt(sr("kitty",e));if(rr(s,"window_logo_scale")||rr(s,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(t.includes("alacritty")){let s=ar(e);if(tg(qt(s)))r.push(`${i(s)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function No(e,t,n,r,i=Kr()){let s=[],o=_e(e,t,!1).palettes;for(let a of n)for(let u of o.filter((c)=>r.includes(c.name)))for(let{file:c}of mg(a,kt(u))){let l=Pe(ir(a,e,i),c);if(Tt(l))Ku(l,{force:!0}),s.push(l)}return s}function un(e,t,n,r){let i=on(),s=Boolean(ft(n))!==Boolean(ft(r)),o=s?Di(r,i):r;return rt(e,t,o),yt(e,o),s&&or(o,i)&&i.running()}import{existsSync as iy,mkdirSync as Ng,readFileSync as Rg,statSync as sy}from"node:fs";import{homedir as oy}from"node:os";import{dirname as ay,join as Sg}from"node:path";import{existsSync as Zu,mkdirSync as zu,readFileSync as Yr,writeFileSync as Xk}from"node:fs";import{homedir as Bk}from"node:os";import{dirname as Vu,join as Zr}from"node:path";import{spawn as Qk}from"node:child_process";var Yk=30000,Zk=3,zk=97,Vk=`ObjC.import('Vision')
373
+ `)}function Ku(e,t,n=[]){for(let c of e)for(let l of[c.name,c.group,c.native??"",c.ansiSource])if(/["$`\\]/.test(l))throw Error(`${c.name}: "${l}" contains a character that breaks zsh quoting`);let r=Math.max(0,...e.map((c)=>c.name.length)),i=(c,l)=>` ${c.name.padEnd(r)} "${l}"`,s=(c)=>c.map((l)=>l.name).join(" "),o=De(e),a=(c)=>`'${c.replaceAll("'","'\\''")}'`,u=Yi.filter((c)=>c.section!=="setup"&&!c.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Ve.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${t??""}`,"","# 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=(${u.map((c)=>c.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((c)=>c.shell).map((c)=>c.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((c)=>` ${c.name} ${a(c.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((c)=>` ${c.name} ${a(c.about)}`),")",`typeset -g TTHEME_HELP=${a(Zi(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${a(Zi(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${rg.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Ju().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((c)=>i(c,[c.background,c.foreground,c.cursor,c.selection,...c.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${s(o)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(Vn(o))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((c)=>i(c,c.group)),")","","# the catalog a market palette sits in — the folder under the market's palettes/, one level below the market in every list","typeset -gA TTHEME_CATALOG=(",...e.filter((c)=>c.catalog).map((c)=>i(c,c.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((c)=>c.native).map((c)=>i(c,c.native??"")),")","","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((c)=>i(c,po(c).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((c)=>i(c,c.ansiSource)),")",""].join(`
374
+ `)}var qu={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Ku(e.map(Rt))}]}};var Hk=["black","red","green","yellow","blue","magenta","cyan","white"];function gg(e,t){return[` ${e}:`,...Hk.map((n,r)=>` ${n}: "${t[r]}"`)]}var Di={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${tt(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...gg("normal",e.ansi.slice(0,8)),...gg("bright",e.ansi.slice(8,16)),""].join(`
375
+ `);return[{path:`warp/themes/${pe(e.name)}.yaml`,content:t}]}};var mg=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,es={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${pe(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 = ${mg(e.ansi.slice(0,8))}`,`brights = ${mg(e.ansi.slice(8,16))}`,""].join(`
376
+ `);return[{path:`wezterm/colors/${pe(e.name)}.toml`,content:t}]}},Jr=(e)=>JSON.stringify(e);function pg(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Jr(e.path)}`,`local COLORS = ${Jr(e.colors)}`,`local BACKGROUNDS = ${Jr(e.backgrounds)}`,`local STARTUP = ${e.startup?Jr(pe(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Jr(t.name)}] = ${Jr(t.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)):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(`
377
+ `)}var wg=["black","red","green","yellow","blue","purple","cyan","white"];function bg(e){return{name:pe(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(wg.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(wg.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function Qu(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:pe(n)}]}:{},schemes:e.map(bg)};return`${JSON.stringify(r,null,2)}
378
+ `}var ts={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${pe(e.name)}.json`,content:`${JSON.stringify(bg(e),null,2)}
379
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Qu(e)}]}};function pe(e){return`ttheme-${en(e)}`}function _r(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}var Jk={ghostty:Ji,kitty:qi,alacritty:Wi,wezterm:es,iterm2:Ki,"windows-terminal":ts,warp:Di},$g="ttheme-default";function sn(e=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let t=(n,r)=>Lk(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?t("defaults",["read",e,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")t("defaults",["write",e,"Default Bookmark Guid","-string",n])},running:()=>{try{return t("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function ft(e){return e.off?void 0:on(e)}function ns(e,t){if(!e.terminals.includes("iterm2"))return e;let n=t.read();return n&&!n.startsWith("ttheme-")?{...e,itermBase:n}:e}function sr(e,t){if(!e.terminals.includes("iterm2"))return!1;let n=t.read(),r=ft(e)?$g:n===$g?e.itermBase:void 0;if(!r||r===n)return!1;return t.write(r),!0}function ue(){return process.env.XDG_CONFIG_HOME??Pe(qr(),".config")}function rs(e){return Pe(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ie(e){let t=In(e);if(!Tt(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Kr(t,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${t} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>So.includes(r)),...n.author?{author:n.author}:{},...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},...Array.isArray(n.markets)?{markets:n.markets.filter((r)=>typeof r==="string")}:{},...n.updates&&typeof n.updates==="object"?{updates:Object.fromEntries(Object.entries(n.updates).filter((r)=>typeof r[1]==="boolean"))}:{},palettes:n.palettes}}function yt(e,t){be(In(e),`${JSON.stringify(t,null,2)}
380
+ `)}function kg(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>$e(o)??[]))].filter((o)=>!e.palettes.some((a)=>$e(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:_u(De(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function yg(e,t){let n=e==="wezterm"?"colors":"themes";return(Jk[e].emit?.(t)??[]).flatMap((r)=>{let[,i,s]=r.path.split("/");return i===n&&s!==void 0?[{file:s,content:r.content}]:[]})}function Fo(e){return process.platform==="darwin"?Pe(e,".warp","themes"):Pe(process.env.XDG_DATA_HOME??Pe(e,".local","share"),"warp-terminal","themes")}function rr(e,t,n){if(e==="warp")return Fo(n);return Pe(t,e,e==="wezterm"?"colors":"themes")}function Oo(e,t){return process.platform==="darwin"?Pe(e,".warp","settings.toml"):Pe(t,"warp-terminal","settings.toml")}var Zu='"dark"';function zu(e){return Pe(e,"ttheme","warp.base")}var Kk="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 qk(e,t,n,r){let i=Oo(t,e);if(!Tt(i))return;let s=zu(e),o=Kr(i,"utf8"),a=No(o),u=a?.includes(`path = "${pe("")}`)===!0,c;if(n){if(!u&&!Tt(s))Uk(Wk(s),{recursive:!0}),jk(s,a??"");c=dg(n)}else{if(!u)return;c=Tt(s)&&Kr(s,"utf8")||Zu,Yu(s,{force:!0})}let l=Ro(o,c);if(l===o)return;if(r)Ga(i),Gk(process.execPath,["-e",Kk,_k(i),l,o],{detached:!0,stdio:"ignore"}).unref();else pi(i,l);return i}function Eg(e){return Pe(e,"ttheme","kitty.py")}function Qr(e,t){let n=Pe(t,".wezterm.lua");return Tt(n)?n:Pe(e,"wezterm","wezterm.lua")}function Po(e){return Pe(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Vu(e){return[Pe(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Pe(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Pe(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Tt(t))}function Qk(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Kr(t,"utf8"))?.[1];if(n)return n}return}function on(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function ir(e,t){return e==="ghostty"?Pe(t,"ghostty","config"):Pe(t,"kitty","kitty.conf")}function vg(e,t,n,r){return e==="ghostty"?eg(Pe(t,"ttheme"),n,r):og(n,Eg(t),r)}function qt(e){return Tt(e)?Kr(e,"utf8"):""}function or(e){return Pe(e,"alacritty","alacritty.toml")}function Yk(e,t){return t?Pe(e,"alacritty","themes",`${pe(t)}.toml`):void 0}function Mg(e,t,n,r){let i=je(e),s=t.map(kt),o=new Map;for(let u of s){let c=pd(i,u.name,r);if(c)o.set(u.name,c)}let a=new Set(De(t).map((u)=>u.name));return Zd(s.filter((u)=>a.has(u.name)),o,s.find((u)=>u.name===ft(n)),n.itermBase)}function Qt(e,t=qr()){let n=ie(e);if(!n.terminals.includes("iterm2"))return;be(rs(t),Mg(e,kg(Tn(e),n.palettes),n,t))}function it(e,t,n,r=qr()){rt(je(e));let i=kg(_e(e,t),n.palettes);vd(e,new Map(i.map((f)=>[f.name,f.backdrop]))),Eo(e,i);let s=[],o=(f,d)=>{if(s.push(f),Tt(f)&&Kr(f,"utf8")===d)return!1;return be(f,d),!0},a=(f,d)=>{s.push(f),pi(f,d)},u=ft(n),c=!1;for(let f of n.terminals){if(f==="iterm2"){o(rs(r),Mg(e,i,n,r));continue}if(f==="windows-terminal"){if(n.wtHome){let p=Vu(n.wtHome),E=i.map(kt),y=Qu(E,n.wtProfile??Qk(p),u);if(o(Po(n.wtHome),y)){let S=new Date;for(let w of p)Ck(w,S,S);c=p.length>0}}continue}let d=u!==void 0&&f==="warp"&&!Tt(Pe(Fo(r),`${pe(u)}.yaml`)),g=f==="warp"?qk(e,r,u,d):void 0;for(let p of i)for(let{file:E,content:y}of yg(f,kt(p)))o(Pe(rr(f,e,r),E),y);if(f==="warp"){if(g)s.push(g);continue}if(f==="wezterm"){let p=Pe(e,"ttheme","wezterm.lua");o(p,pg({path:p,colors:rr("wezterm",e,r),backgrounds:je(e),...u?{startup:u}:{},palettes:i.map(kt)}));let E=Qr(e,r),y=xi(qt(E),ug(p));if(y!==void 0)a(E,y);continue}if(f==="alacritty"){let p=or(e),E=Bi(qt(p),Yk(e,u));if(E!==void 0)a(p,E);continue}if(f==="kitty")o(Eg(e),zd({themes:rr("kitty",e,r),backgrounds:je(e)}));let m=ir(f,e),$=qt(m);a(m,Vi($,vg(f,e,u,$)))}let l=Pe(e,"ttheme","palettes.zsh"),h=Ku(i,u,n.terminals);if(c||qt(l)!==h)be(l,h),Yu(`${l}.zwc`,{force:!0});return s.push(l),s}function Sg(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Zk(e){return[...new Set(e.split(`
381
+ `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function Ig(e,t,n=qr()){let r=ft(t),i=(o)=>Sg(o,n),s=[];for(let o of t.terminals){if(o==="iterm2"){s.push(`Write ${i(rs(n))} — a "ttheme · <palette>" profile per palette`);continue}if(o==="windows-terminal"){if(t.wtHome)s.push(`Write ${Po(t.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(s.push(`Write ${i(rr(o,e,n))}/${pe("*")} — a theme file per palette`),o==="warp"){let c=Oo(n,e);if(r&&Tt(c))s.push(`Edit ${i(c)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(o==="wezterm"){let c=Qr(e,n);if(xi(qt(c),"")!==void 0)s.push(`Edit ${i(c)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(o==="alacritty"){let c=or(e);if(Bi(qt(c),void 0)!==void 0)s.push(`Edit ${i(c)} — a ttheme block: general.import`);continue}let a=ir(o,e),u=qt(a);s.push(`Edit ${i(a)} — a ttheme block: ${Zk(vg(o,e,r,u))}`)}return s}function Ng(e,t,n=qr()){let r=[],i=(s)=>Sg(s,n);if(t.includes("ghostty")){let s=ir("ghostty",e);if(nr(qt(s),"command"))r.push(`${i(s)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(t.includes("kitty")){let s=qt(ir("kitty",e));if(nr(s,"window_logo_scale")||nr(s,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(t.includes("alacritty")){let s=or(e);if(ag(qt(s)))r.push(`${i(s)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function To(e,t,n,r,i=qr()){let s=[],o=_e(e,t,!1).palettes;for(let a of n)for(let u of o.filter((c)=>r.includes(c.name)))for(let{file:c}of yg(a,kt(u))){let l=Pe(rr(a,e,i),c);if(Tt(l))Yu(l,{force:!0}),s.push(l)}return s}function an(e,t,n,r){let i=sn(),s=Boolean(ft(n))!==Boolean(ft(r)),o=s?ns(r,i):r;return it(e,t,o),yt(e,o),s&&sr(o,i)&&i.running()}import{existsSync as ay,mkdirSync as Ag,readFileSync as Hg,statSync as uy}from"node:fs";import{homedir as cy}from"node:os";import{dirname as ly,join as Pg}from"node:path";import{existsSync as Xu,mkdirSync as Bu,readFileSync as Zr,writeFileSync as Dk}from"node:fs";import{homedir as ey}from"node:os";import{dirname as xu,join as zr}from"node:path";import{spawn as zk}from"node:child_process";var Vk=30000,Xk=3,Bk=97,xk=`ObjC.import('Vision')
382
382
  ObjC.import('CoreImage')
383
383
  ObjC.import('CoreGraphics')
384
384
  function run(argv) {
@@ -397,11 +397,11 @@ function run(argv) {
397
397
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
398
398
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
399
399
  if (!written) throw new Error('write failed')
400
- }`;function Qr(){return process.platform==="darwin"}function Ro(e){return e>=Zk&&e<=zk}function ts(e,t,n){return new Promise((r,i)=>{let s=Qk("osascript",["-l","JavaScript","-e",Vk,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Yk)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
401
- `).at(-1)||`osascript exited ${a}`))})})}var vg=90000;function Xu(e,t){let n=je(e),r=Eu(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&ee.some((a)=>a.key===s)?[{site:s,id:Number(o),...vu(n,i)}]:[]});return r.length>0?r:void 0}function xk(e,t){let n=new Set(nt(je(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(Dn(r)))}function Ln(e,t){let n=new Set((t??[]).map((r)=>Dn(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(Dn(r)))}}function Dk(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 ey(e,t,n,r,i){let s=ee.find((g)=>g.key===n.site);if(!s)throw Error(`no site called ${n.site}`);let o=await Pi(s,n.id,i);if(!o)throw Error("the post is gone");if(!Ds(s,o,Zn(process.env.TTHEME_FIND_RATING))||xs(o,Rr(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let a=Dt(o);if(!a)throw Error("too large to use");let u=Zr(Nt(s),"orig",`${n.id}.${a.ext}`),c;if(Zu(u))c=new Uint8Array(Yr(u));else c=await to(s,a.file,i),zu(Vu(u),{recursive:!0}),Xk(u,c);let l=qn(c,$t),h=!1;if(Bt(l)===0&&Qr()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let g=Zr(Nt(s),"cut",`${n.id}.png`);try{if(!Zu(g))zu(Vu(g),{recursive:!0}),await ts(u,g,i);let m=qn(new Uint8Array(Yr(g)),$t);if(Ro(Bt(m)))l=m,h=!0}catch{}}let f=Dk(t);uo(e,f,Tr(f,t.signatureSlots),l,{site:s.key,id:n.id,ext:a.ext,bytes:c,from:`${s.name} ${n.id} ${s.pageUrl(n.id)}`,cut:h},{width:0,height:0},jr(e));let d=Eu(e,t.name).find((g)=>g.key===Dn(n));if(d)Mu(je(e),d,n,r,Bk())}async function ty(e,t,n,r){let i=0;for(let o of xk(e,t)){let a=`${t.name} · ${ee.find((u)=>u.key===o.site)?.name??o.site} ${o.id}`;try{await ey(e,t,o,n,AbortSignal.timeout(vg)),r(` ▣ ${a}`),i++}catch(u){r(` ▢ ${a} — ${u instanceof Error?u.message:String(u)}`)}}let[s]=t.pictures??[];if(i>0&&s)pd(e,t.name,Dn(s));return i}async function Yt(e,t,n){let r=0;for(let i of t)r+=await ty(e,i,!n.includes("iterm2"),(s)=>console.log(s));if(r>0)Qt(e)}function Eg(e,t,n){if(t.width!==e.width||t.height!==e.height)return!1;for(let r=0;r<e.width*e.height;r++)e.data[r*4+3]=t.data[r*4+n]??0;return!0}async function ny(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Zr(Or(),n??"local","cut",`${r??e}.png`);if(!Zu(i)){if(!Qr())return;zu(Vu(i),{recursive:!0}),await ts(t,i,AbortSignal.timeout(vg))}return qn(new Uint8Array(Yr(i)),$t)}function ry(e,t){try{return Bt(Kn(new Uint8Array(Yr(Zr(e,`${t.stem}.png`)))))>0}catch{return!1}}async function Mg(e,t,n,r,i,s,o){let a=je(e),u=nt(a).palettes[t]?.pictures.find((h)=>h.key===n);if(!u?.original)return null;let c=Zr(a,u.original),l=qn(new Uint8Array(Yr(c)),$t);if(u.cut){if(!Eg(l,Kn(new Uint8Array(Yr(Zr(a,u.cut)))),0))return null;return co(e,t,u,l,r,i,s,o,!1)}if(u.tone===void 0&&Bt(l)===0&&ry(a,u)){let h=await ny(n,c);if(!h||!Eg(l,h,3))return null;return co(e,t,u,l,r,i,s,o,!0)}return co(e,t,u,l,r,i,s,o,!1)}var uy=86400000,cy=3600000,xu=5000;function Bu(){return Sg(process.env.XDG_STATE_HOME??Sg(oy(),".local","state"),"ttheme","markets.json")}function cn(){try{let e=JSON.parse(Rg(Bu(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Ig(e,t){let n=cn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Ng(ay(Bu()),{recursive:!0}),be(Bu(),`${JSON.stringify(n,null,2)}
402
- `)}function ns(e,t){let n=t===Z?Pt(e):lt(t)?Ot(e,t):void 0;try{return n?sy(n).mtimeMs:void 0}catch{return}}function ly(e,t,n,r){return e&&(t===void 0||r-t>=uy)&&(n===void 0||r-n>=cy)}function Du(e,t,n=Date.now()){let r=cn();return Ze(t.markets).filter((i)=>ly(On(i,t.updates),ns(e,i),r[i]?.at,n))}async function hy(e,t,n){try{return await Gi(vd(e),Hu,t,n)}catch(r){if(r instanceof bo)throw Error(`${Se(e)} has no ${Wt} — is the repository public, and has its action run?`);throw r}}async function zr(e,t,n){if(e===Z){let s=await Gi(Ad,Kt,t,n);return{source:e,id:Z,manifest:s,entries:s.palettes}}let r=await hy(e,t,n),i=Gr(e,r);return{source:e,id:i,manifest:r,entries:po(r,i)}}function Vr(e,t){if(t.source===Z){mo(e,t.manifest);return}Ng(Nu(e),{recursive:!0}),be(Ot(e,t.source),`${JSON.stringify(t.manifest,null,2)}
403
- `)}function Xr(e,t){try{if(t===Z)return Kt(Rg(Pt(e),"utf8")).palettes;let n=Tn(e,t);return po(n,Gr(t,n))}catch{return[]}}function fy(e,t){let n=new Map(e.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(t.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,s])=>n.has(i)&&n.get(i)!==s).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function rs(e,t,n){let r=Xr(e,t),i;try{i=await zr(t,n)}catch(s){throw Ig(t,s.message),s}return Vr(e,i),Ig(t,void 0),{source:t,id:i.id,...t===Z?{version:i.manifest.version}:{},count:De(i.entries).length,change:fy(r,i.entries)}}function st(e){return`${e} palette${e===1?"":"s"}`}function is(e,t=Date.now()){let n=Math.floor(Math.max(0,t-e)/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Og({added:e,changed:t,gone:n}){return[e.length>0?`${e.length} new`:"",t.length>0?`${t.length} changed`:"",n.length>0?`${n.length} gone`:""].filter(Boolean).join(", ")}function ec(e){let t=Og(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${st(e.count)}${t?` (${t})`:""}`}function tc(e){return Og(e.change)?`Updated ${ec(e)}`:void 0}async function Oo(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=Le(e,!1);rt(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await Yt(e,_e(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ln(c,u.get(c.name))),t.terminals)}async function Fg(e=ue()){try{if(!iy(Rn(e)))return;let t=ie(e),n=Du(e,t);if(n.length===0)return;let r=sn(e),i=(await Promise.allSettled(n.map((o)=>rs(e,o,xu)))).flatMap((o)=>o.status==="fulfilled"?[o.value]:[]),s=i.flatMap((o)=>tc(o)??[]);if(s.length===0)return;for(let o of s)console.log(o);await Oo(e,t,r,i)}catch{return}}var Ug=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,gy=["add","remove","search","init"];function ic(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function my(){try{let e=dy("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Ug.test(e)?e:void 0}catch{return}}async function py(e,t){if(t.author)return t.author;let n=my();if(!n){if(!ic())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 Ma({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Ug.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(Be(r))throw Error("no handle given");n=r.toLowerCase()}return yt(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Br(e,t){if(t===Z)return Z;return Ae(t)?ht(Jt(t)):Gr(t,Tn(e,t))}function Po(e,t){try{return Br(e,t)}catch{return}}function _g(e){return Me(e)??Z}function To(e){return Le(e).palettes.filter((t)=>Me(t.name)===void 0)}function wy(e){let t=ln(import.meta.dirname,"..","dist","manifest.json");return Fo(t)?Kt(rc(t,"utf8")).palettes:To(e)}function ss(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==On(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function Cg(e,t,n,r){return t.find((i)=>i!==n&&!Lr(i,n)&&Po(e,i)===r)}function nc(e,t,n,r){let i=ie(e),s=Ze(i.markets),o=Cg(e,s,t,n);if(o)throw Error(`${n} already names the market at ${Se(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};yt(e,ss(i,s.includes(t)?s:[...s,t],a))}async function by(e){if(!ic())return!1;let t=await Ht({message:`Update ${e} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(Be(t))throw Error("no answer given — nothing was added");return t}async function $y(e,t,n){let r=await zr(n),i=ie(e),s=Ze(i.markets),o=Cg(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${Se(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return yt(e,ss(i,s.map((l)=>l===t?n:l),c)),Vr(e,r),r}async function sc(e,t){let n=Fn(t),r=Ze(ie(e).markets);if(r.includes(n))return console.log(`${Se(n)} is already added`),{source:n,id:Br(e,n),fresh:!1};let i=lt(n)?r.find((u)=>lt(u)&&Lr(u,n)):void 0;if(i){let u=await $y(e,i,n);return console.log(`Moved ${u.id} to ${Iu(n)??"its default branch"} · ${Se(n)} — ${st(De(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Ae(n)){let u=ht(Jt(n));nc(e,n,u);let c=Pn(n,u,To(e)).length;return console.log(`Added ${u} · ${Se(n)} — ${st(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await zr(n),o=n===Z?void 0:await by(s.id);nc(e,n,s.id,o),Vr(e,s);let a=st(De(s.entries).length);return console.log(n===Z?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${Se(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function ky(e){let t=ue(),{source:n,id:r,fresh:i}=await sc(t,e);if(!i)return;if(Ae(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===Z)console.log("\n`ttheme browse` picks them");else console.log(`
404
- \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function oc(e,t){if(t===Z)Tg(Pt(e),{force:!0});else if(lt(t))Tg(Ot(e,t),{force:!0})}function ac(e){return`${st(e.length)} installed from it keep${e.length===1?"s":""} working: ${e.join(", ")} — \`ttheme remove\` drops ${e.length===1?"it":"them"}`}function yy(e){let t=ue(),n=ie(t),r=Ze(n.markets),i=r.find((c)=>Po(t,c)===e)??r.find((c)=>c===jg(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Po(t,i),o=n.palettes.filter((c)=>_g(c)===s),a=r.filter((c)=>c!==i),u=ss(n,a,n.updates??{});if(yt(t,u),oc(t,i),rt(t,Le(t),u),console.log(`Removed ${s??e} · ${Se(i)}`),o.length>0)console.log(ac(o))}function jg(e){try{return Fn(e)}catch{return}}function Ey(e,t){try{if(t===Z)return De(Kt(rc(Pt(e),"utf8")).palettes).length;if(Ae(t))return Pn(t,Br(e,t),To(e),!1).length;return Tn(e,t).palettes.length}catch{return}}function uc(e,t,n=cn(),r=Date.now()){if(Ae(t))return"read in place";let i=n[t],s=ns(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${is(i.at,r)}`;return s===void 0?"never updated":`updated ${is(s,r)}`}function vy(){let e=ue(),t=ie(e),n=Ze(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=cn(),i=n.map((a)=>{let u=Po(e,a)??"?",c=Ey(e,a),l=t.palettes.filter((f)=>_g(f)===u).length,h=Ae(a)?[]:[`auto-update ${On(a,t.updates)?"on":"off"}`];return{name:u,where:Se(a),note:[c===void 0?"Unreadable":st(c),...l>0?[`${l} installed`]:[],...h,uc(e,a,r)].join(" · ")}}),s=Math.max(...i.map((a)=>a.name.length)),o=Math.max(...i.map((a)=>a.where.length));for(let a of i)console.log(` ${a.name.padEnd(s)} ${a.where.padEnd(o)} ${a.note}`)}function cc(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function lc(e,t){let n=encodeURIComponent(`topic:${Ar}${e?` ${e}`:""}`);try{let{items:r}=await Gi(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof $o)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function My(e){let t=ue(),n=await lc(e);if(n.length===0){console.log(`No repository carries the ${Ar} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(Ze(ie(t).markets).map(Nn)),i=n.map((o)=>{let a=cc(o);return{arg:a,added:r.has(a),stars:`★${o.stargazers_count}`,about:o.description??""}}),s=Math.max(...i.map((o)=>o.arg.length));for(let o of i)console.log(` ${o.added?"●":"○"} ${o.arg.padEnd(s)} ${o.stars.padStart(5)} ${o.about}`);console.log("\n`ttheme market add <name>` adds one")}var Sy=`name: ttheme market
400
+ }`;function Yr(){return process.platform==="darwin"}function Ao(e){return e>=Xk&&e<=Bk}function is(e,t,n){return new Promise((r,i)=>{let s=zk("osascript",["-l","JavaScript","-e",xk,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Vk)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
401
+ `).at(-1)||`osascript exited ${a}`))})})}var Fg=90000;function Du(e,t){let n=je(e),r=Su(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&ee.some((a)=>a.key===s)?[{site:s,id:Number(o),...Iu(n,i)}]:[]});return r.length>0?r:void 0}function ty(e,t){let n=new Set(rt(je(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(xn(r)))}function Hn(e,t){let n=new Set((t??[]).map((r)=>xn(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(xn(r)))}}function ny(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 ry(e,t,n,r,i){let s=ee.find((g)=>g.key===n.site);if(!s)throw Error(`no site called ${n.site}`);let o=await Pi(s,n.id,i);if(!o)throw Error("the post is gone");if(!so(s,o,Yn(process.env.TTHEME_FIND_RATING))||io(o,Rr(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let a=Dt(o);if(!a)throw Error("too large to use");let u=zr(Nt(s),"orig",`${n.id}.${a.ext}`),c;if(Xu(u))c=new Uint8Array(Zr(u));else c=await ao(s,a.file,i),Bu(xu(u),{recursive:!0}),Dk(u,c);let l=Kn(c,$t),h=!1;if(Bt(l)===0&&Yr()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let g=zr(Nt(s),"cut",`${n.id}.png`);try{if(!Xu(g))Bu(xu(g),{recursive:!0}),await is(u,g,i);let m=Kn(new Uint8Array(Zr(g)),$t);if(Ao(Bt(m)))l=m,h=!0}catch{}}let f=ny(t);go(e,f,Ar(f,t.signatureSlots),l,{site:s.key,id:n.id,ext:a.ext,bytes:c,from:`${s.name} ${n.id} ${s.pageUrl(n.id)}`,cut:h},{width:0,height:0},Wr(e));let d=Su(e,t.name).find((g)=>g.key===xn(n));if(d)Nu(je(e),d,n,r,ey())}async function iy(e,t,n,r){let i=0;for(let o of ty(e,t)){let a=`${t.name} · ${ee.find((u)=>u.key===o.site)?.name??o.site} ${o.id}`;try{await ry(e,t,o,n,AbortSignal.timeout(Fg)),r(` ▣ ${a}`),i++}catch(u){r(` ▢ ${a} — ${u instanceof Error?u.message:String(u)}`)}}let[s]=t.pictures??[];if(i>0&&s)kd(e,t.name,xn(s));return i}async function Yt(e,t,n){let r=0;for(let i of t)r+=await iy(e,i,!n.includes("iterm2"),(s)=>console.log(s));if(r>0)Qt(e)}function Rg(e,t,n){if(t.width!==e.width||t.height!==e.height)return!1;for(let r=0;r<e.width*e.height;r++)e.data[r*4+3]=t.data[r*4+n]??0;return!0}async function sy(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=zr(Fr(),n??"local","cut",`${r??e}.png`);if(!Xu(i)){if(!Yr())return;Bu(xu(i),{recursive:!0}),await is(t,i,AbortSignal.timeout(Fg))}return Kn(new Uint8Array(Zr(i)),$t)}function oy(e,t){try{return Bt(Jn(new Uint8Array(Zr(zr(e,`${t.stem}.png`)))))>0}catch{return!1}}async function Og(e,t,n,r,i,s,o){let a=je(e),u=rt(a).palettes[t]?.pictures.find((h)=>h.key===n);if(!u?.original)return null;let c=zr(a,u.original),l=Kn(new Uint8Array(Zr(c)),$t);if(u.cut){if(!Rg(l,Jn(new Uint8Array(Zr(zr(a,u.cut)))),0))return null;return mo(e,t,u,l,r,i,s,o,!1)}if(u.tone===void 0&&Bt(l)===0&&oy(a,u)){let h=await sy(n,c);if(!h||!Rg(l,h,3))return null;return mo(e,t,u,l,r,i,s,o,!0)}return mo(e,t,u,l,r,i,s,o,!1)}var hy=86400000,fy=3600000,tc=5000;function ec(){return Pg(process.env.XDG_STATE_HOME??Pg(cy(),".local","state"),"ttheme","markets.json")}function un(){try{let e=JSON.parse(Hg(ec(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Tg(e,t){let n=un();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Ag(ly(ec()),{recursive:!0}),be(ec(),`${JSON.stringify(n,null,2)}
402
+ `)}function ss(e,t){let n=t===Z?Pt(e):lt(t)?Ft(e,t):void 0;try{return n?uy(n).mtimeMs:void 0}catch{return}}function dy(e,t,n,r){return e&&(t===void 0||r-t>=hy)&&(n===void 0||r-n>=fy)}function nc(e,t,n=Date.now()){let r=un();return Ze(t.markets).filter((i)=>dy(Nn(i,t.updates),ss(e,i),r[i]?.at,n))}async function gy(e,t,n){try{return await Ci(Nd(e),Uu,t,n)}catch(r){if(r instanceof vo)throw Error(`${Se(e)} has no ${Wt} — is the repository public, and has its action run?`);throw r}}async function Vr(e,t,n){if(e===Z){let s=await Ci(Cd,Kt,t,n);return{source:e,id:Z,manifest:s,entries:s.palettes}}let r=await gy(e,t,n),i=Ur(e,r);return{source:e,id:i,manifest:r,entries:yo(r,i)}}function Xr(e,t){if(t.source===Z){ko(e,t.manifest);return}Ag(Ou(e),{recursive:!0}),be(Ft(e,t.source),`${JSON.stringify(t.manifest,null,2)}
403
+ `)}function Br(e,t){try{if(t===Z)return Kt(Hg(Pt(e),"utf8")).palettes;let n=Pn(e,t);return yo(n,Ur(t,n))}catch{return[]}}function my(e,t){let n=new Map(e.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(t.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,s])=>n.has(i)&&n.get(i)!==s).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function os(e,t,n){let r=Br(e,t),i;try{i=await Vr(t,n)}catch(s){throw Tg(t,s.message),s}return Xr(e,i),Tg(t,void 0),{source:t,id:i.id,...t===Z?{version:i.manifest.version}:{},count:De(i.entries).length,change:my(r,i.entries)}}function st(e){return`${e} palette${e===1?"":"s"}`}function as(e,t=Date.now()){let n=Math.floor(Math.max(0,t-e)/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Lg({added:e,changed:t,gone:n}){return[e.length>0?`${e.length} new`:"",t.length>0?`${t.length} changed`:"",n.length>0?`${n.length} gone`:""].filter(Boolean).join(", ")}function rc(e){let t=Lg(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${st(e.count)}${t?` (${t})`:""}`}function ic(e){return Lg(e.change)?`Updated ${rc(e)}`:void 0}async function Ho(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=Le(e,!1);it(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await Yt(e,_e(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Hn(c,u.get(c.name))),t.terminals)}async function Gg(e=ue()){try{if(!ay(In(e)))return;let t=ie(e),n=nc(e,t);if(n.length===0)return;let r=rn(e),i=(await Promise.allSettled(n.map((o)=>os(e,o,tc)))).flatMap((o)=>o.status==="fulfilled"?[o.value]:[]),s=i.flatMap((o)=>ic(o)??[]);if(s.length===0)return;for(let o of s)console.log(o);await Ho(e,t,r,i)}catch{return}}var Wg=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ky=["add","remove","search","init"];function uc(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function yy(){try{let e=py("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Wg.test(e)?e:void 0}catch{return}}async function Ey(e,t){if(t.author)return t.author;let n=yy();if(!n){if(!uc())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 Ra({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Wg.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(Be(r))throw Error("no handle given");n=r.toLowerCase()}return yt(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function xr(e,t){if(t===Z)return Z;return Ae(t)?ht(Jt(t)):Ur(t,Pn(e,t))}function Lo(e,t){try{return xr(e,t)}catch{return}}function Jg(e){return $e(e)??Z}function Go(e){return Le(e).palettes.filter((t)=>$e(t.name)===void 0)}function vy(e){let t=ar(import.meta.dirname,"..","dist","manifest.json");return sc(t)?Kt(ac(t,"utf8")).palettes:Go(e)}function us(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==Nn(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function Kg(e,t,n,r){return t.find((i)=>i!==n&&!Gr(i,n)&&Lo(e,i)===r)}function oc(e,t,n,r){let i=ie(e),s=Ze(i.markets),o=Kg(e,s,t,n);if(o)throw Error(`${n} already names the market at ${Se(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};yt(e,us(i,s.includes(t)?s:[...s,t],a))}async function My(e){if(!uc())return!1;let t=await Ht({message:`Update ${e} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(Be(t))throw Error("no answer given — nothing was added");return t}async function Sy(e,t,n){let r=await Vr(n),i=ie(e),s=Ze(i.markets),o=Kg(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${Se(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return yt(e,us(i,s.map((l)=>l===t?n:l),c)),Xr(e,r),r}async function cc(e,t){let n=Rn(t),r=Ze(ie(e).markets);if(r.includes(n))return console.log(`${Se(n)} is already added`),{source:n,id:xr(e,n),fresh:!1};let i=lt(n)?r.find((u)=>lt(u)&&Gr(u,n)):void 0;if(i){let u=await Sy(e,i,n);return console.log(`Moved ${u.id} to ${Fu(n)??"its default branch"} · ${Se(n)} — ${st(De(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Ae(n)){let u=ht(Jt(n));oc(e,n,u);let c=On(n,u,Go(e)).length;return console.log(`Added ${u} · ${Se(n)} — ${st(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await Vr(n),o=n===Z?void 0:await My(s.id);oc(e,n,s.id,o),Xr(e,s);let a=st(De(s.entries).length);return console.log(n===Z?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${Se(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function Iy(e){let t=ue(),{source:n,id:r,fresh:i}=await cc(t,e);if(!i)return;if(Ae(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===Z)console.log("\n`ttheme browse` picks them");else console.log(`
404
+ \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function lc(e,t){if(t===Z)_g(Pt(e),{force:!0});else if(lt(t))_g(Ft(e,t),{force:!0})}function hc(e){return`${st(e.length)} installed from it keep${e.length===1?"s":""} working: ${e.join(", ")} — \`ttheme remove\` drops ${e.length===1?"it":"them"}`}function Ny(e){let t=ue(),n=ie(t),r=Ze(n.markets),i=r.find((c)=>Lo(t,c)===e)??r.find((c)=>c===qg(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Lo(t,i),o=n.palettes.filter((c)=>Jg(c)===s),a=r.filter((c)=>c!==i),u=us(n,a,n.updates??{});if(yt(t,u),lc(t,i),it(t,Le(t),u),console.log(`Removed ${s??e} · ${Se(i)}`),o.length>0)console.log(hc(o))}function qg(e){try{return Rn(e)}catch{return}}function Ry(e,t){try{if(t===Z)return De(Kt(ac(Pt(e),"utf8")).palettes).length;if(Ae(t))return On(t,xr(e,t),Go(e),!1).length;return Pn(e,t).palettes.length}catch{return}}function fc(e,t,n=un(),r=Date.now()){if(Ae(t))return"read in place";let i=n[t],s=ss(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${as(i.at,r)}`;return s===void 0?"never updated":`updated ${as(s,r)}`}function Fy(){let e=ue(),t=ie(e),n=Ze(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=un(),i=n.map((a)=>{let u=Lo(e,a)??"?",c=Ry(e,a),l=t.palettes.filter((f)=>Jg(f)===u).length,h=Ae(a)?[]:[`auto-update ${Nn(a,t.updates)?"on":"off"}`];return{name:u,where:Se(a),note:[c===void 0?"Unreadable":st(c),...l>0?[`${l} installed`]:[],...h,fc(e,a,r)].join(" · ")}}),s=Math.max(...i.map((a)=>a.name.length)),o=Math.max(...i.map((a)=>a.where.length));for(let a of i)console.log(` ${a.name.padEnd(s)} ${a.where.padEnd(o)} ${a.note}`)}function dc(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function gc(e,t){let n=encodeURIComponent(`topic:${Hr}${e?` ${e}`:""}`);try{let{items:r}=await Ci(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof Mo)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function Oy(e){let t=ue(),n=await gc(e);if(n.length===0){console.log(`No repository carries the ${Hr} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(Ze(ie(t).markets).map(Sn)),i=n.map((o)=>{let a=dc(o);return{arg:a,added:r.has(a),stars:`★${o.stargazers_count}`,about:o.description??""}}),s=Math.max(...i.map((o)=>o.arg.length));for(let o of i)console.log(` ${o.added?"●":"○"} ${o.arg.padEnd(s)} ${o.stars.padStart(5)} ${o.about}`);console.log("\n`ttheme market add <name>` adds one")}var Py=`name: ttheme market
405
405
 
406
406
  on:
407
407
  push:
@@ -416,57 +416,57 @@ jobs:
416
416
  runs-on: ubuntu-latest
417
417
  steps:
418
418
  - uses: kecan0406/ttheme/market@v1
419
- `;function Wg({name:e}){return`ttheme-${e}`}function Iy(e,t){Pg(rn(e),{recursive:!0}),Pg(ln(e,".github","workflows"),{recursive:!0}),Jg(e,t,[]),be(ln(e,".github","workflows","ttheme.yml"),Sy),be(ln(e,"README.md"),`# ${ht(t)}
419
+ `;function Qg({name:e}){return`ttheme-${e}`}function Ty(e,t){Ug(bo(e),{recursive:!0}),Ug(ar(e,".github","workflows"),{recursive:!0}),Yg(e,t,[]),be(ar(e,".github","workflows","ttheme.yml"),Py),be(ar(e,"README.md"),`# ${ht(t)}
420
420
 
421
421
  A [ttheme](https://github.com/kecan0406/ttheme) market:
422
422
 
423
423
  \`\`\`sh
424
- ttheme market add ${t.owner}/${Wg(t)}
424
+ ttheme market add ${t.owner}/${Qg(t)}
425
425
  ttheme browse
426
426
  \`\`\`
427
- `)}function Jg(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Hi(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};be(ln(e,Wt),`${JSON.stringify(a,null,2)}
428
- `)}function Kg(e){return jt(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function qg(){if(!ic())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Ma({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>Kg((t??"").toLowerCase())});if(Be(e))throw Error("no market name given");return e.toLowerCase()}async function Qg(e,t){let n=tr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===jg(t));if(!o)throw Error(`${t} is not one of your local markets — \`ttheme market init ${t}\` makes it one`);return o}let[r,...i]=n;if(r&&i.length===0)return r;if(r)throw Error(`you have ${n.length} local markets — --in names one: ${n.map((o)=>o.name).join(", ")}`);let s=await qg();return Yg(e,Ru(e,s),s)}async function Yg(e,t,n){let r=!Fo(ln(t,Wt)),i;if(r){let o=Kg(n);if(o)throw Error(`the market name ${n} ${o}`);if(Fo(t)&&Lg(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await py(e,ie(e)),name:n},Iy(t,i)}else i=Jt(t);let s=ht(i);return nc(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${Se(t)}`),{dir:t,...i,id:s}}function Ag(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function Ny(e){let t=ue(),n=e&&!Ag(e)?e.toLowerCase():e?Gg(Fn(e)).toLowerCase():await qg(),r=e&&Ag(e)?Fn(e):Ru(t,n),i=await Yg(t,r,n),s=`${i.owner}/${Wg(i)}`;console.log(`
429
- \`ttheme new <palette> --from <palette>\` puts palettes in it — others see them once it is on GitHub:
427
+ `)}function Yg(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Li(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};be(ar(e,Wt),`${JSON.stringify(a,null,2)}
428
+ `)}function Zg(e){return jt(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function zg(){if(!uc())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Ra({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>Zg((t??"").toLowerCase())});if(Be(e))throw Error("no market name given");return e.toLowerCase()}async function Vg(e,t){let n=er(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===qg(t));if(!o)throw Error(`${t} is not one of your local markets — \`ttheme market init ${t}\` makes it one`);return o}let[r,...i]=n;if(r&&i.length===0)return r;if(r)throw Error(`you have ${n.length} local markets — --in names one: ${n.map((o)=>o.name).join(", ")}`);let s=await zg();return Xg(e,Pu(e,s),s)}async function Xg(e,t,n){let r=!sc(ar(t,Wt)),i;if(r){let o=Zg(n);if(o)throw Error(`the market name ${n} ${o}`);if(sc(t)&&wy(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await Ey(e,ie(e)),name:n},Ty(t,i)}else i=Jt(t);let s=ht(i);return oc(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${Se(t)}`),{dir:t,...i,id:s}}function Cg(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function Ay(e){let t=ue(),n=e&&!Cg(e)?e.toLowerCase():e?by(Rn(e)).toLowerCase():await zg(),r=e&&Cg(e)?Rn(e):Pu(t,n),i=await Xg(t,r,n),s=`${i.owner}/${Qg(i)}`;console.log(`
429
+ \`ttheme new <palette> --from <palette>\` puts palettes in it, and a folder under palettes/ shelves them in a catalog — others see them once it is on GitHub:
430
430
 
431
431
  cd ${Se(r)}
432
432
  git init -b main && git add -A && git commit -m "${i.id}"
433
433
  gh repo create ${s} --public --source . --push
434
- gh repo edit ${s} --add-topic ${Ar}
434
+ gh repo edit ${s} --add-topic ${Hr}
435
435
 
436
- Its action rebuilds ${Wt} on every push; then \`ttheme market add ${s}\` works anywhere`)}function Ry(e){let t=e?Fn(e):process.cwd(),n=Jt(t),r=ht(n),i=wy(ue()),s=rn(t),o=(Fo(s)?Lg(s).sort():[]).filter((l)=>l.endsWith(".toml")),a=[],u=[];for(let l of o){let h=Gg(l,".toml");try{a.push({...Ft(`${r}/${h}`,rc(ln(s,l),"utf8"),i),name:h})}catch(f){u.push(` ${ln("palettes",l)}: ${f.message}`)}}if(u.length>0)return console.error(`${u.length} palettes cannot be read — the index was left as it was:
437
- ${u.join(`
438
- `)}`),1;let c=a.map(Rt);for(let l of c){let f=Li(l).filter((d)=>d.startsWith(" ✗"));console.log(` ${l.name}${f.length>0?`
439
- ${f.join(`
440
- `)}`:" passes the gate"}`)}return Jg(t,n,c),console.log(`
441
- ${r} · ${st(c.length)} → ${ln(t,Wt)}`),0}async function Zg(e,t){switch(e){case void 0:vy();return;case"add":await ky(Hg(e,t));return;case"remove":yy(Hg(e,t));return;case"search":await My(t);return;case"init":await Ny(t);return;case"build":return Ry(t);default:throw Error(`unknown market action ${e} — ${gy.join(", ")}, or none to list them`)}}function Hg(e,t){if(!t)throw Error(e==="add"?"market add takes a repository or a folder: ttheme market add alice/ttheme-dust":"market remove takes a market name — `ttheme market` lists them");return t}function zg(e,t){let n=Br(e,t);return`${n} — ${st(Pn(t,n,To(e),!1).length)}, read in place`}function Ao(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??""].some((r)=>r.toLowerCase().includes(n))}function Vg(e,t,n){let r=n.trim(),i=[],s=new Set;for(let o of e){if(o.default||s.has(o.group))continue;s.add(o.group);let a=e.filter((l)=>!l.default&&l.group===o.group),u=r?a.filter((l)=>Ao(l,r)):a;if(r&&u.length===0)continue;let c=r.length>0||t.has(o.group);if(i.push({kind:"group",name:o.group,native:o.native,lead:a.find((l)=>l.lead)??o,expanded:c,count:u.length}),c)i.push(...u.map((l)=>({kind:"palette",entry:l})))}return i}function Oy(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||Ao(i,n))).map((i)=>i.group));return Vg(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Fy(e){return e.includes("@")}function Py(e){let t=e.findIndex((n)=>n.kind==="group"&&Fy(n.name));return t>0&&e.slice(0,t).some((n)=>n.kind==="group")?[...e.slice(0,t),{kind:"rule"},...e.slice(t)]:e}function Ty(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var Gn="\x1B[0m",os="\x1B[2m",as="\x1B[1m",ur="\x1B[22m",hc="\x1B[36m",fc="\x1B[33m";function Ho(e){return e==="decode"||e==="glitch"?e:"typewriter"}class us{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(e){this.picked=e.picked,this.scope=e.scope??"palette",this.maxItems=e.maxItems??12,this.color=e.color??!0,this.onFocus=e.onFocus,this.load(e.entries),this.rebuild("first")}load(e){this.entries=e,this.named=e.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.namePad=Math.max(0,...this.named.map((t)=>t.name.length))}setEntries(e){this.load(e),this.rebuild("stay")}setFilter(e){if(e!==this.filter)this.filter=e,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(e){let t=this.scope==="palette"?this.filter.trim():"";return this.named.filter((n)=>n.group===e&&(t===""||Ao(n,t)))}everyone(e){return e.flatMap((t)=>t.kind==="group"?this.members(t.name):[])}pick(){let e=this.rows[this.cursor],t=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(t.length===0)return;let n=t.some((r)=>!this.picked.has(r));for(let r of t)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(e){return this.members(e).filter((t)=>this.picked.has(t.name)).length}pickedCount(){if(this.scope==="palette")return this.named.filter((e)=>this.picked.has(e.name)).length;return this.series.filter((e)=>this.members(e).every((t)=>this.picked.has(t.name))).length}total(){return this.scope==="series"?this.series.length:this.named.length}matched(){let e=this.filter.trim();if(this.scope==="series")return this.rows.filter((t)=>t.kind==="group").length;return e?this.named.filter((t)=>Ao(t,e)).length:this.named.length}sync(){let e=this.rows[this.cursor],t=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(t&&t.name!==this.lastFocused)this.lastFocused=t.name,this.onFocus?.(t)}rebuild(e){let t=this.rows[this.cursor],n=this.scope==="series"?Oy(this.entries,this.filter):Vg(this.entries,this.expanded,this.filter);this.rows=n.length>0?Py([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[Ty(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=(o)=>t?.kind==="palette"?o.kind==="palette"&&o.entry.name===t.entry.name:e==="stay"&&t!==void 0&&o.kind===t.kind&&("name"in o?o.name:"")===("name"in t?t.name:""),s=t?this.rows.findIndex(i):-1;this.cursor=s===-1?r:s}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 t=this.cursor+e;if(this.rows[t]?.kind==="rule")t+=e;if(t>=0&&t<this.rows.length)this.cursor=t;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.filter||this.scope==="series")return;let t=this.rows[this.cursor];if(t?.kind==="group"){if(e!==t.expanded)this.toggle(t.name)}else if(t?.kind==="palette"&&!e&&!t.entry.default){let n=t.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()}}window(){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 e=this.rows.slice(this.top,this.top+this.maxItems);return{lines:e.map((t,n)=>this.renderRow(t,this.top+n===this.cursor)),below:this.rows.length-this.top-e.length}}renderRow(e,t){if(e.kind==="rule")return` ${this.color?`${os}${"── Markets ──────────"}${Gn}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="group"?e.lead:void 0,r=this.color&&t&&n!==void 0,i=(d)=>this.color?`${os}${d}${ur}`:d,s=(d)=>this.color?`${as}${d}${ur}`:d,o=(d)=>this.color?` ${Jl(lo(d),r?pn(d.foreground):"\x1B[39m")}`:"",a=t?r?`${pn(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(d)=>r?`${a}${Fs(n.selection,n.foreground)} ${d} ${Gn}`:`${a} ${d}`;if(e.kind==="all"){let d=this.everyone(this.rows).every((g)=>this.picked.has(g.name))?"●":"○";return u(`${d} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let d=this.pickedIn(e.name)===e.count?"●":"○",g=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${d} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i(g)}`)}if(e.kind==="group"){let d=this.rows[this.cursor],g=d?.kind==="palette"&&d.entry.group===e.name?d.entry:void 0,m=this.color&&g?`${as}${pn(g.cursor)}${e.name}${ur}\x1B[39m`:s(e.name),$=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${$}`)}let c=e.entry,l=this.picked.has(c.name)?"●":"○",h=this.color?c.name.padEnd(this.namePad):c.name,f=t?s(h):h;return u(` ${l} ${f}${o(c)}`)}}function dc(e){let t=e.named[Math.floor(Math.random()*e.named.length)],n=e.series[Math.floor(Math.random()*e.series.length)];return t&&n?`${t.name} | ${n}`:""}class Lo{fx;make;redraw;roller;example="";step=0;seed=0;timer;constructor(e,t,n){this.fx=e,this.make=t,this.redraw=n,this.roll(),this.roller=setInterval(()=>{this.roll(),this.step=8,this.redraw()},3000),this.roller.unref?.()}stop(){clearInterval(this.roller),clearTimeout(this.timer)}roll(){let e=this.make();this.example=e.length>30?`${e.slice(0,29)}…`:e,this.seed=Math.floor(Math.random()*997)}text(){if(this.step===0)return this.example;if(!this.timer)this.timer=setTimeout(()=>{this.timer=void 0,this.step-=1,this.redraw()},60),this.timer.unref?.();let e=Math.floor(this.example.length*(8-this.step)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let t=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.seed)%3<e||n(r)?r:t[Math.floor(Math.random()*t.length)]??r).join("")}}class gc extends pt{picked;list;scope;color;hint;lastInput="";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.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new us({entries:e.entries,picked:this.picked,scope:this.scope,...e.maxItems===void 0?{}:{maxItems:e.maxItems},color:this.color,...e.onFocus?{onFocus:e.onFocus}:{}}),this.hint=new Lo(e.fx??"typewriter",()=>dc(this.list),()=>this.output.emit("resize")),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(t)=>{if(t==="up")this.list.move(-1);else if(t==="down")this.list.move(1);else if(t==="left")this.list.fold(!1);else if(t==="right")this.list.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.list.setFilter(t)}),this.on("key",(t,n)=>{if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(d)=>this.color?`${os}${d}${Gn}`:d,t=(d)=>this.color?`${hc}${d}${Gn}`:d,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((d)=>`${t("│")} ${d}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",h=this.scope==="series"?"continue":"install",f=this.state==="error"?`${t("└")} ${this.color?`${fc}${this.error}${Gn}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${h} · esc cancel`)}`;return[r,s,...u,c,f].join(`
442
- `)}}var cs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],mc=34,Ay=72,Hy=94,pc={title:"",lines:[],brief:""};function Go(e){let t=e.trim();if(t!==Z&&!t.includes("/")&&!t.startsWith("~"))return;try{return Fn(t)}catch{return}}function Ly(e){return e.charAt(0).toUpperCase()+e.slice(1)}class wc extends pt{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new us({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new us({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Lo(e.fx??"typewriter",()=>dc(this.tab==="installed"?this.mine:this.catalog),()=>this.redraw()),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(n)=>{if(this.asking)return;if(n==="up"||n==="down")this.move(n==="up"?-1:1);else if(n==="left"||n==="right")this.side(n==="right")}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.filters[this.tab]=n,this.list()?.setFilter(n)}),this.on("key",(n,r)=>this.key(n,r));for(let n of e.due)this.update(n)}_isActionKey(e){return e==="\t"||e===" "||this.asking!==void 0&&e!==void 0}_shouldSubmit(){return this.asking===void 0}async idle(){await Promise.allSettled([...this.inflight])}result(){let e=new Set(this.entries().map((t)=>t.name));return{picked:new Set([...this.picked].filter((t)=>e.has(t))),adds:[...this.adds.values()],removes:[...this.removes],auto:Object.fromEntries(this.want),refreshed:this.refreshed}}key(e,t){if(this.asking){if(t?.name==="escape")this.asking=void 0,Object.assign(t,{name:"answered",sequence:""});else if(e&&/^[yn]$/i.test(e))this.answer(e.toLowerCase()==="y");return}if(t?.name==="tab")this.switchTab(t.shift?-1:1);else if(t?.name==="space")this.activate();else if(t?.ctrl&&t.name==="r"){let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!this.adds.has(n.market.source))this.update(n.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(e,t){if(this.tab===e&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(t)}track(e){this.inflight.add(e);let t=()=>this.inflight.delete(e);return e.then(t,t),e}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((e)=>!this.removes.has(e.source)),...this.adds.values()]}entries(){let e=this.active().flatMap((i)=>i.entries),t=new Set(e.map((i)=>i.name)),n=new Map,r=this.markets.filter((i)=>this.removes.has(i.source)).flatMap((i)=>i.entries);for(let i of[...this.kept,...r])if(this.installed.has(i.name)&&!t.has(i.name))n.set(i.name,i);return this.order([...e,...n.values()])}mineOf(e){return e.filter((t)=>this.installed.has(t.name))}reload(){let e=this.entries();this.catalog.setEntries(e),this.mine.setEntries(this.mineOf(e))}switchTab(e){let t=cs.findIndex((i)=>i.tab===this.tab),n=cs[(t+e+cs.length)%cs.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(e){let t=this.list();if(t){t.move(e);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((s)=>s.kind==="rule"):this.problemRows().map(()=>!1),i=this.cursor[n]+e;if(r[i])i+=e;if(i>=0&&i<r.length)this.cursor[n]=i}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!Ae(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>Lr(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Ae(e)||e===Z)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!Go(e)?e:void 0)).then((t)=>{this.searching=!1,this.repos=t,this.redraw()},(t)=>{this.searching=!1,this.searchError=t.message,this.redraw()})}marketRows(){let e=this.filters.markets.trim().toLowerCase(),t=(...o)=>e===""||o.some((a)=>a.toLowerCase().includes(e)),n=[...this.markets,...this.adds.values()],r=n.filter((o)=>t(o.id,o.shown,o.source)).map((o)=>({kind:"market",market:o})),i=Go(this.filters.markets);if(i&&!n.some((o)=>Lr(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:cc(o)})).filter(({repo:o,source:a})=>t(a,o.description??""));if(s.length>0)r.push({kind:"rule"},...s.map(({repo:o,source:a})=>({kind:"repo",repo:o,source:a})));return r}marketRow(){let e=this.marketRows();return e[Math.min(this.cursor.markets,e.length-1)]}problemList(){let e=new Map([...this.markets,...this.adds.values()].map((t)=>[t.source,t.id]));return[...this.problems.filter((t)=>!(t.update&&t.source&&this.failed.has(t.source))),...[...this.failed].map(([t,n])=>({where:e.get(t)??t,message:n,source:t}))]}problemRows(){let e=this.filters.errors.trim().toLowerCase();return this.problemList().filter((t)=>e===""||`${t.where} ${t.message}`.toLowerCase().includes(e))}windowOf(e,t,n,r=()=>!1){let i=Math.min(this.cursor[t],Math.max(0,e.length-1));if(r(e[i]))i-=1;this.cursor[t]=i;let s=Math.min(this.top[t],i);if(i>=s+this.maxItems)s=i-this.maxItems+1;s=Math.max(0,Math.min(s,e.length-this.maxItems)),this.top[t]=s;let o=e.slice(s,s+this.maxItems);return{lines:o.map((a,u)=>n(a,s+u===i)),below:e.length-s-o.length}}dim(e){return this.color?`${os}${e}${ur}`:e}bold(e){return this.color?`${as}${e}${ur}`:e}warn(e){return this.color?`${fc}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${pn(e.cursor)}▌\x1B[39m ${Fs(e.selection,e.foreground)} ${n} ${Gn}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${Se(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!Go(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,t,`⌕ ${s}`)}let n=this.busy.get(e.source),r=this.known(e.source)?"●":"○";return this.lit(void 0,t,`${r} ${e.source} ${this.dim(`★${e.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(e,t){return this.lit(void 0,t,`${this.warn("✗")} ${e.where} ${this.dim(e.message)}`)}body(){let e=this.list();if(e){let n=this.filters[this.tab];return{...e.window(),empty:n?`No palettes match '${n}'`:this.tab==="installed"?"Nothing installed yet":"No palettes"}}if(this.tab==="markets")return{...this.windowOf(this.marketRows(),"markets",(n,r)=>this.marketLine(n,r),(n)=>n?.kind==="rule"),empty:""};let t=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:t?`No problems match '${t}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}counts(){let e=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",t=this.list();if(t)return`${e}${t.matched()}/${t.total()} · ${t.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((s)=>s.kind==="market").length,i=this.changes();return`${e}${r}/${n} markets${i>0?` · ${i} to apply`:""}`}return`${this.problemRows().length}/${this.problemList().length}`}searchText(){if(this.userInput)return`${this.userInput}_`;if(this.tab==="markets")return this.dim("Search… or add one: owner/repo");let e=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${e?` e.g. ${e}`:""}`)}tabBar(){return cs.map(({tab:e,title:t})=>{let n=e==="errors"?this.problemList().length:0,r=n>0?`${t} ${n}`:t;if(!this.color)return e===this.tab?`[${r}]`:` ${r} `;return e===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(e){let t=this.active().find((n)=>n.entries.some((r)=>r.name===e.name));if(!t)return"In no market you added";return t.source===Z?"The ttheme catalog":t.shown}paletteState(e){let t=this.picked.has(e.name),n=this.installed.has(e.name),r=t&&n?"Installed":t?"Will install":n?"Will remove":"Not installed";return this.startup===e.name?`${r} · Default`:r}paletteDetail(e,t){if(!e||e.kind==="rule")return pc;if(e.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(e.kind==="group"){let c=this.entries().filter((f)=>f.group===e.name&&!f.default),l=this.sourceOf(e.lead),h=`${st(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?it(e.native,t).map((f)=>this.dim(f)):[],...it(l,t),h],brief:`${l} · ${h}`}}let n=e.entry,r=this.sourceOf(n),i=Ui(n),s=`Gate ${Lt.length-i.length}/${Lt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=Me(n.name)?[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${as}${pn(n.cursor)}${n.name}${ur}\x1B[39m`:n.name,lines:[...it(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>it(c,t-2).map((l,h)=>`${h===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return pc;if(e.kind==="market"){let i=e.market,s=i.source===Z?"The ttheme catalog":i.shown,o=i.entries.filter((d)=>!d.default),a=o.filter((d)=>this.installed.has(d.name)).map((d)=>d.name),u=`${st(o.length)} · ${a.length} installed`,c=Ae(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??Ly(i.status),h=this.failed.get(i.source),f=this.adds.has(i.source)?["Will add"]:this.removes.has(i.source)?[a.length>0?`Will remove — ${a.join(", ")} stay${a.length===1?"s":""} installed`:"Will remove"]:this.want.has(i.source)?[`Auto-update turns ${this.want.get(i.source)?"on":"off"}`]:[];return{title:this.bold(i.id),lines:[...it(s,t),u,"",Ae(i.source)?c:`${c} ${this.dim("←→")}`,...Ae(i.source)?[]:[l],...h?it(h,t).map((d)=>this.warn(d)):[],...f.length>0?["",...f.flatMap((d)=>it(d,t))]:[]],brief:[s,c,...f,...Ae(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(Se(e.source)),lines:["Not added","",...it(i,t)],brief:i}}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...it(`Repositories with the ${Ar} topic`,t),...i&&!Go(i)?[`Matching "${i}"`]:[],"",...it(s,t)],brief:s}}let r=this.known(e.source)?"Added":this.busy.get(e.source)??this.failed.get(e.source)??"space adds it";return{title:this.bold(e.source),lines:[`★ ${e.repo.stargazers_count}`,...it(e.repo.description??"",t),"",...it(r,t)],brief:r}}detail(e){let t=this.list();if(t)return this.paletteDetail(t.focusedRow(),e);if(this.tab==="markets")return this.marketDetail(this.marketRow(),e);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:it(r.message,e),brief:r.message}:pc}footer(e,t){if(this.asking)return`${e("└")} Update ${this.asking.id} on its own when its author changes it? ${this.dim("y yes · n no · esc back")}`;let n={catalog:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],installed:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],markets:["tab switch","space add/remove","←→ auto-update",t?"ctrl+r update":""],errors:["tab switch","↑↓ move","type to filter"]}[this.tab];return`${e("└")} ${this.dim([...n.filter(Boolean),"enter apply","esc cancel"].join(" · "))}`}summary(){let e=this.changes();return`${this.catalog.pickedCount()} picked${e>0?` · ${e} market change${e===1?"":"s"}`:""}`}columns(){return this.output.columns??100}draw(){let e=(h)=>this.color?`${hc}${h}${Gn}`:h;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=Hy,r=n?Math.min(t-mc-4,Ay):t-1,{lines:i,below:s,empty:o}=this.body(),a=i.length>0?i.map((h)=>`${e("│")} ${h}`):[`${e("│")} ${this.dim(o)}`];while(a.length<this.maxItems)a.push(e("│"));let u=[`${e("◆")} ${this.tabBar()}`,ql(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?mc:r-2);return[...n?u.map((h,f)=>`${mn(h,r)} ${this.dim("│")} ${mn(f===0?c.title:c.lines[f-1]??"",mc,!1)}`):[...u.map((h)=>mn(h,r,!1)),mn(`${e("│")} ${this.dim(c.brief)}`,r,!1)],mn(this.footer(e,n),t-1,!1)].join(`
443
- `)}}import{existsSync as u1}from"node:fs";import{spawnSync as Jy}from"node:child_process";import{existsSync as xr,mkdirSync as Ky,mkdtempSync as qy,readFileSync as _o,rmSync as Qy,writeFileSync as Yy}from"node:fs";import{tmpdir as Zy}from"node:os";import{basename as zy,dirname as em,join as kc}from"node:path";var $c=5,Gy=6,Xg=0.05,Uy=[1,2,3,4,5,6,9,10,11,12,13,14],Bg=(e,t)=>(t-e+360)%360<=180?1:-1;function bc(e,t,n){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),s=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((l)=>l**3),[o,a,u]=s,c=[4.0767416621*o-3.3077115913*a+0.2309699292*u,-1.2684380046*o+2.6097574011*a-0.3413193965*u,-0.0041960863*o-0.7034186147*a+1.707614701*u];if(c.some((l)=>l<-0.0001||l>1.0001))return;return c.map((l)=>{let h=Math.min(1,Math.max(0,l));return Math.round(255*(h<=0.0031308?12.92*h:1.055*h**0.4166666666666667-0.055))})}function Uo(e,t,n){let r=0,i=t;if(bc(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(bc(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(bc(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function _y(e,t){let{l:n,c:r}=Mt(e);return Uo(n,r,(t+360)%360)}function Cy(e,t,n){let{l:r,c:i,h:s}=Mt(e),o=et(t)<0.18,a=(l)=>Uo(o?r+(1-r)*l:r*(1-l),i,s);if(ut(a(1),t)<n+Xg)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let h=(u+c)/2;if(ut(a(h),t)>=n+Xg)c=h;else u=h}return a(c)}function jy(e,t){let{l:n,c:r,h:i}=Mt(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(et(Uo(u,r,i))<=t-0.005)s=u;else o=u}return Uo(s,r,i)}function Wy(e,t,n){let r=mi[t],[i,s]=[Mt(e[t]),Mt(e[t+8])],o=(l,h)=>n.has(l)?[h]:Array.from({length:2*r.width+1},(f,d)=>(r.center-r.width+d+360)%360),a=(l,h,f)=>$r.every((d)=>{let g=(l>8?8:0)+d;if(g===l)return!0;let m=Mt(e[g]);return m.c<Oa||bn(m.h,h)>=Ls+1||Math.abs(m.l-f)>=Gs}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let h of o(t+8,s.h)){if(bn(l,h)>Wn-$c||!n.has(t+8)&&!a(t+8,h,s.l))continue;let f=bn(l,i.h)+bn(h,s.h);if(f<c)c=f,u=[l,h]}}return u}class xg{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,t,n){let r=this.get(e);if(n===r)return;if(this.moves.push({slot:e,rule:t,from:r,to:n}),e==="foreground")this.theme.foreground=n;else if(e==="selection")this.theme.selectionBackground=n;else this.theme.ansi[Number(e.slice(4))]=n}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,t,n){this.set(`ansi${e}`,t,_y(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Ts(this.theme)){let i=mi[kr(n)];this.rehue(n,"ansi-role",i.center+Bg(i.center,r)*(i.width-$c))}for(let{normal:n,gap:r}of As(this.theme)){if(r<=Wn)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Mt(this.theme.ansi[i]).h,a=Mt(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+Bg(o,a)*(Wn-$c))}let t=Us(this.theme);for(let[n,r]of Hs(this.theme)){let i=kr(t.has(r)?n:r),s=Wy(this.theme.ansi,i,t);if(s===void 0)continue;this.rehue(i,"distinct",s[0]),this.rehue(i+8,"distinct",s[1])}}readability(){let e=new Set(this.theme.waive),{background:t}=this.theme,n=(r,i,s,o=t)=>{if(e.has(r))return;for(let a of i)if(ut(this.get(a),o)<s)this.set(a,r,Cy(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",Uy.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&et(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",jy(this.get("ansi0"),0.15));n("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let t=this.moves.filter((i)=>i.slot===e),n=t[0].from,r=this.get(e);return n===r?[]:[{slot:e,rule:[...new Set(t.map((i)=>i.rule))].join(", "),from:n,to:r}]})}}function Dg(e){let t=new xg(e);for(let n=0;n<Gy;n++)if(t.readability(),t.roles(),Cs(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Cs(t.theme)}}function Vy(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function tm(e,t){if(e.includes("/"))return e;let n=tr(t,!1),r=n.filter((s)=>xr(kc(rn(s.dir),`${e}.toml`))),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function Xy(e,t,n){let r=ie(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)un(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))rt(e,t,r);return{state:r,fresh:i}}function By(e){let t=Math.max(0,...e.map((n)=>n.slot.length));return e.map((n)=>` ${n.slot.padEnd(t)} ${n.from} → ${n.to} ${n.rule}`)}function nm(e,t,n){let r=Od(t),i=Rt(Ft(r.name,Tu(r),n.palettes)),s=_e(e,n,!1).palettes.find((o)=>o.name===i.name);if(s&&JSON.stringify(s)!==JSON.stringify(i))throw Error(`${i.name} is already in ${Me(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)wo(e,[...sn(e),i]);return i.name}async function rm(e,t,n){let r=ue(),i=Le(r),s=ie(r),o=await Qg(r,n),a=e.includes("/")?e:`${o.id}/${e}`,u=jt(a);if(u)throw Error(`${a} ${u}`);if(Me(a)!==o.id)throw Error(`palettes in ${o.dir} are named ${o.id}/<palette> — ${a} belongs elsewhere`);let c=Fu(r,a);if(xr(c))throw Error(`${a} already exists — \`ttheme edit ${a}\` changes it`);let l=_e(r,i),h=t??an(s);if(!h)throw Error("--from names the palette to start from");let f=nr(l.palettes,h),d=Me(f.name)?f.base:f.default?void 0:f.name,{base:g,ansiSource:m,group:$,...w}=Pu(f,a,`kept from ${f.name}`),M=Xu(r,f.name)??f.pictures,y=Tu({...w,...d?{base:d}:{},...M?{pictures:M}:{}});Ft(a,y,i.palettes),Ky(em(c),{recursive:!0}),be(c,y);let{state:S}=Xy(r,i,[a]);console.log(` + ${a} from ${f.name}
444
- ${c}`),await Yt(r,_e(r,i).palettes.filter((p)=>p.name===a),S.terminals),console.log(`
445
- \`ttheme edit ${a}\` changes its colors · \`ttheme use ${a}\` wears it`)}function xy(e){let t=process.env.VISUAL||process.env.EDITOR||"vi",n=Jy("sh",["-c",`${t} "$1"`,"sh",e],{stdio:"inherit"});if(n.status!==0)throw Error(`${t} exited ${n.status??n.signal}`)}function Dy(e,t,n){let r=Rt(Ft(e,t,n.palettes));return Ui(r).length>0?Li(r).filter((i)=>i.startsWith(" ✗")):[]}async function im(e){let t=ue(),n=Le(t),r=ie(t),i=_e(t,n,!1),s=tm(e,t),o=Co(t,s),a=o&&xr(o)?s:i.palettes.some((g)=>g.name===e)?e:s,u=Co(t,a);if(!u||!xr(u)){let g=i.palettes.some((m)=>m.name===a);throw Error(g?`${a} is not one of yours — \`ttheme new <name> --from ${a}\` makes your own copy`:`no palette of yours called ${a} — \`ttheme new\` makes one`)}if(!Vy())throw Error("edit opens your editor — run it in a terminal");let c=_o(u,"utf8"),l=kc(qy(kc(Zy(),"ttheme-edit-")),zy(u));Yy(l,c);let h=[];try{for(;;){xy(l);let g=_o(l,"utf8");if(g===c){console.log("Nothing changed");return}try{h=Dy(a,g,n)}catch(m){console.log(`
436
+ Its action rebuilds ${Wt} on every push; then \`ttheme market add ${s}\` works anywhere`)}function Hy(e){let t=e?Rn(e):process.cwd(),n=Jt(t),r=ht(n),i=vy(ue()),s=new Map,o=[],a=[];for(let u of Fn(t))try{let c=Ui(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=Ot(`${r}/${u.slug}`,ac(u.path,"utf8"),i),h=Rt({...l,name:u.slug});o.push(u.catalog?{...h,catalog:u.catalog}:h)}catch(c){a.push(` ${$y(t,u.path)}: ${c.message}`)}if(a.length>0)return console.error(`${a.length} palettes cannot be read — the index was left as it was:
437
+ ${a.join(`
438
+ `)}`),1;for(let u of o){let l=_i(u).filter((f)=>f.startsWith(" ✗")),h=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${h}${l.length>0?`
439
+ ${l.join(`
440
+ `)}`:" passes the gate"}`)}return Yg(t,n,o),console.log(`
441
+ ${r} · ${st(o.length)} → ${ar(t,Wt)}`),0}async function Bg(e,t){switch(e){case void 0:Fy();return;case"add":await Iy(jg(e,t));return;case"remove":Ny(jg(e,t));return;case"search":await Oy(t);return;case"init":await Ay(t);return;case"build":return Hy(t);default:throw Error(`unknown market action ${e} — ${ky.join(", ")}, or none to list them`)}}function jg(e,t){if(!t)throw Error(e==="add"?"market add takes a repository or a folder: ttheme market add alice/ttheme-dust":"market remove takes a market name — `ttheme market` lists them");return t}function xg(e,t){let n=xr(e,t);return`${n} — ${st(On(t,n,Go(e),!1).length)}, read in place`}function ls(e,t){return`${e}/${t}`}function Dg(e){return $e(e.name)?Pr(e.name):e.name}function cs(e){return e.catalog!==void 0&&tm(e.group)?ls(e.group,e.catalog):void 0}function mc(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${ls(e.group,e.name)}`;return e?.kind??""}function Uo(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function em(e,t,n){let r=n.trim(),i=[],s=new Set,o=(a)=>({kind:"palette",entry:a});for(let a of e){if(a.default||s.has(a.group))continue;s.add(a.group);let u=e.filter((f)=>!f.default&&f.group===a.group),c=r?u.filter((f)=>Uo(f,r)):u;if(r&&c.length===0)continue;let l=r.length>0||t.has(a.group);if(i.push({kind:"group",name:a.group,native:a.native,lead:u.find((f)=>f.lead)??a,expanded:l,count:c.length}),!l)continue;let h=c.filter((f)=>cs(f)!==void 0);for(let f of new Set(h.map((d)=>d.catalog))){let d=h.filter((m)=>m.catalog===f),g=r.length>0||t.has(ls(a.group,f));if(i.push({kind:"catalog",group:a.group,name:f,lead:d[0],expanded:g,count:d.length}),g)i.push(...d.map(o))}i.push(...c.filter((f)=>cs(f)===void 0).map(o))}return i}function Ly(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||Uo(i,n))).map((i)=>i.group));return em(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function tm(e){return e.includes("@")}function Gy(e){let t=e.findIndex((n)=>n.kind==="group"&&tm(n.name));return t>0&&e.slice(0,t).some((n)=>n.kind==="group")?[...e.slice(0,t),{kind:"rule"},...e.slice(t)]:e}function Uy(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var Ln="\x1B[0m",hs="\x1B[2m",fs="\x1B[1m",ur="\x1B[22m",pc="\x1B[36m",wc="\x1B[33m";function _o(e){return e==="decode"||e==="glitch"?e:"typewriter"}class ds{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(e){this.picked=e.picked,this.scope=e.scope??"palette",this.maxItems=e.maxItems??12,this.color=e.color??!0,this.onFocus=e.onFocus,this.load(e.entries),this.rebuild("first")}load(e){this.entries=e,this.named=e.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.namePad=Math.max(0,...this.named.map((t)=>this.indent(t).length+Dg(t).length))}indent(e){return cs(e)===void 0?" ":" "}setEntries(e){this.load(e),this.rebuild("stay")}setFilter(e){if(e!==this.filter)this.filter=e,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(e,t){let n=this.scope==="palette"?this.filter.trim():"";return this.named.filter((r)=>r.group===e&&(t===void 0||r.catalog===t)&&(n===""||Uo(r,n)))}everyone(e){return e.flatMap((t)=>t.kind==="group"?this.members(t.name):[])}pick(){let e=this.rows[this.cursor],t=e?.kind==="palette"?[e.entry.name]:e?.kind==="group"?this.members(e.name).map((r)=>r.name):e?.kind==="catalog"?this.members(e.group,e.name).map((r)=>r.name):e?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(t.length===0)return;let n=t.some((r)=>!this.picked.has(r));for(let r of t)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(e,t){return this.members(e,t).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.named.filter((e)=>this.picked.has(e.name)).length;return this.series.filter((e)=>this.members(e).every((t)=>this.picked.has(t.name))).length}total(){return this.scope==="series"?this.series.length:this.named.length}matched(){let e=this.filter.trim();if(this.scope==="series")return this.rows.filter((t)=>t.kind==="group").length;return e?this.named.filter((t)=>Uo(t,e)).length:this.named.length}sync(){let e=this.rows[this.cursor],t=e?.kind==="palette"?e.entry:e?.kind==="group"&&this.scope==="series"?e.lead:void 0;if(t&&t.name!==this.lastFocused)this.lastFocused=t.name,this.onFocus?.(t)}rebuild(e){let t=this.rows[this.cursor],n=this.scope==="series"?Ly(this.entries,this.filter):em(this.entries,this.expanded,this.filter);this.rows=n.length>0?Gy([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[Uy(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=mc(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>mc(o)===i):-1;this.cursor=s===-1?r:s}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 t=this.cursor+e;if(this.rows[t]?.kind==="rule")t+=e;if(t>=0&&t<this.rows.length)this.cursor=t;this.sync()}toggle(e){if(this.expanded.has(e))this.expanded.delete(e);else this.expanded.add(e);this.rebuild("clamp")}climb(e,t){this.expanded.delete(e),this.rebuild("clamp"),this.cursor=Math.max(0,this.rows.findIndex((n)=>mc(n)===t)),this.sync()}fold(e){if(this.filter||this.scope==="series")return;let t=this.rows[this.cursor];if(t?.kind==="group"){if(e!==t.expanded)this.toggle(t.name)}else if(t?.kind==="catalog"){if(e!==t.expanded)this.toggle(ls(t.group,t.name));else if(!e)this.climb(t.group,`group ${t.group}`)}else if(t?.kind==="palette"&&!e&&!t.entry.default){let n=cs(t.entry);if(n===void 0)this.climb(t.entry.group,`group ${t.entry.group}`);else this.climb(n,`catalog ${n}`)}}window(){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 e=this.rows.slice(this.top,this.top+this.maxItems);return{lines:e.map((t,n)=>this.renderRow(t,this.top+n===this.cursor)),below:this.rows.length-this.top-e.length}}renderRow(e,t){if(e.kind==="rule")return` ${this.color?`${hs}${"── Markets ──────────"}${Ln}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(p)=>this.color?`${hs}${p}${ur}`:p,s=(p)=>this.color?`${fs}${p}${ur}`:p,o=(p)=>this.color?` ${Yl(po(p),r?gn(p.foreground):"\x1B[39m")}`:"",a=t?r?`${gn(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(p)=>r?`${a}${Gs(n.selection,n.foreground)} ${p} ${Ln}`:`${a} ${p}`;if(e.kind==="all"){let p=this.everyone(this.rows).every((E)=>this.picked.has(E.name))?"●":"○";return u(`${p} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let p=this.pickedIn(e.name)===e.count?"●":"○",E=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${p} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i(E)}`)}let c=this.rows[this.cursor],l=(p,E)=>this.color&&c?.kind==="palette"&&p?`${fs}${gn(c.entry.cursor)}${E}${ur}\x1B[39m`:s(E);if(e.kind==="group"){let p=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),E=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${p} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${E}`)}if(e.kind==="catalog"){let p=c?.kind==="palette"&&cs(c.entry)===ls(e.group,e.name),E=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(p,e.name)} ${E}`)}let h=e.entry,f=this.picked.has(h.name)?"●":"○",d=this.indent(h),g=Dg(h),m=this.color?g.padEnd(this.namePad-d.length):g,$=t?s(m):m;return u(`${d}${f} ${$}${o(h)}`)}}function bc(e){let t=e.named[Math.floor(Math.random()*e.named.length)],n=e.series[Math.floor(Math.random()*e.series.length)];return t&&n?`${t.name} | ${n}`:""}class Co{fx;make;redraw;roller;example="";step=0;seed=0;timer;constructor(e,t,n){this.fx=e,this.make=t,this.redraw=n,this.roll(),this.roller=setInterval(()=>{this.roll(),this.step=8,this.redraw()},3000),this.roller.unref?.()}stop(){clearInterval(this.roller),clearTimeout(this.timer)}roll(){let e=this.make();this.example=e.length>30?`${e.slice(0,29)}…`:e,this.seed=Math.floor(Math.random()*997)}text(){if(this.step===0)return this.example;if(!this.timer)this.timer=setTimeout(()=>{this.timer=void 0,this.step-=1,this.redraw()},60),this.timer.unref?.();let e=Math.floor(this.example.length*(8-this.step)/8);if(this.fx==="typewriter")return`${this.example.slice(0,e)}▏`;let t=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.seed)%3<e||n(r)?r:t[Math.floor(Math.random()*t.length)]??r).join("")}}class $c extends pt{picked;list;scope;color;hint;lastInput="";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.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new ds({entries:e.entries,picked:this.picked,scope:this.scope,...e.maxItems===void 0?{}:{maxItems:e.maxItems},color:this.color,...e.onFocus?{onFocus:e.onFocus}:{}}),this.hint=new Co(e.fx??"typewriter",()=>bc(this.list),()=>this.output.emit("resize")),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(t)=>{if(t==="up")this.list.move(-1);else if(t==="down")this.list.move(1);else if(t==="left")this.list.fold(!1);else if(t==="right")this.list.fold(!0)}),this.on("userInput",(t)=>{if(t!==this.lastInput)this.lastInput=t,this.list.setFilter(t)}),this.on("key",(t,n)=>{if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(d)=>this.color?`${hs}${d}${Ln}`:d,t=(d)=>this.color?`${pc}${d}${Ln}`:d,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((d)=>`${t("│")} ${d}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",h=this.scope==="series"?"continue":"install",f=this.state==="error"?`${t("└")} ${this.color?`${wc}${this.error}${Ln}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${h} · esc cancel`)}`;return[r,s,...u,c,f].join(`
442
+ `)}}var gs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],kc=34,_y=72,Cy=94,yc={title:"",lines:[],brief:""};function jo(e){let t=e.trim();if(t!==Z&&!t.includes("/")&&!t.startsWith("~"))return;try{return Rn(t)}catch{return}}function jy(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Ec extends pt{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new ds({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new ds({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Co(e.fx??"typewriter",()=>bc(this.tab==="installed"?this.mine:this.catalog),()=>this.redraw()),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(n)=>{if(this.asking)return;if(n==="up"||n==="down")this.move(n==="up"?-1:1);else if(n==="left"||n==="right")this.side(n==="right")}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.filters[this.tab]=n,this.list()?.setFilter(n)}),this.on("key",(n,r)=>this.key(n,r));for(let n of e.due)this.update(n)}_isActionKey(e){return e==="\t"||e===" "||this.asking!==void 0&&e!==void 0}_shouldSubmit(){return this.asking===void 0}async idle(){await Promise.allSettled([...this.inflight])}result(){let e=new Set(this.entries().map((t)=>t.name));return{picked:new Set([...this.picked].filter((t)=>e.has(t))),adds:[...this.adds.values()],removes:[...this.removes],auto:Object.fromEntries(this.want),refreshed:this.refreshed}}key(e,t){if(this.asking){if(t?.name==="escape")this.asking=void 0,Object.assign(t,{name:"answered",sequence:""});else if(e&&/^[yn]$/i.test(e))this.answer(e.toLowerCase()==="y");return}if(t?.name==="tab")this.switchTab(t.shift?-1:1);else if(t?.name==="space")this.activate();else if(t?.ctrl&&t.name==="r"){let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!this.adds.has(n.market.source))this.update(n.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(e,t){if(this.tab===e&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(t)}track(e){this.inflight.add(e);let t=()=>this.inflight.delete(e);return e.then(t,t),e}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((e)=>!this.removes.has(e.source)),...this.adds.values()]}entries(){let e=this.active().flatMap((i)=>i.entries),t=new Set(e.map((i)=>i.name)),n=new Map,r=this.markets.filter((i)=>this.removes.has(i.source)).flatMap((i)=>i.entries);for(let i of[...this.kept,...r])if(this.installed.has(i.name)&&!t.has(i.name))n.set(i.name,i);return this.order([...e,...n.values()])}mineOf(e){return e.filter((t)=>this.installed.has(t.name))}reload(){let e=this.entries();this.catalog.setEntries(e),this.mine.setEntries(this.mineOf(e))}switchTab(e){let t=gs.findIndex((i)=>i.tab===this.tab),n=gs[(t+e+gs.length)%gs.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(e){let t=this.list();if(t){t.move(e);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((s)=>s.kind==="rule"):this.problemRows().map(()=>!1),i=this.cursor[n]+e;if(r[i])i+=e;if(i>=0&&i<r.length)this.cursor[n]=i}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!Ae(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>Gr(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Ae(e)||e===Z)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!jo(e)?e:void 0)).then((t)=>{this.searching=!1,this.repos=t,this.redraw()},(t)=>{this.searching=!1,this.searchError=t.message,this.redraw()})}marketRows(){let e=this.filters.markets.trim().toLowerCase(),t=(...o)=>e===""||o.some((a)=>a.toLowerCase().includes(e)),n=[...this.markets,...this.adds.values()],r=n.filter((o)=>t(o.id,o.shown,o.source)).map((o)=>({kind:"market",market:o})),i=jo(this.filters.markets);if(i&&!n.some((o)=>Gr(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:dc(o)})).filter(({repo:o,source:a})=>t(a,o.description??""));if(s.length>0)r.push({kind:"rule"},...s.map(({repo:o,source:a})=>({kind:"repo",repo:o,source:a})));return r}marketRow(){let e=this.marketRows();return e[Math.min(this.cursor.markets,e.length-1)]}problemList(){let e=new Map([...this.markets,...this.adds.values()].map((t)=>[t.source,t.id]));return[...this.problems.filter((t)=>!(t.update&&t.source&&this.failed.has(t.source))),...[...this.failed].map(([t,n])=>({where:e.get(t)??t,message:n,source:t}))]}problemRows(){let e=this.filters.errors.trim().toLowerCase();return this.problemList().filter((t)=>e===""||`${t.where} ${t.message}`.toLowerCase().includes(e))}windowOf(e,t,n,r=()=>!1){let i=Math.min(this.cursor[t],Math.max(0,e.length-1));if(r(e[i]))i-=1;this.cursor[t]=i;let s=Math.min(this.top[t],i);if(i>=s+this.maxItems)s=i-this.maxItems+1;s=Math.max(0,Math.min(s,e.length-this.maxItems)),this.top[t]=s;let o=e.slice(s,s+this.maxItems);return{lines:o.map((a,u)=>n(a,s+u===i)),below:e.length-s-o.length}}dim(e){return this.color?`${hs}${e}${ur}`:e}bold(e){return this.color?`${fs}${e}${ur}`:e}warn(e){return this.color?`${wc}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${gn(e.cursor)}▌\x1B[39m ${Gs(e.selection,e.foreground)} ${n} ${Ln}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${Se(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!jo(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,t,`⌕ ${s}`)}let n=this.busy.get(e.source),r=this.known(e.source)?"●":"○";return this.lit(void 0,t,`${r} ${e.source} ${this.dim(`★${e.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(e,t){return this.lit(void 0,t,`${this.warn("✗")} ${e.where} ${this.dim(e.message)}`)}body(){let e=this.list();if(e){let n=this.filters[this.tab];return{...e.window(),empty:n?`No palettes match '${n}'`:this.tab==="installed"?"Nothing installed yet":"No palettes"}}if(this.tab==="markets")return{...this.windowOf(this.marketRows(),"markets",(n,r)=>this.marketLine(n,r),(n)=>n?.kind==="rule"),empty:""};let t=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:t?`No problems match '${t}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}counts(){let e=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",t=this.list();if(t)return`${e}${t.matched()}/${t.total()} · ${t.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((s)=>s.kind==="market").length,i=this.changes();return`${e}${r}/${n} markets${i>0?` · ${i} to apply`:""}`}return`${this.problemRows().length}/${this.problemList().length}`}searchText(){if(this.userInput)return`${this.userInput}_`;if(this.tab==="markets")return this.dim("Search… or add one: owner/repo");let e=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${e?` e.g. ${e}`:""}`)}tabBar(){return gs.map(({tab:e,title:t})=>{let n=e==="errors"?this.problemList().length:0,r=n>0?`${t} ${n}`:t;if(!this.color)return e===this.tab?`[${r}]`:` ${r} `;return e===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(e){let t=this.active().find((n)=>n.entries.some((r)=>r.name===e.name));if(!t)return"In no market you added";return t.source===Z?"The ttheme catalog":t.shown}paletteState(e){let t=this.picked.has(e.name),n=this.installed.has(e.name),r=t&&n?"Installed":t?"Will install":n?"Will remove":"Not installed";return this.startup===e.name?`${r} · Default`:r}paletteDetail(e,t){if(!e||e.kind==="rule")return yc;if(e.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(e.kind==="group"){let c=this.entries().filter((f)=>f.group===e.name&&!f.default),l=this.sourceOf(e.lead),h=`${st(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?et(e.native,t).map((f)=>this.dim(f)):[],...et(l,t),h],brief:`${l} · ${h}`}}if(e.kind==="catalog"){let c=this.entries().filter((f)=>f.group===e.group&&f.catalog===e.name),l=this.sourceOf(e.lead),h=`${st(c.length)} · ${c.filter((f)=>this.installed.has(f.name)).length} installed`;return{title:this.bold(e.name),lines:[e.group,...et(l,t),h],brief:`${e.group} · ${h}`}}let n=e.entry,r=this.sourceOf(n),i=ji(n),s=`Gate ${Lt.length-i.length}/${Lt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=$e(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${fs}${gn(n.cursor)}${n.name}${ur}\x1B[39m`:n.name,lines:[...et(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>et(c,t-2).map((l,h)=>`${h===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return yc;if(e.kind==="market"){let i=e.market,s=i.source===Z?"The ttheme catalog":i.shown,o=i.entries.filter((d)=>!d.default),a=o.filter((d)=>this.installed.has(d.name)).map((d)=>d.name),u=`${st(o.length)} · ${a.length} installed`,c=Ae(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??jy(i.status),h=this.failed.get(i.source),f=this.adds.has(i.source)?["Will add"]:this.removes.has(i.source)?[a.length>0?`Will remove — ${a.join(", ")} stay${a.length===1?"s":""} installed`:"Will remove"]:this.want.has(i.source)?[`Auto-update turns ${this.want.get(i.source)?"on":"off"}`]:[];return{title:this.bold(i.id),lines:[...et(s,t),u,"",Ae(i.source)?c:`${c} ${this.dim("←→")}`,...Ae(i.source)?[]:[l],...h?et(h,t).map((d)=>this.warn(d)):[],...f.length>0?["",...f.flatMap((d)=>et(d,t))]:[]],brief:[s,c,...f,...Ae(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(Se(e.source)),lines:["Not added","",...et(i,t)],brief:i}}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...et(`Repositories with the ${Hr} topic`,t),...i&&!jo(i)?[`Matching "${i}"`]:[],"",...et(s,t)],brief:s}}let r=this.known(e.source)?"Added":this.busy.get(e.source)??this.failed.get(e.source)??"space adds it";return{title:this.bold(e.source),lines:[`★ ${e.repo.stargazers_count}`,...et(e.repo.description??"",t),"",...et(r,t)],brief:r}}detail(e){let t=this.list();if(t)return this.paletteDetail(t.focusedRow(),e);if(this.tab==="markets")return this.marketDetail(this.marketRow(),e);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:et(r.message,e),brief:r.message}:yc}footer(e,t){if(this.asking)return`${e("└")} Update ${this.asking.id} on its own when its author changes it? ${this.dim("y yes · n no · esc back")}`;let n={catalog:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],installed:["tab switch","↑↓ move","←→ fold","space pick",t?"type to filter":""],markets:["tab switch","space add/remove","←→ auto-update",t?"ctrl+r update":""],errors:["tab switch","↑↓ move","type to filter"]}[this.tab];return`${e("└")} ${this.dim([...n.filter(Boolean),"enter apply","esc cancel"].join(" · "))}`}summary(){let e=this.changes();return`${this.catalog.pickedCount()} picked${e>0?` · ${e} market change${e===1?"":"s"}`:""}`}columns(){return this.output.columns??100}draw(){let e=(h)=>this.color?`${pc}${h}${Ln}`:h;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=Cy,r=n?Math.min(t-kc-4,_y):t-1,{lines:i,below:s,empty:o}=this.body(),a=i.length>0?i.map((h)=>`${e("│")} ${h}`):[`${e("│")} ${this.dim(o)}`];while(a.length<this.maxItems)a.push(e("│"));let u=[`${e("◆")} ${this.tabBar()}`,zl(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?kc:r-2);return[...n?u.map((h,f)=>`${dn(h,r)} ${this.dim("│")} ${dn(f===0?c.title:c.lines[f-1]??"",kc,!1)}`):[...u.map((h)=>dn(h,r,!1)),dn(`${e("│")} ${this.dim(c.brief)}`,r,!1)],dn(this.footer(e,n),t-1,!1)].join(`
443
+ `)}}import{existsSync as dE}from"node:fs";import{spawnSync as Zy}from"node:child_process";import{existsSync as ms,mkdirSync as zy,mkdtempSync as Vy,readFileSync as Jo,rmSync as Xy,writeFileSync as By}from"node:fs";import{tmpdir as xy}from"node:os";import{basename as Dy,dirname as am,join as om}from"node:path";var Mc=5,Wy=6,nm=0.05,Jy=[1,2,3,4,5,6,9,10,11,12,13,14],rm=(e,t)=>(t-e+360)%360<=180?1:-1;function vc(e,t,n){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),s=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((l)=>l**3),[o,a,u]=s,c=[4.0767416621*o-3.3077115913*a+0.2309699292*u,-1.2684380046*o+2.6097574011*a-0.3413193965*u,-0.0041960863*o-0.7034186147*a+1.707614701*u];if(c.some((l)=>l<-0.0001||l>1.0001))return;return c.map((l)=>{let h=Math.min(1,Math.max(0,l));return Math.round(255*(h<=0.0031308?12.92*h:1.055*h**0.4166666666666667-0.055))})}function Wo(e,t,n){let r=0,i=t;if(vc(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(vc(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(vc(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function Ky(e,t){let{l:n,c:r}=Mt(e);return Wo(n,r,(t+360)%360)}function qy(e,t,n){let{l:r,c:i,h:s}=Mt(e),o=tt(t)<0.18,a=(l)=>Wo(o?r+(1-r)*l:r*(1-l),i,s);if(ut(a(1),t)<n+nm)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let h=(u+c)/2;if(ut(a(h),t)>=n+nm)c=h;else u=h}return a(c)}function Qy(e,t){let{l:n,c:r,h:i}=Mt(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(tt(Wo(u,r,i))<=t-0.005)s=u;else o=u}return Wo(s,r,i)}function Yy(e,t,n){let r=mi[t],[i,s]=[Mt(e[t]),Mt(e[t+8])],o=(l,h)=>n.has(l)?[h]:Array.from({length:2*r.width+1},(f,d)=>(r.center-r.width+d+360)%360),a=(l,h,f)=>$r.every((d)=>{let g=(l>8?8:0)+d;if(g===l)return!0;let m=Mt(e[g]);return m.c<Aa||pn(m.h,h)>=Ws+1||Math.abs(m.l-f)>=Js}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let h of o(t+8,s.h)){if(pn(l,h)>jn-Mc||!n.has(t+8)&&!a(t+8,h,s.l))continue;let f=pn(l,i.h)+pn(h,s.h);if(f<c)c=f,u=[l,h]}}return u}class im{theme;moves=[];constructor(e){this.theme={...e,ansi:[...e.ansi]}}set(e,t,n){let r=this.get(e);if(n===r)return;if(this.moves.push({slot:e,rule:t,from:r,to:n}),e==="foreground")this.theme.foreground=n;else if(e==="selection")this.theme.selectionBackground=n;else this.theme.ansi[Number(e.slice(4))]=n}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,t,n){this.set(`ansi${e}`,t,Ky(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of _s(this.theme)){let i=mi[kr(n)];this.rehue(n,"ansi-role",i.center+rm(i.center,r)*(i.width-Mc))}for(let{normal:n,gap:r}of Cs(this.theme)){if(r<=jn)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Mt(this.theme.ansi[i]).h,a=Mt(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+rm(o,a)*(jn-Mc))}let t=Ks(this.theme);for(let[n,r]of js(this.theme)){let i=kr(t.has(r)?n:r),s=Yy(this.theme.ansi,i,t);if(s===void 0)continue;this.rehue(i,"distinct",s[0]),this.rehue(i+8,"distinct",s[1])}}readability(){let e=new Set(this.theme.waive),{background:t}=this.theme,n=(r,i,s,o=t)=>{if(e.has(r))return;for(let a of i)if(ut(this.get(a),o)<s)this.set(a,r,qy(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",Jy.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&tt(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",Qy(this.get("ansi0"),0.15));n("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((e)=>e.slot))].flatMap((e)=>{let t=this.moves.filter((i)=>i.slot===e),n=t[0].from,r=this.get(e);return n===r?[]:[{slot:e,rule:[...new Set(t.map((i)=>i.rule))].join(", "),from:n,to:r}]})}}function sm(e){let t=new im(e);for(let n=0;n<Wy;n++)if(t.readability(),t.roles(),Qs(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Qs(t.theme)}}function eE(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function um(e,t){if(e.includes("/"))return e;let n=er(t,!1),r=n.filter((s)=>Fn(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function tE(e,t,n){let r=ie(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)an(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))it(e,t,r);return{state:r,fresh:i}}function nE(e){let t=Math.max(0,...e.map((n)=>n.slot.length));return e.map((n)=>` ${n.slot.padEnd(t)} ${n.from} → ${n.to} ${n.rule}`)}function cm(e,t,n){let r=Ld(t),i=Rt(Ot(r.name,Lu(r),n.palettes)),s=_e(e,n,!1).palettes.find((o)=>o.name===i.name);if(s&&JSON.stringify(s)!==JSON.stringify(i))throw Error(`${i.name} is already in ${$e(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)Eo(e,[...rn(e),i]);return i.name}async function lm(e,t,n){let r=ue(),i=Le(r),s=ie(r),o=await Vg(r,n),a=e.includes("/")?e:`${o.id}/${e}`,u=jt(a);if(u)throw Error(`${a} ${u}`);if($e(a)!==o.id)throw Error(`palettes in ${o.dir} are named ${o.id}/<palette> — ${a} belongs elsewhere`);let c=Au(r,a);if(ms(c))throw Error(`${a} already exists — \`ttheme edit ${a}\` changes it`);let l=_e(r,i),h=t??on(s);if(!h)throw Error("--from names the palette to start from");let f=tr(l.palettes,h),d=$e(f.name)?f.base:f.default?void 0:f.name,{base:g,ansiSource:m,group:$,...p}=Hu(f,a,`kept from ${f.name}`),E=Du(r,f.name)??f.pictures,y=Lu({...p,...d?{base:d}:{},...E?{pictures:E}:{}});Ot(a,y,i.palettes),zy(am(c),{recursive:!0}),be(c,y);let{state:S}=tE(r,i,[a]);console.log(` + ${a} from ${f.name}
444
+ ${c}`),await Yt(r,_e(r,i).palettes.filter((w)=>w.name===a),S.terminals),console.log(`
445
+ \`ttheme edit ${a}\` changes its colors · \`ttheme use ${a}\` wears it`)}function rE(e){let t=process.env.VISUAL||process.env.EDITOR||"vi",n=Zy("sh",["-c",`${t} "$1"`,"sh",e],{stdio:"inherit"});if(n.status!==0)throw Error(`${t} exited ${n.status??n.signal}`)}function iE(e,t,n){let r=Rt(Ot(e,t,n.palettes));return ji(r).length>0?_i(r).filter((i)=>i.startsWith(" ✗")):[]}async function hm(e){let t=ue(),n=Le(t),r=ie(t),i=_e(t,n,!1),s=um(e,t),o=Ko(t,s),a=o&&ms(o)?s:i.palettes.some((g)=>g.name===e)?e:s,u=Ko(t,a);if(!u||!ms(u)){let g=i.palettes.some((m)=>m.name===a);throw Error(g?`${a} is not one of yours — \`ttheme new <name> --from ${a}\` makes your own copy`:`no palette of yours called ${a} — \`ttheme new\` makes one`)}if(!eE())throw Error("edit opens your editor — run it in a terminal");let c=Jo(u,"utf8"),l=om(Vy(om(xy(),"ttheme-edit-")),Dy(u));By(l,c);let h=[];try{for(;;){rE(l);let g=Jo(l,"utf8");if(g===c){console.log("Nothing changed");return}try{h=iE(a,g,n)}catch(m){console.log(`
446
446
  ${m.message}
447
- `);let $=await Ht({message:`${a} cannot be read like this — edit it again?`});if(Be($)||!$){console.log("Kept the old one");return}continue}be(u,g);break}}finally{Qy(em(l),{recursive:!0,force:!0})}if(r.palettes.includes(a))rt(t,n,r);if(console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`),h.length>0)console.log(`
447
+ `);let $=await Ht({message:`${a} cannot be read like this — edit it again?`});if(Be($)||!$){console.log("Kept the old one");return}continue}be(u,g);break}}finally{Xy(am(l),{recursive:!0,force:!0})}if(r.palettes.includes(a))it(t,n,r);if(console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`),h.length>0)console.log(`
448
448
  It misses the contrast gate:
449
449
  ${h.join(`
450
450
  `)}
451
- \`ttheme check --fix ${a}\` suggests colors that pass`);let f=_e(t,n).palettes.find((g)=>g.name===a),d=Rt(Ft(a,c,n.palettes));if(f&&r.palettes.includes(a))await Yt(t,[Ln(f,d.pictures)],r.terminals)}function sm(e,t,n){return nr(e.palettes,e.palettes.some((r)=>r.name===t)?t:tm(t,n))}function om(e,t=!1){let n=ue(),r=Le(n),i=ie(n),s=sm(_e(n,r),e,n);if(console.log(`${s.name} · ${s.group}
452
- `),console.log(Li(s).join(`
453
- `)),Ui(s).length===0)return console.log(`
454
- Passes the gate`),0;let{theme:a,moves:u,left:c}=Dg(kt(s));if(u.length===0)return console.log(`
451
+ \`ttheme check --fix ${a}\` suggests colors that pass`);let f=_e(t,n).palettes.find((g)=>g.name===a),d=Rt(Ot(a,c,n.palettes));if(f&&r.palettes.includes(a))await Yt(t,[Hn(f,d.pictures)],r.terminals)}function fm(e,t,n){return tr(e.palettes,e.palettes.some((r)=>r.name===t)?t:um(t,n))}function dm(e,t=!1){let n=ue(),r=Le(n),i=ie(n),s=fm(_e(n,r),e,n);if(console.log(`${s.name} · ${s.group}
452
+ `),console.log(_i(s).join(`
453
+ `)),ji(s).length===0)return console.log(`
454
+ Passes the gate`),0;let{theme:a,moves:u,left:c}=sm(kt(s));if(u.length===0)return console.log(`
455
455
  No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
456
456
  ${c.length===0?"These colors pass":"These colors come closer"}:
457
- ${By(u).join(`
458
- `)}`);let l=Co(n,s.name);if(!l||!xr(l))return console.log(`
457
+ ${nE(u).join(`
458
+ `)}`);let l=Ko(n,s.name);if(!l||!ms(l))return console.log(`
459
459
  \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
460
- \`ttheme check --fix ${s.name}\` writes them`),1;if(be(l,Fd(_o(l,"utf8"),a)),i.palettes.includes(s.name))rt(n,r,i);return console.log(`
461
- Wrote ${l}`),c.length===0?0:1}function Co(e,t){let n=Me(t);return n&&tr(e,!1).some((r)=>r.id===n)?Fu(e,t):void 0}function e1(e,t){let n=Co(e,t.name),r=n&&xr(n)?Ft(t.name,_o(n,"utf8"),[t]).waiveReason:void 0,i=Xu(e,t.name)??t.pictures,{pictures:s,...o}=Pu(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function am(e){let t=ue(),n=Rd(e1(t,sm(_e(t,Le(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
462
- Anyone with ttheme wears it with: ttheme add ${nn}…`)}import{openSync as t1,writeSync as n1}from"node:fs";import{ReadStream as r1}from"node:tty";var i1=["10","11","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function Un(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Dr(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((t,n)=>`\x1B]4;${n};${t}\x1B\\`)].join("")}function s1(e){let t=new Map;for(let n of e.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=r??[];if(i&&s)t.set(i,s)}return t}function jo(e){return[...e].map(([t,n])=>`\x1B]${t};${n}\x1B\\`).join("")}var o1=`${i1.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`;function a1(e){return e.includes("\x1B[0n")}async function Wo(){let e,t;try{e=t1("/dev/tty","r+"),t=new r1(e),t.setRawMode(!0)}catch{return new Map}try{n1(e,o1);let n="";return await new Promise((r)=>{let i=setTimeout(r,120);t.on("data",(s)=>{if(n+=s.toString(),a1(n))clearTimeout(i),r()})}),s1(n)}finally{t.setRawMode(!1),t.destroy()}}function Jo(e){console.log(`
463
- ${e} palettes installed — open a new tab, or reload your terminal config`)}function c1(e,t){return e.map((n)=>{if(n.startsWith(nn))return n;let r=Me(n);if(r===void 0)return t===Z?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function um(e,t){let n=ue(),r=t?c1(e,(await sc(n,t)).id):e,i=Le(n),s=[...new Set(r.map((l)=>l.startsWith(nn)?nm(n,l,i):l))],o=ie(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){rt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};un(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Yt(n,_e(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Jo(c.palettes.length)}function cm(e){let t=ue(),n=Le(t),r=ie(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};un(t,n,r,o),No(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Jo(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function lm(e){let t=ue(),n=Le(t),r=ie(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=on(),a=Di({...s,startup:e},o);rt(t,n,a),yt(t,a);let u=or(a,o);console.log(dm(e,a.terminals,u&&o.running()).join(`
464
- `))}function hm(){let e=ue(),t=ie(e),n=an(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=un(e,Le(e),t,i);console.log(dm(n,i.terminals,s).join(`
465
- `))}function fm(){let e=ue(),t=ie(e);if(t.off){console.log("Already off");return}let n=un(e,Le(e),t,{...t,off:!0}),r=an(t);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 dm(e,t,n){let r=t.filter((s)=>s!=="iterm2"),i=r.length>0?[`Default ${e} · ${r.map((s)=>_r[s]).join(", ")} open new tabs with it once their config reloads`]:[];if(t.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 ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function gm(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of go(e,t.palettes,!1))n.set(r.name,"mine");return n}function mm(e,t=!1){let n=ue(),r=Le(n),i=new Set(ie(n).palettes),s=gm(n,r),o=De(_e(n,r).palettes),a=Xn(e?Gd(o,e):o),u=(h)=>s.get(h)??"kept";if(t){let h=a.map((f)=>({name:f.name,group:f.group,installed:i.has(f.name),source:u(f.name)}));console.log(JSON.stringify(h,null,2));return}let c=Math.max(...a.map((h)=>h.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let h of a)console.log(` ${i.has(h.name)?"●":"○"} ${h.name.padEnd(c)} ${h.group}${l[u(h.name)]}`);if(process.stdout.isTTY){let h=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
466
- ${h} palettes — ${a.filter((f)=>i.has(f.name)).length} installed`)}}async function pm(){let e=ue(),t=Hr(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");for(let a of t)try{console.log(` ${Ae(a)?zg(e,a):ec(await rs(e,a))}`)}catch(u){let c=Se(a);console.log(` ${c}: ${u.message} — kept the copy from the last update`)}if(!u1(Rn(e)))return;let n=Le(e),r=ie(e),i=gm(e,n),s=r.palettes.filter((a)=>!i.has(a)),o=new Map(sn(e).map((a)=>[a.name,a.pictures]));rt(e,n,r);for(let a of s)console.log(` ${a} left its market — ttheme keeps the copy you have`);await Yt(e,_e(e,n,!1).palettes.filter((a)=>r.palettes.includes(a.name)&&o.has(a.name)).map((a)=>Ln(a,o.get(a.name))),r.terminals)}async function yc(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Xn(e.palettes),s=process.stdout.isTTY===!0&&!Un(),o=s?await Wo():new Map,a=new gc({entries:i,scope:n,installed:t,required:r,color:!Un(),fx:Ho(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(Dr(c)):void 0}),u=await a.prompt();if(process.stdout.write(jo(o)),Be(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Ec(e,t,n,r){let i;try{i=Br(e,n)}catch{i=lt(n)?Nn(n):Se(n)}let s=[];if(Ae(n))try{s=Pn(n,i,Xr(e,Z),!1)}catch{s=[]}else s=Xr(e,n);return{source:n,id:i,shown:Se(n),entries:s,auto:On(n,t.updates),status:uc(e,n,r)}}function Ko(e){return e instanceof Error?e.message:String(e)}function f1(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of Ze(t.markets)){let a=i.get(o)??Se(o),u=n[o],c=ns(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${is(u.at)}: ${u.error}`});if(o===Z)try{Kt(bm(Pt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${Se(Pt(e))}: ${Ko(l)}`})}else if(lt(o))if(!wm(Ot(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{Tn(e,o)}catch(l){s.push({where:a,source:o,message:`${Se(Ot(e,o))}: ${Ko(l)}`})}else try{let l=ht(Jt(o)),h=rn(o),f=wm(h)?l1(h).filter((d)=>d.endsWith(".toml")):[];for(let d of f.sort())try{Ft(`${l}/${h1(d,".toml")}`,bm($m(h,d),"utf8"),Xr(e,Z))}catch(g){s.push({where:Se($m(h,d)),message:Ko(g)})}}catch(l){s.push({where:a,message:Ko(l)})}}return s}function d1(e,t,n,r){return{refresh:async(i)=>{if(Ae(i)){let o=Ec(e,t,i,cn());return{market:o,refreshed:{source:i,id:o.id,count:De(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await rs(e,i,xu);return{market:Ec(e,t,i,cn()),refreshed:s}},fetch:async(i)=>{if(Ae(i)){let o=ht(Jt(i));return{source:i,id:o,shown:Se(i),entries:Pn(i,o,Xr(e,Z),!1),auto:!1,status:"read in place"}}let s=await zr(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:Se(i),entries:s.entries,auto:On(i,{}),status:"not added yet"}},search:(i)=>lc(i,r)}}function g1(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==Z&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${st(De(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${Se(i)}`);let o=n.filter((a)=>(Me(a)??Z)===s);if(o.length>0)r.push(ac(o))}for(let[i,s]of Object.entries(e.auto)){let o=t.find((a)=>a.source===i);if(o&&!e.removes.includes(i))r.push(`${o.id} ${s?"updates on its own now":"no longer updates on its own"}`)}return r}async function m1(e,t,n,r,i){let s=ie(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let w of r.adds){let M=i.get(w.source);if(M)Vr(e,M)}for(let w of r.removes)oc(e,w);let a=[...Ze(s.markets).filter((w)=>!r.removes.includes(w)),...r.adds.map((w)=>w.source)],u=ss(s,a,{...s.updates,...r.auto});if(o)yt(e,u);let c=Le(e,!1),l=_e(e,c,!1).palettes.filter((w)=>r.picked.has(w.name)).map((w)=>w.name),h=s.palettes.filter((w)=>!l.includes(w)),f=l.filter((w)=>!s.palettes.includes(w));if(!o&&f.length===0&&h.length===0){await Oo(e,s,t,r.refreshed),console.log("Nothing changed");return}let d={...u,palettes:l};un(e,c,s,d),No(e,c,s.terminals,h);for(let w of g1(r,n,l))console.log(w);for(let w of f)console.log(` + ${w}`);for(let w of h)console.log(` - ${w}`);let g=new Map(t.map((w)=>[w.name,w.pictures])),m=new Set(r.refreshed.flatMap((w)=>[...w.change.changed,...w.change.gone])),$=_e(e,c,!1).palettes;if(await Yt(e,[...$.filter((w)=>f.includes(w.name)),...$.filter((w)=>l.includes(w.name)&&!f.includes(w.name)&&m.has(w.name)&&g.has(w.name)).map((w)=>Ln(w,g.get(w.name)))],d.terminals),f.length>0||h.length>0)Jo(d.palettes.length)}async function km(){let e=ue(),t=ie(e),n=sn(e),r=cn(),i=Ze(t.markets).map((m)=>Ec(e,t,m,r)),s=new Set(i.flatMap((m)=>m.entries.map(($)=>$.name))),o=n.filter((m)=>t.palettes.includes(m.name)&&!s.has(m.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0&&!Un(),l=c?await Wo():new Map,h=ft(t),f=new wc({markets:i,kept:o,installed:t.palettes,...h?{startup:h}:{},problems:f1(e,t,r,i),due:Du(e,t),io:d1(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Xn},color:!Un(),fx:Ho(process.env.TTHEME_FX),...c?{onFocus:(m)=>process.stdout.write(Dr(m))}:{}}),d=await f.prompt();process.stdout.write(jo(l)),u.abort(),await f.idle();let g=f.result();for(let m of g.refreshed){let $=tc(m);if($)console.log($)}if(Be(d)){await Oo(e,ie(e),n,g.refreshed),console.log("Nothing changed");return}await m1(e,n,i,g,a)}import{rmSync as ym}from"node:fs";import{basename as p1,join as ls}from"node:path";var Em=ls(import.meta.dirname,".."),w1=ls(Em,"themes"),vc=ls(Em,"dist"),qo=[Ci,Wi,_i,Bi,ji,xi,Xi],b1=[Wu,Su],vO=qo.map((e)=>e.id);async function Qo({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let t=e&&e.length>0?qo.filter((s)=>e.includes(s.id)):qo,n=Vf(w1),r=xl(n);if(r.length>0){for(let s of r)console.error(` ✗ ${s.theme} [${s.rule}] ${s.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(t.length===qo.length)ym(vc,{recursive:!0,force:!0});else for(let s of t)ym(ls(vc,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...b1]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(ls(vc,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>p1(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
467
- ${n.length} themes (${Xf(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as ME}from"node:child_process";import{createHash as Ep}from"node:crypto";import{existsSync as ti,mkdirSync as ms,mkdtempSync as SE,readFileSync as vp,rmSync as Cc,statSync as IE,writeFileSync as ps}from"node:fs";import{tmpdir as NE}from"node:os";import{dirname as ta,join as Vt}from"node:path";import{pathToFileURL as RE}from"node:url";import{execFile as $1}from"node:child_process";import{createHash as Im}from"node:crypto";import{existsSync as k1,mkdtempSync as y1,readFileSync as Vo,rmSync as E1,statSync as Nm,writeFileSync as Rm}from"node:fs";import{homedir as v1,tmpdir as M1}from"node:os";import{join as Yo}from"node:path";import{fileURLToPath as S1}from"node:url";import{promisify as I1}from"node:util";var Zt=I1($1),Zo=67108864,N1=4096,Ic=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],R1=["text/uri-list","text/plain;charset=utf-8","text/plain"],Mc=[...Ic,"text/uri-list","text/plain"];function O1(e){try{return Nm(e).isFile()}catch{return!1}}function F1(e){let t=[],n="",r="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r==="'")if(o==="'")r="";else n+=o;else if(r==='"')if(o==='"')r="";else if(o==="\\"&&'"\\$`'.includes(e[s+1]??""))n+=e[++s];else n+=o;else if(o==="\\"&&s+1<e.length)n+=e[++s],i=!0;else if(o==="'"||o==='"')r=o,i=!0;else if(/\s/.test(o)){if(i)t.push(n);n="",i=!1}else n+=o,i=!0}if(i)t.push(n);return t}function vm(e){if(/^file:\/\//i.test(e))try{return S1(e)}catch{return}if(e.startsWith("~/"))return Yo(v1(),e.slice(2));return e.startsWith("/")?e:void 0}function Xo(e,t=O1){let n=[];for(let r of e.replace(/\r\n?/g,`
460
+ \`ttheme check --fix ${s.name}\` writes them`),1;if(be(l,Gd(Jo(l,"utf8"),a)),i.palettes.includes(s.name))it(n,r,i);return console.log(`
461
+ Wrote ${l}`),c.length===0?0:1}function Ko(e,t){let n=$e(t);return n&&er(e,!1).some((r)=>r.id===n)?Au(e,t):void 0}function sE(e,t){let n=Ko(e,t.name),r=n&&ms(n)?Ot(t.name,Jo(n,"utf8"),[t]).waiveReason:void 0,i=Du(e,t.name)??t.pictures,{pictures:s,...o}=Hu(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function gm(e){let t=ue(),n=Hd(sE(t,fm(_e(t,Le(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
462
+ Anyone with ttheme wears it with: ttheme add ${nn}…`)}import{openSync as oE,writeSync as aE}from"node:fs";import{ReadStream as uE}from"node:tty";var cE=["10","11","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function Gn(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Dr(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((t,n)=>`\x1B]4;${n};${t}\x1B\\`)].join("")}function lE(e){let t=new Map;for(let n of e.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=r??[];if(i&&s)t.set(i,s)}return t}function qo(e){return[...e].map(([t,n])=>`\x1B]${t};${n}\x1B\\`).join("")}var hE=`${cE.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`;function fE(e){return e.includes("\x1B[0n")}async function Qo(){let e,t;try{e=oE("/dev/tty","r+"),t=new uE(e),t.setRawMode(!0)}catch{return new Map}try{aE(e,hE);let n="";return await new Promise((r)=>{let i=setTimeout(r,120);t.on("data",(s)=>{if(n+=s.toString(),fE(n))clearTimeout(i),r()})}),lE(n)}finally{t.setRawMode(!1),t.destroy()}}function Yo(e){console.log(`
463
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}function gE(e,t){return e.map((n)=>{if(n.startsWith(nn))return n;let r=$e(n);if(r===void 0)return t===Z?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function mm(e,t){let n=ue(),r=t?gE(e,(await cc(n,t)).id):e,i=Le(n),s=[...new Set(r.map((l)=>l.startsWith(nn)?cm(n,l,i):l))],o=ie(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){it(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};an(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Yt(n,_e(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Yo(c.palettes.length)}function pm(e){let t=ue(),n=Le(t),r=ie(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};an(t,n,r,o),To(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Yo(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function wm(e){let t=ue(),n=Le(t),r=ie(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=sn(),a=ns({...s,startup:e},o);it(t,n,a),yt(t,a);let u=sr(a,o);console.log(km(e,a.terminals,u&&o.running()).join(`
464
+ `))}function bm(){let e=ue(),t=ie(e),n=on(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=an(e,Le(e),t,i);console.log(km(n,i.terminals,s).join(`
465
+ `))}function $m(){let e=ue(),t=ie(e);if(t.off){console.log("Already off");return}let n=an(e,Le(e),t,{...t,off:!0}),r=on(t);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 km(e,t,n){let r=t.filter((s)=>s!=="iterm2"),i=r.length>0?[`Default ${e} · ${r.map((s)=>Cr[s]).join(", ")} open new tabs with it once their config reloads`]:[];if(t.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 ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function ym(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of $o(e,t.palettes,!1))n.set(r.name,"mine");return n}function Em(e,t=!1){let n=ue(),r=Le(n),i=new Set(ie(n).palettes),s=ym(n,r),o=De(_e(n,r).palettes),a=Vn(e?Jd(o,e):o),u=(h)=>s.get(h)??"kept";if(t){let h=a.map((f)=>({name:f.name,group:f.group,...f.catalog?{catalog:f.catalog}:{},installed:i.has(f.name),source:u(f.name)}));console.log(JSON.stringify(h,null,2));return}let c=Math.max(...a.map((h)=>h.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let h of a){let f=h.catalog?`${h.group} / ${h.catalog}`:h.group;console.log(` ${i.has(h.name)?"●":"○"} ${h.name.padEnd(c)} ${f}${l[u(h.name)]}`)}if(process.stdout.isTTY){let h=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
466
+ ${h} palettes — ${a.filter((f)=>i.has(f.name)).length} installed`)}}async function vm(){let e=ue(),t=Lr(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");for(let a of t)try{console.log(` ${Ae(a)?xg(e,a):rc(await os(e,a))}`)}catch(u){let c=Se(a);console.log(` ${c}: ${u.message} — kept the copy from the last update`)}if(!dE(In(e)))return;let n=Le(e),r=ie(e),i=ym(e,n),s=r.palettes.filter((a)=>!i.has(a)),o=new Map(rn(e).map((a)=>[a.name,a.pictures]));it(e,n,r);for(let a of s)console.log(` ${a} left its market — ttheme keeps the copy you have`);await Yt(e,_e(e,n,!1).palettes.filter((a)=>r.palettes.includes(a.name)&&o.has(a.name)).map((a)=>Hn(a,o.get(a.name))),r.terminals)}async function Sc(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Vn(e.palettes),s=process.stdout.isTTY===!0&&!Gn(),o=s?await Qo():new Map,a=new $c({entries:i,scope:n,installed:t,required:r,color:!Gn(),fx:_o(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(Dr(c)):void 0}),u=await a.prompt();if(process.stdout.write(qo(o)),Be(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Ic(e,t,n,r){let i;try{i=xr(e,n)}catch{i=lt(n)?Sn(n):Se(n)}let s=[];if(Ae(n))try{s=On(n,i,Br(e,Z),!1)}catch{s=[]}else s=Br(e,n);return{source:n,id:i,shown:Se(n),entries:s,auto:Nn(n,t.updates),status:fc(e,n,r)}}function Zo(e){return e instanceof Error?e.message:String(e)}function pE(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of Ze(t.markets)){let a=i.get(o)??Se(o),u=n[o],c=ss(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${as(u.at)}: ${u.error}`});if(o===Z)try{Kt(Mm(Pt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${Se(Pt(e))}: ${Zo(l)}`})}else if(lt(o))if(!mE(Ft(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{Pn(e,o)}catch(l){s.push({where:a,source:o,message:`${Se(Ft(e,o))}: ${Zo(l)}`})}else try{let l=ht(Jt(o)),h=new Map;for(let f of Fn(o))try{let d=Ui(f,h);if(d)throw Error(d);h.set(f.slug,f),Ot(`${l}/${f.slug}`,Mm(f.path,"utf8"),Br(e,Z))}catch(d){s.push({where:Se(f.path),message:Zo(d)})}}catch(l){s.push({where:a,message:Zo(l)})}}return s}function wE(e,t,n,r){return{refresh:async(i)=>{if(Ae(i)){let o=Ic(e,t,i,un());return{market:o,refreshed:{source:i,id:o.id,count:De(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await os(e,i,tc);return{market:Ic(e,t,i,un()),refreshed:s}},fetch:async(i)=>{if(Ae(i)){let o=ht(Jt(i));return{source:i,id:o,shown:Se(i),entries:On(i,o,Br(e,Z),!1),auto:!1,status:"read in place"}}let s=await Vr(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:Se(i),entries:s.entries,auto:Nn(i,{}),status:"not added yet"}},search:(i)=>gc(i,r)}}function bE(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==Z&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${st(De(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${Se(i)}`);let o=n.filter((a)=>($e(a)??Z)===s);if(o.length>0)r.push(hc(o))}for(let[i,s]of Object.entries(e.auto)){let o=t.find((a)=>a.source===i);if(o&&!e.removes.includes(i))r.push(`${o.id} ${s?"updates on its own now":"no longer updates on its own"}`)}return r}async function $E(e,t,n,r,i){let s=ie(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let p of r.adds){let E=i.get(p.source);if(E)Xr(e,E)}for(let p of r.removes)lc(e,p);let a=[...Ze(s.markets).filter((p)=>!r.removes.includes(p)),...r.adds.map((p)=>p.source)],u=us(s,a,{...s.updates,...r.auto});if(o)yt(e,u);let c=Le(e,!1),l=_e(e,c,!1).palettes.filter((p)=>r.picked.has(p.name)).map((p)=>p.name),h=s.palettes.filter((p)=>!l.includes(p)),f=l.filter((p)=>!s.palettes.includes(p));if(!o&&f.length===0&&h.length===0){await Ho(e,s,t,r.refreshed),console.log("Nothing changed");return}let d={...u,palettes:l};an(e,c,s,d),To(e,c,s.terminals,h);for(let p of bE(r,n,l))console.log(p);for(let p of f)console.log(` + ${p}`);for(let p of h)console.log(` - ${p}`);let g=new Map(t.map((p)=>[p.name,p.pictures])),m=new Set(r.refreshed.flatMap((p)=>[...p.change.changed,...p.change.gone])),$=_e(e,c,!1).palettes;if(await Yt(e,[...$.filter((p)=>f.includes(p.name)),...$.filter((p)=>l.includes(p.name)&&!f.includes(p.name)&&m.has(p.name)&&g.has(p.name)).map((p)=>Hn(p,g.get(p.name)))],d.terminals),f.length>0||h.length>0)Yo(d.palettes.length)}async function Sm(){let e=ue(),t=ie(e),n=rn(e),r=un(),i=Ze(t.markets).map((m)=>Ic(e,t,m,r)),s=new Set(i.flatMap((m)=>m.entries.map(($)=>$.name))),o=n.filter((m)=>t.palettes.includes(m.name)&&!s.has(m.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0&&!Gn(),l=c?await Qo():new Map,h=ft(t),f=new Ec({markets:i,kept:o,installed:t.palettes,...h?{startup:h}:{},problems:pE(e,t,r,i),due:nc(e,t),io:wE(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Vn},color:!Gn(),fx:_o(process.env.TTHEME_FX),...c?{onFocus:(m)=>process.stdout.write(Dr(m))}:{}}),d=await f.prompt();process.stdout.write(qo(l)),u.abort(),await f.idle();let g=f.result();for(let m of g.refreshed){let $=ic(m);if($)console.log($)}if(Be(d)){await Ho(e,ie(e),n,g.refreshed),console.log("Nothing changed");return}await $E(e,n,i,g,a)}import{rmSync as Im}from"node:fs";import{basename as kE,join as ps}from"node:path";var Nm=ps(import.meta.dirname,".."),yE=ps(Nm,"themes"),Nc=ps(Nm,"dist"),zo=[Ji,qi,Wi,es,Ki,ts,Di],EE=[qu,Ru],NF=zo.map((e)=>e.id);async function Vo({only:e}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let t=e&&e.length>0?zo.filter((s)=>e.includes(s.id)):zo,n=Df(yE),r=nh(n);if(r.length>0){for(let s of r)console.error(` ✗ ${s.theme} [${s.rule}] ${s.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(t.length===zo.length)Im(Nc,{recursive:!0,force:!0});else for(let s of t)Im(ps(Nc,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...EE]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(ps(Nc,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>kE(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
467
+ ${n.length} themes (${ed(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as R1}from"node:child_process";import{createHash as Np}from"node:crypto";import{existsSync as ti,mkdirSync as ys,mkdtempSync as F1,readFileSync as Rp,rmSync as Kc,statSync as O1,writeFileSync as Es}from"node:fs";import{tmpdir as P1}from"node:os";import{dirname as sa,join as Vt}from"node:path";import{pathToFileURL as T1}from"node:url";import{execFile as vE}from"node:child_process";import{createHash as Pm}from"node:crypto";import{existsSync as ME,mkdtempSync as SE,readFileSync as Do,rmSync as IE,statSync as Tm,writeFileSync as Am}from"node:fs";import{homedir as NE,tmpdir as RE}from"node:os";import{join as Xo}from"node:path";import{fileURLToPath as FE}from"node:url";import{promisify as OE}from"node:util";var Zt=OE(vE),Bo=67108864,PE=4096,Oc=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],TE=["text/uri-list","text/plain;charset=utf-8","text/plain"],Rc=[...Oc,"text/uri-list","text/plain"];function AE(e){try{return Tm(e).isFile()}catch{return!1}}function HE(e){let t=[],n="",r="",i=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r==="'")if(o==="'")r="";else n+=o;else if(r==='"')if(o==='"')r="";else if(o==="\\"&&'"\\$`'.includes(e[s+1]??""))n+=e[++s];else n+=o;else if(o==="\\"&&s+1<e.length)n+=e[++s],i=!0;else if(o==="'"||o==='"')r=o,i=!0;else if(/\s/.test(o)){if(i)t.push(n);n="",i=!1}else n+=o,i=!0}if(i)t.push(n);return t}function Rm(e){if(/^file:\/\//i.test(e))try{return FE(e)}catch{return}if(e.startsWith("~/"))return Xo(NE(),e.slice(2));return e.startsWith("/")?e:void 0}function ea(e,t=AE){let n=[];for(let r of e.replace(/\r\n?/g,`
468
468
  `).split(`
469
- `)){let i=vm(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of F1(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=vm(s);if(o&&t(o))n.push(o)}}return n}function P1(e){if(e[0]!==255||e[1]!==216)return null;let t=2;while(t+9<e.length){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=e[t+2]<<8|e[t+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+r}return null}function Mm(e){let t=Ir(e)?yn(e):P1(e);if(!t)return;return{ext:Ir(e)?"png":"jpg",width:t.width,height:t.height}}async function zo(e,t){let n=Mm(e);if(n&&n.width*n.height<=$t)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${$t/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=y1(Yo(M1(),"ttheme-attach-"));try{let i=Yo(r,"in"),s=Yo(r,"out.png");Rm(i,e);let o=!n||n.width*n.height>$t?["--resampleHeightWidthMax",String(N1)]:[];await Zt("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(Vo(s)),u=Mm(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{E1(r,{recursive:!0,force:!0})}}async function Nc(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":ru},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Zo)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(e).host} sent a web page, not a picture — copy the image address instead`);return zo(r,e)}if(Nm(e).size>Zo)throw Error("that picture is over 64 MB");return zo(new Uint8Array(Vo(e)),e)}var Om=new Map,Bo={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,scored:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",narrow:()=>[],postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Om.get(e)??"",parse:()=>[],count:()=>0};function Fm(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Pm(e,t){Om.set(e,t)}function Tm(e){return Number.parseInt(Im("sha1").update(e).digest("hex").slice(0,8),16)%xt}var T1=`ObjC.import('AppKit')
469
+ `)){let i=Rm(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of HE(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=Rm(s);if(o&&t(o))n.push(o)}}return n}function LE(e){if(e[0]!==255||e[1]!==216)return null;let t=2;while(t+9<e.length){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=e[t+2]<<8|e[t+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+r}return null}function Fm(e){let t=Ir(e)?$n(e):LE(e);if(!t)return;return{ext:Ir(e)?"png":"jpg",width:t.width,height:t.height}}async function xo(e,t){let n=Fm(e);if(n&&n.width*n.height<=$t)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${$t/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=SE(Xo(RE(),"ttheme-attach-"));try{let i=Xo(r,"in"),s=Xo(r,"out.png");Am(i,e);let o=!n||n.width*n.height>$t?["--resampleHeightWidthMax",String(PE)]:[];await Zt("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(Do(s)),u=Fm(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{IE(r,{recursive:!0,force:!0})}}async function Pc(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":au},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Bo)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(e).host} sent a web page, not a picture — copy the image address instead`);return xo(r,e)}if(Tm(e).size>Bo)throw Error("that picture is over 64 MB");return xo(new Uint8Array(Do(e)),e)}var Hm=new Map,ta={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,scored:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",narrow:()=>[],postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(e)=>Hm.get(e)??"",parse:()=>[],count:()=>0};function Lm(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Gm(e,t){Hm.set(e,t)}function Um(e){return Number.parseInt(Pm("sha1").update(e).digest("hex").slice(0,8),16)%xt}var GE=`ObjC.import('AppKit')
470
470
  function run(argv) {
471
471
  const pb = $.NSPasteboard.generalPasteboard
472
472
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -491,16 +491,16 @@ function run(argv) {
491
491
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
492
492
  const text = pb.stringForType('public.utf8-plain-text')
493
493
  return text && !text.isNil() ? text.js : ''
494
- }`,A1=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
494
+ }`,UE=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
495
495
  $c = [Windows.Forms.Clipboard]
496
496
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
497
497
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
498
498
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
499
499
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
500
- $c::GetText()`;function Am(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Vo("/proc/version","utf8"))}catch{return!1}}async function H1(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await Zt(n[0],n[1])).stdout.split(`
501
- `).map((o)=>o.trim()),i=(o)=>t?Zt("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:Zo}):Zt("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:Zo});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Ic.find((o)=>r.includes(o));if(s)return Rm(e,(await i(s)).stdout),{image:e};return{text:r.some((o)=>o.startsWith("text/plain")||o==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Rc(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Hm(e){if(process.platform==="darwin"){let t=(await Zt("osascript",["-l","JavaScript","-e",T1,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Am()){let t=(await Zt("powershell.exe",["-NoProfile","-STA","-Command",A1])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
500
+ $c::GetText()`;function _m(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Do("/proc/version","utf8"))}catch{return!1}}async function _E(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await Zt(n[0],n[1])).stdout.split(`
501
+ `).map((o)=>o.trim()),i=(o)=>t?Zt("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:Bo}):Zt("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:Bo});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Oc.find((o)=>r.includes(o));if(s)return Am(e,(await i(s)).stdout),{image:e};return{text:r.some((o)=>o.startsWith("text/plain")||o==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function Tc(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Cm(e){if(process.platform==="darwin"){let t=(await Zt("osascript",["-l","JavaScript","-e",GE,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(_m()){let t=(await Zt("powershell.exe",["-NoProfile","-STA","-Command",UE])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
502
502
  `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await Zt("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
503
- `)}}if(process.platform==="linux")return H1(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var L1=`ObjC.import('AppKit')
503
+ `)}}if(process.platform==="linux")return _E(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var CE=`ObjC.import('AppKit')
504
504
  function run() {
505
505
  const pb = $.NSPasteboard.generalPasteboard
506
506
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -512,27 +512,27 @@ function run() {
512
512
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
513
513
  }
514
514
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
515
- }`;async function Lm(){if(Rc())return;if(process.platform==="darwin"){let[e="",t=""]=(await Zt("osascript",["-l","JavaScript","-e",L1])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Am()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await Zt("wl-paste",["--list-types"])).stdout:(await Zt("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function Gm(e){let t=[],n="",r=0;while(r<e.length){if(e[r]!=="\x1B"){n+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let s=e.indexOf("\x1B[201~",r+6);if(s===-1)return{events:t,keys:n,pending:e.slice(r)};t.push({kind:"paste",text:e.slice(r+6,s)}),r=s+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let s=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((h)=>h!==-1);if(s.length===0)return{events:t,keys:n,pending:e.slice(r)};let o=Math.min(...s),a=e.slice(r+2,o),[u="",c="",...l]=a.split(";");t.push({kind:"osc",code:u,meta:G1(c),payload:l.join(";")}),r=o+(e[o]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")t.push({kind:"attributes"});else{let[s="0",o="0"]=(i[1]??"").split(";");t.push({kind:"mode",mode:Number(s),value:Number(o)})}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:t,keys:n,pending:e.slice(r)};n+=e[r],r++}return{events:t,keys:n,pending:""}}function G1(e){let t={};for(let n of e.split(":")){let r=n.indexOf("=");if(r>0)t[n.slice(0,r)]=n.slice(r+1)}return t}var hs=(e)=>Buffer.from(e).toString("base64"),Sc=(e)=>Buffer.from(e,"base64");function Sm(e,t){return t.find((n)=>e.includes(n))}class Oc{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=hs(Im("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,t){this.send=e,this.deliver=t}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${Mc.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=${hs("ttheme")}:pw=${this.pw};${hs(".")}\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,t){if(e.type!=="read")return;let n=e.status??"";if(n==="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(n==="DATA"){if(r.mime=e.mime?Sc(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Sc(t));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 s=i.toString("utf8").split(/\s+/).filter(Boolean),o=Sm(s,[...Ic,...R1]);if(!o){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:o,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${hs(u)}:pw=${a};${hs(o)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,t){let n=e.t??"";if(n==="m"){if(e.x==="-1"){this.offered=[];return}if(t){this.offered=t.split(" ").filter(Boolean);let a=Mc.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${a.length>0?1:0};${a.join(" ")}\x1B\\`)}return}if(n==="M"){let a=t?t.split(" ").filter(Boolean):this.offered,u=Sm(a,Mc);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:a,index:a.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: ${t.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(t)r.chunks.push(Sc(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?Xo(a).find((c)=>k1(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(Vo(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var ot={pitch:25,cols:22,rows:9,height:13},lr={cols:25,rows:16},U1=2147483648,_1=-1073741826,C1=1600,j1="\x1B[0m",hn="\x1B[1m",we="\x1B[2m",fs="\x1B[31m",zt="\x1B[32m",Et="\x1B[33m",xo="\x1B[1;34m",W1="\x1B[35m",J1={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 qm(e){let t=[],n=0;while(n<e.length){let r=e[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(n+1));if(i){t.push(J1[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let s=e[n+1]??"";if(/^[a-z]$/.test(s)){t.push(`alt-${s}`),n+=2;continue}t.push("esc"),n++;continue}t.push(r==="\r"||r===`
516
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Qm="\x1B]1337;ReportCellSize\x07\x1B[16t",Um="\x1B]1337;ReportCellSize=";function Tc(e){let t=e.indexOf(Um);if(t!==-1){let i=e.slice(t+Um.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function ei(e,t){return{perRow:Math.max(1,Math.floor((e+1)/ot.pitch)),rowsVis:Math.max(1,Math.floor((t-4)/ot.height))}}function Ym(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function Zm(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 zm(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function Vm(e){return`\x1B[38;2;${qe(e).join(";")}m`}function Fc(e){return`\x1B[48;2;${qe(e).join(";")}m`}function Je(e){return Array.from(e).length}class Do{parts=[];cols;constructor(e){this.cols=e}put(e,t,n=""){return this.parts.push({col:e,text:t,sgr:n}),e+Je(t)}run(e,t){let n=e;for(let[r,i]of t)n=this.put(n,r,i);return n}right(e,t){this.run(e-t.reduce((n,[r])=>n+Je(r),0),t)}render(){let e="";for(let{col:t,text:n,sgr:r}of this.parts){if(t>=this.cols||t<0)continue;let i=Array.from(n).slice(0,this.cols-t).join("");e+=`\x1B[${t+1}G${r}${i}${r?j1:""}`}return e}}function Xm(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function K1(e,t){if(!t)return Xm(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function Bm(e){return e.replace(/_\([^)]*\)?$/,"")}function xm(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<C1?Et:we]}function ds(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Je(s[0])]:[],...i.map(([f,d])=>Je(f)+1+Je(d))];return(r.badge?Je(r.badge)+4:0)+l.reduce((f,d)=>f+d,0)+3*Math.max(0,l.length-1)+(o?3+Je(o[0])+1+Je(o[1]):0)};while(a()>t)if(i.length>2)i.splice(-2,1);else if(o)o=void 0;else if(i.length>1)i.splice(-2,1);else break;if(s&&a()>t){let l=Math.max(0,Je(s[0])-(a()-t)-1);s=[`${Array.from(s[0]).slice(0,l).join("")}…`,s[1]]}let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[[s]]:[],...i.map(([l,h])=>[[l,hn],[` ${h}`,we]])].forEach((l,h)=>{u=e.run(u+(h?3:0),l)}),o)e.right(t,[[o[0],hn],[` ${o[1]}`,we]])}function q1(e,t,n,r,i,s){let{ansi:o,selection:a,cursor:u}=s.colors,c=r<44?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let g=0;g<8;g++)l=(e[t]?.put(l,"▀".repeat(c),Vm(o[g]??u)+Fc(o[g+8]??u))??l)+1;let h=["❯ ",zt],f=[[["~/code/demo",xo],[" on ",we],["main",W1],[" +2",zt],[" ~1",Et]]];if(f.push([h,["git status -sb",""]]),r>=44)f.push([["## ",""],["main",zt],["...",""],["origin/main",fs],[" [ahead 1]",Et]]);if(f.push([[" M",fs],[" src/main.rs",""]]),f.push([["??",fs],[" notes.md",""]]),f.push([]),r>=44)f.push([h,["ls",""]]),f.push([["docs",xo],[" ",""],["src",xo],[" ",""],["tests",xo],[" Cargo.toml README.md",""]]),f.push([]);f.push([h,["cargo test",""]]),f.push([[" ✓",zt],[" parses config",""]]);let d=[[" ✗",fs],[" renders frame",""]];if(r>=44)d.push([" expected ",we],["3",zt],[", received ",we],["2",fs]);f.push(d),f.push([]),f.push([h,["echo ",""],["selected text",Fc(a)],[" ",""],[" ",Fc(u)]]),f.forEach((g,m)=>{let $=t+2+m;if($<=i)e[$]?.run(n,g)})}function Q1(e,t,n,r,i,s){e[t]?.put(n,`╭${"─".repeat(i-2)}╮`,s);for(let o=t+1;o<t+r-1;o++)e[o]?.put(n,"│",s),e[o]?.put(n+i-1,"│",s);e[t+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,s)}function Pc(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function Y1(e){return`${ee[Math.floor(e/xt)]?.name??"local"} ${e%xt}`}function Z1(e,t,n){let r=[{name:"all",moved:!1},...ee].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Pc(n,a):[` ${a} `,we];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+Je(o),0)<=t;e.run(0,i?r:[Pc(n)])}function z1(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,we);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":we]]),s=Qn.filter((u)=>!n.block.includes(u)),o=ee.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,we),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,we]);e.right(t,u)}}function V1(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,zt]];if(e.cut==="off")return[["Opaque · x cuts out",Et]];if(e.cut==="failed")return[["Opaque · no cut-out",Et]];return[e.clear>0?[`${e.clear}% transparent`,zt]:["Opaque",Et]]}function _m(e){return e.site==="all"?"any site":e.site}function Dm(e){if(e.installing!==void 0)return[`Installing ${e.palette} ← ${Y1(e.installing)}`,Et];if(e.hint)return[e.hint,zt];if(e.error)return[e.error,Et];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,Et];if(e.fetching)return[`Fetching ${e.fetching.id%xt} · ${K1(e.fetching.got,e.fetching.size)}`,Et];if(e.cutting!==void 0)return[`Cutting out ${e.cutting%xt}`,Et];if(e.preparing!==void 0)return[`Preparing ${e.preparing%xt}`,Et];if(e.saved)return[e.saved,zt];if(e.note)return[e.note,we];return}function X1(e,t,n,r,i,s){let{perRow:o,rowsVis:a}=ei(n,r);z1(e[0],n,i,s),Z1(e[1],n,i);for(let d=0;d<o*a;d++){let g=i.top*o+d,m=i.tiles[g];if(!m)break;let $=2+Math.floor(d/o)*ot.height,w=d%o*ot.pitch,M=g===i.focus;if(M)Q1(e,$,w,ot.height,ot.pitch-1,s);if(m.thumb)t.push({id:m.key,path:m.thumb,row:$+1,col:w+1,cols:ot.cols,rows:ot.rows,z:-1});if(e[$+10]?.run(w+1,[...i.installed.includes(m.key)?[["✓ ",zt]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),M?hn:""],[" ",""],xm(m)]),m.mates.length>0)e[$+10]?.put(w+ot.cols,"≈",s);let y=m.artist?Bm(m.artist):m.owner&&`@${m.owner}`;if(y)e[$+11]?.put(w+1,y.slice(0,ot.cols-8),we);let S=[];if(m.score>0)S.push([`★${m.score}`,we]);if(m.variants>1)S.push([` ×${m.variants}`,s]);if(S.length>0)e[$+11]?.right(w+ot.cols+1,S)}let u=i.top*o,c=i.tiles.length-(i.top+a)*o,l=[...u>0?[`↑ ${u} above`]:[],...c>0?[`↓ ${c} more`]:[]];if(l.length>0)e[r-2]?.put(0,l.join(" "),we);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${_m(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${_m(i)} — tab tries ${i.nextSite}`,we);let h=e[r-1],f=Dm(i);if(i.searching&&i.tiles.length===0&&!f){ds(h,n,s,{badge:"FIND",lead:[i.preset==="cutouts"?"Checking PNG headers":"Fetching posts",we],right:["esc","back"]});return}ds(h,n,s,{badge:"FIND",lead:f,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function B1(e,t,n,r,i,s){let o=i.tiles[i.focus];if(!o)return;let a=i.shown?.id===o.key?i.shown:void 0,u=[Pc(i,o.site,o.siteAnsi),[" ",""],[String(o.id),hn],[" ",""],xm(o)];if(o.artist)u.push([` · ${Bm(o.artist)}`,""]);if(o.score>0)u.push([` · ★${o.score}`,we]);if(a)u.push([` · ${Xm(a.bytes)}`,we]);if(o.owner)u.push([` · ${o.owner}`,we]);if(o.origin)u.push([` · ${o.origin}`,we]);if(a)u.push([" ",""],...V1(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),we]]);if(q1(e,3,2,n-4,r-2,i),i.shown)t.push({id:U1+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:_1});let c=Dm(i);ds(e[r-1],n,s,{badge:"TRY",lead:c,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 x1={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab all, ${ee.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"],["Advanced","a or Advanced › in settings min score, min size, sites, hide, hide tags, PNG only"],["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"]]},Ac=6,D1=24;function gs(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function eE(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function Cm(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>eE(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function ep(e,t,n){let r=e.indexOf(t);if(r!==-1)return e[(r+n+e.length)%e.length];let i=Number(t)||0;return(n>0?e.find((o)=>(Number(o)||0)>i):[...e].reverse().find((o)=>(Number(o)||0)<i))??e[n>0?0:e.length-1]}function cr(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&Je(r)+1+Je(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function tE(e){if(e.entry!=="number"||e.choices.includes(e.value))return e.choices;let t=e.choices.findIndex((n)=>(Number(n)||0)>Number(e.value));return t===-1?[...e.choices,e.value]:[...e.choices.slice(0,t),e.value,...e.choices.slice(t)]}function nE(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":we}];let o=s?[]:e.value.split(" "),a=(s?e.choices:tE(e)).map((u,c)=>{let l=o.includes(u),h=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${h}7;${30+r}m`:"":h?`\x1B[4m${we}`:we}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function jm(e){if(e.entry==="text")return[{text:" ".repeat(D1),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Ac)}█ `,sgr:""}]:t}function rE(e){return e.reduce((t,n)=>t+Je(n.text)+1,0)-1}function Wm(e,t){let n=[[]],r=0;for(let i of e){let s=Je(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+Je(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=Je(s.text)+1}return n}function Jm(e){if(e.multi&&e.choices.every((t)=>e.default.split(" ").includes(t)))return"Default all";return`Default ${e.default&&e.default!==e.multi?.none?e.default:"none"}`}function Km(e){if(!e.tag)return"";if(!e.counts)return`${e.tag}: counting…`;let t=e.counts.map(({site:n,count:r})=>`${n} ${r===void 0?"no count":r.toLocaleString("en-US")}`);return`${e.tag}: ${t.join(" · ")}`}function iE(e,t){let n=e.advanced?"basic":"advanced";if(!t)return{keys:[["↑↓","setting"],["enter",n],["s","save"]],right:["esc","undo"]};if(e.typing!==void 0)return{keys:[["⌫","erase"],["enter","done"]],right:["esc","cancel"]};if(t.entry)return{keys:[["↑↓","setting"],...t.entry==="number"?[["←→","step"]]:[],["a",n],["enter","type"],["s","save"]],right:["esc","undo"]};return{keys:[["↑↓","setting"],["←→","value"],["a",n],...t.multi?[["space","toggle"]]:[],["enter","save"]],right:["esc","undo"]}}function sE(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((H)=>Je(H.label))),c=Math.max(...r.settings.map((H)=>Je(Jm(H)))),l=u+Math.max(...r.settings.map((H)=>rE(jm(H))))+c+5,h=Math.min(t-2,Math.max(48,l)),f=h-u-c-5,d=h-7,g=[!1,!0].map((H)=>({advanced:H,rows:gs({settings:r.settings,advanced:H}).slice(0,-1)})),m=r.settings.map((H)=>Wm(jm(H),f).length),$=Math.max(...g.map((H)=>H.rows.reduce((A,Q)=>A+m[Q],0))),w=Math.max(...g.map((H)=>cr(Cm({settings:r.settings,advanced:H.advanced}),d).length),...r.settings.map((H)=>cr(H.about,d).length)),M=`${r.tag}: ${ee.map((H)=>`${H.name} 0,000,000`).join(" · ")}`,y=r.tag?Math.max(cr(M,d).length,cr(Km(r),d).length):0,S=$+w+y+8,p=Math.floor((t-h)/2),N=Math.max(1,Math.floor((n-1-S)/2)),E=`\x1B[7;${30+r.siteAnsi}m`;e[N]?.put(p,`╭─ Settings ${"─".repeat(Math.max(0,h-13))}╮`);for(let H=N+1;H<N+S-1;H++)e[H]?.put(p,`│${" ".repeat(h-2)}│`);let F=N+2;for(let H of gs(r).slice(0,-1)){let A=r.settings[H],Q=H===s;if(Q)e[F]?.put(p+2,"▶",i);if(e[F]?.put(p+4,A.label,Q?hn:""),A.value!==A.default)e[F]?.right(p+h-3,[[Jm(A),we]]);Wm(nE(A,Q,r.typing,r.siteAnsi),f).forEach((Ne,$e)=>{let x=p+u;for(let Ge of Ne)x=e[F+$e].put(x,Ge.text,Ge.sgr)+1}),F+=m[H]}let O=g.find((H)=>H.advanced!==r.advanced)?.rows??[],L=e[N+3+$];if(s===o)L.put(p+2,"▶",i);let U=L.put(p+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?E:hn);if(O.some((H)=>r.settings[H]?.value!==r.settings[H]?.default))L.put(U+1,"•",we);e[N+5+$]?.put(p+2,"─".repeat(h-4),we),cr(r.settings[s]?.about??Cm(r),d).forEach((H,A)=>{e[N+6+$+A]?.put(p+4,H)}),cr(Km(r),d).forEach((H,A)=>{e[N+6+$+w+A]?.put(p+4,H,we)}),e[N+S-1]?.put(p,`╰${"─".repeat(h-2)}╯`);let{keys:ce,right:j}=iE(r,r.settings[s]);ds(e[n-1],t,i,{badge:"SET",keys:ce,right:j})}function oE(e,t,n,r,i){let s=x1[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,f])=>Je(f)+16))),a=s.map(([f,d])=>({label:f,parts:cr(d,o-16)})),u=a.reduce((f,{parts:d})=>f+d.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Keys ${"─".repeat(o-9)}╮`);for(let f=l+1;f<l+u-1;f++)e[f]?.put(c,`│${" ".repeat(o-2)}│`);let h=l+2;for(let{label:f,parts:d}of a){e[h]?.put(c+3,f,hn);for(let g of d)e[h]?.put(c+13,g),h++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),ds(e[n-1],t,i,{badge:"KEYS",right:["? esc","close"]})}function aE(e,t,n){let r=t.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),s=Math.max(...r.map((a)=>Je(a.value))),o=Math.max(7,...i.map(Je));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?hn+n:""]]),l?.right(2+s+2+o,[[i[u],we]])})}function tp(e,t,n){let r=Array.from({length:n},()=>new Do(t)),i=[],s=Vm(e.colors.cursor);if(t<lr.cols||n<lr.rows)return r[0]?.put(0,"ttheme find",hn+s),r[1]?.put(0,`Needs ${lr.cols}×${lr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",we),{lines:r.map((o)=>o.render()),images:i};if(e.mode==="try")B1(r,i,t,n,e,s);else X1(r,i,t,n,e,s);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let o=1;o<n-1;o++)r[o]=new Do(t);return aE(r,e,s),{lines:r.map((o)=>o.render()),images:[]}}if(e.help||e.panel!==void 0){let o=e.mode==="try"?i:[];for(let a=0;a<n;a++)r[a]=new Do(t);if(e.help)oE(r,t,n,e,s);else sE(r,t,n,e,s);return{lines:r.map((a)=>a.render()),images:o}}return{lines:r.map((o)=>o.render()),images:i}}var uE=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),cE=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),lE=0.04,hE=0.1,fE=0.05,dE=4096;function gE(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function mE(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...gE(i)].some((l)=>o.has(l)),u=Math.min(s.width,s.height),c=s.width>0&&s.height>0?s.width/s.height/(t.w/t.h):1;return(s.solo?2:0)+([...uE].some((l)=>o.has(l))?-3:0)+([...cE].some((l)=>o.has(l))?-1.5:0)+2*Math.min(1,u/t.h)+(a?1.5:-Math.min(1.5,Math.abs(Math.log(c))))+(n>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(n):0)+2*r}function ea(e,t,n=new Map){let r=new Map;for(let{site:i,post:s}of e)r.set(i,Math.max(r.get(i)??0,s.score));return e.map((i,s)=>({pick:i,at:s,score:mE(i,t,r.get(i.site)??0,n.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function rp(e){let t=new Map;for(let r of e)t.set(r.site,[...t.get(r.site)??[],r]);let n=[];for(let r=0;n.length<e.length;r++)for(let i of t.values()){let s=i[r];if(s)n.push(s)}return n}function Hc(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function np(e,t,n){let[r,i,s]=[Hc(e),Hc(t),Hc(n)],o=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*s),a=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*s),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*a-0.0040720468*u,1.9779984951*o-2.428592205*a+0.4505937099*u,0.0259040371*o+0.7827717662*a-0.808675766*u]}function ip(e,t){let n=t.map((o)=>np(...qe(o))).filter(([,o,a])=>Math.hypot(o,a)>=lE);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/dE))),i=n.map(()=>0),s=0;for(let o=0;o<e.height;o+=r)for(let a=0;a<e.width;a+=r){let u=(o*e.width+a)*4;if(e.data[u+3]<128)continue;s++;let[c,l,h]=np(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([f,d,g],m)=>{if(Math.hypot(c-f,l-d,h-g)<hE)i[m]=i[m]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/fE),0)/n.length}import{mkdirSync as cp,readFileSync as lp,writeFileSync as hp}from"node:fs";import{dirname as fp}from"node:path";import{isMainThread as $E,parentPort as dp,Worker as kE}from"node:worker_threads";var pE=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,wE=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"],[/zerochan\.net\/(\d+)(?:[?#\s]|$)/,"zerochan"]];function Lc(e){let t=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...t&&e.source.includes("pximg")?[`pixiv:${t[1]}_p${t[2]}`]:[]]}function sp(e,t){let n=pE.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...wE.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function op(e,t){let n=e.owner||e.artist;return n!==""&&n===(t.owner||t.artist)&&e.width===t.width&&e.height===t.height}function ap(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),h=0;for(let f=o;f<a;f++)for(let d=c;d<l;d++){let g=(f*e.width+d)*4,m=e.data[g+3]/255,$=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];h+=$*m+255*(1-m)}r.push(h/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function bE(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function up(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(t.width/t.height)))<0.01&&bE(e.hash,t.hash)<=2}var yE={thumb:"tile",match:"tile",show:"view",backdrop:"view",redraw:"view"};async function EE(e){if(e.job==="redraw")return Mg(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);let t=qn(new Uint8Array(lp(e.from)),$t);if(e.job==="backdrop")return uo(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(lp(e.source)),cut:e.from!==e.source},e,e.blur),0;if(e.job==="match")return{match:ip(t,e.colors),hash:ap(t)};if(e.job==="thumb")return cp(fp(e.to),{recursive:!0}),hp(e.to,za(af(t,e.width,e.height))),0;let n=Bt(t);return cp(fp(e.to),{recursive:!0}),hp(e.to,za(cd(t,e.colors,e.tone,e.width,e.height,e.blur))),n}function vE(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await EE(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Gc{worker;next=1;waiting=new Map;send(e){let t=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(t,{ok:n,no:r}),i.ref(),i.postMessage({...e,id:t})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new kE(import.meta.filename);e.unref(),e.on("message",({id:n,value:r,error:i})=>{let s=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)e.unref();if(i!==void 0)s?.no(Error(i));else s?.ok(r)});let t=(n)=>{if(this.worker===e)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return e.on("error",t),e.on("exit",()=>t(void 0)),this.worker=e,e}drop(e){for(let t of this.waiting.values())t.no(e);this.waiting.clear()}}class Uc{lines=new Map;run(e){let t=yE[e.job],n=this.lines.get(t);if(!n)n=new Gc,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class _c{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Gc)}async map(e){let t=[],n=0;return await Promise.all(this.lines.map(async(r)=>{while(n<e.length){let i=n++;try{t[i]=await r.send(e[i])}catch(s){t[i]=s instanceof Error?s:Error(String(s))}}})),t}close(){for(let e of this.lines)e.close()}}if(!$E&&dp)vE(dp);var hr=[{name:"TTHEME_FIND_RATING",label:"Rating",about:"The ratings to list, each site read in its own words — space ticks one, and one stays ticked",choices:Ni,multi:{read:Zn}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Qn,multi:{read:Rr,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...Qr()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Mf,entry:"number",advanced:!0},{name:"TTHEME_FIND_MIN_SIZE",label:"Min size",about:"The shorter side of a picture, in px — every site filters it. ←→ steps, or type any number",choices:Sf,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:ee.map((e)=>e.name),multi:{read:Oi},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:nu,multi:{read:zs,none:"none"},advanced:!0},{name:"TTHEME_FIND_HIDE_TAGS",label:"Hide tags",about:"Posts with any of these tags are left out, spaced like cosplay multiple_girls — checked as posts arrive",choices:[],entry:"text",advanced:!0},{name:"TTHEME_FIND_PNG",label:"PNG only",about:"PNG originals only — danbooru counts it, the others are told by the file; zerochan only where danbooru holds it",choices:["off","on"],advanced:!0}];function gp(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return Fi(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var OE=["fit","newest","score"];function jc(e){return OE.find((t)=>t===e)??"fit"}function FE(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var mp=12,PE=4,TE=150,AE=300,pp=12,HE=2,LE=150,GE=30,UE=4000,_E=8000,wp=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,CE=process.platform==="win32"?"alt+v":"ctrl+v",bp=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",jE=1280,$p=2,WE=3,JE=8;function na(e,t){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:t}}function ws(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return ws(e.errors[0]);if(e.cause)return ws(e.cause);let t=e.code;if(typeof t==="string")return t;let n=(e.message||e.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function Wc(e,t){return`${e}: ${ws(t)}`}function kp(e){return e.width*e.height}function yp(e,t){return`${e}-${Ep("sha1").update(t).digest("hex").slice(0,8)}`}function KE(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function Jc(e,t){try{return JSON.parse(vp(Vt(Nt(e),t),"utf8"))}catch{return{}}}function Kc(e,t,n){ms(Nt(e),{recursive:!0}),ps(Vt(Nt(e),t),`${JSON.stringify(n)}
517
- `)}class Mp{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(hr.map((e)=>[e.name,gp(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 Uc;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Oc((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=SE(Vt(NE(),"ttheme-find-"));home;catalog;entry;blurring;constructor(e,t,n,r){this.home=e,this.catalog=t,this.entry=n,this.tone=Tr(n,n.signatureSlots),this.blurring=jr(e),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:jc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Zn(this.setting("TTHEME_FIND_RATING")),block:Rr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:Oi(this.setting("TTHEME_FIND_SITES")),hide:zs(this.setting("TTHEME_FIND_HIDE")),hideTags:Fi(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:hr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),default:gp(i,Uu(i.name)),multi:i.multi&&{none:i.multi.none},about:i.about,entry:i.entry,advanced:i.advanced,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=na(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:ee[this.tab-1]}get sites(){return this.site?[this.site]:ee.filter((e)=>this.view.enabled.includes(e.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??PE}get nextTabName(){let e=(this.tab+1)%(ee.length+1);return e===0?"all":ee[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)}narrowed(){return iu(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return Vt(Nt(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=Bs(e.site,e.post);return Vt(Nt(e.site),"thumb",`${yp(e.post.id,t)}.${Sn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=_t(n,r.id),s=Dt(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,owner:r.owner,artist:n===Bo?Fm(r.source):r.artist,score:r.score,variants:t,origin:Ys(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let e=this.view,t=this.board;e.tiles=t.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),e.checked=t.checked,e.total=t.total,e.searching=t.searching,e.note=t.note,e.focus=Math.max(0,Math.min(t.focus,e.tiles.length-1)),e.top=t.top}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:t}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),t.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((o)=>{this.done=o}),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 s=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(),this.quietCount(),clearInterval(r),e.off("data",this.onData),t.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(),Cc(this.scratch,{recursive:!0,force:!0}),Gf(),s}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 t=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(n)=>{clearTimeout(t),this.probeWait=void 0,e(n)},this.write(Qm)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=Tc(this.input);n;n=Tc(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=Gm(this.input);if(this.input=t.pending,this.view.editing===void 0&&t.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(t.keys))this.pasted(t.keys),t.keys="";this.typed+=t.keys;for(let n of t.events)this.inbound(n);if(clearTimeout(this.partial),KE(this.typed)){this.partial=setTimeout(this.flushKeys,GE);return}this.flushKeys()};flushKeys=()=>{let e=qm(this.typed);this.typed="";for(let t of e)this.key(t)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let t=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(t),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 t=this.view;if(t.editing!==void 0&&e.trim()!==""&&!this.picture(e)){t.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(t.installing!==void 0||t.panel!==void 0||t.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let t=e.trim();if(/^https?:\/\/\S+$/i.test(t))return!Vs(t,this.site??ee[0]);return Xo(t).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 — ${bp}`);return}this.pasted(e.text);return}await this.bring(()=>zo(e.bytes,e.source))}notice(e,t=UE){let n=this.view;n.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===e)n.error=void 0,this.draw()},t),this.draw()}async peek(){let e=this.view,t;try{t=await Lm()}catch{return}if(!t||t.stamp===this.peeked)return;if(this.peeked=t.stamp,!t.picture||e.installing!==void 0)return;e.hint=`Picture on the clipboard · ${CE} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},_E),this.draw()}async fromClipboard(){let e=this.view;if(Rc()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("Over SSH the clipboard is not here — drop the file");return}let t;try{t=await Hm(Vt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${ws(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await Nc(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${bp}`);return}if(this.picture(n)){await this.attach(n);return}if(e.editing===void 0)e.editing="";this.pasted(n)}async attach(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let i=Vs(t,this.site??ee[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Xo(t).sort((i,s)=>Number(!wp.test(i))-Number(!wp.test(s)));if(!n){this.notice("Nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Nc(n,i),r.length)}async bring(e,t=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 e(AbortSignal.any([r.signal,this.signal]))}catch(f){if(!r.signal.aborted)n.note=void 0,this.notice(ws(f),8000);return}if(r.signal.aborted)return;n.note=t>0?`The first picture of ${t+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 s=Tm(i.bytes);Pm(s,i.source);let o=this.origPath(Bo,s,i.ext);ms(ta(o),{recursive:!0}),ps(o,i.bytes);let a=RE(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",artist:"",score:0,rating:"s",md5:Ep("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},c={site:Bo,post:u},l=this.previewPath(c);ms(ta(l),{recursive:!0}),ps(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let h=na(`local|post:${s}`,!1);this.board=h,this.boards.set(h.key,h),this.single(h,c)}single(e,t){e.searching=!1,this.posts.set(_t(t.site,t.post.id),t),e.groups=[{posts:[t],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(t),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>Mn(i)>Mn(r)?i:r),t=Math.ceil((Mn(e)-Date.now())/1000),n=t>0?t:void 0;if(n!==this.view.waiting)this.view.waiting=n,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 t=this.view;if(e==="ctrl-c"){this.finish(2);return}if(t.installing!==void 0)return;if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&t.panel===void 0){this.fromClipboard();return}if(t.editing!==void 0){this.editKey(e);return}if(t.panel!==void 0){this.panelKey(e);return}if(t.help){if(e==="?"||e==="esc")t.help=!1,this.draw();return}if(this.cols<lr.cols||this.rows<lr.rows){if(e==="esc")this.finish(2);return}if(e==="?"){t.help=!0,this.draw();return}if(t.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let t=this.view,{perRow:n,rowsVis:r}=ei(this.cols,this.rows),s={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-t.focus,end:t.tiles.length}[e];if(s!==void 0){this.focus(t.focus+s);return}if(e==="enter"&&t.tiles[t.focus]){t.mode="try",t.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){t.preset=t.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(ee.length+1),this.syncSite(),this.turn();return}if(e==="/"){t.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){t.panel=0,t.advanced=!1,this.recount(),this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let t=this.view,n=t.panel??0,r=t.settings[n];if(t.typing!==void 0&&r){this.typeKey(r,e);return}let i=gs(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[Math.max(0,Math.min(i.length-1,s))]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=gs(t)[0]??0,this.draw();return}if(r?.entry&&(e==="enter"||r.entry==="number"&&/^[0-9]$/.test(e))){t.typing=e==="enter"?r.entry==="text"?r.value:"":e,this.draw();return}if((e==="left"||e==="right")&&r&&r.entry!=="text"){let s=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+s+r.choices.length)%r.choices.length;else r.value=ep(r.choices,r.value,s),this.recount();this.draw();return}if(e===" "&&r?.multi){let s=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!s.includes(u):s.includes(u)),a=r.multi.none;if(o.length>0||a!==void 0)r.value=o.length>0?o.join(" "):a,this.recount(),this.draw();return}if(e==="esc"){t.settings.forEach((s,o)=>{s.value=this.setting(hr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":Fi(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<Ac:/^[\x20-\x7e]$/.test(t))n.typing=r+t,this.draw()}quietCount(){clearTimeout(this.countTimer),this.counting?.abort(),this.counting=void 0}recount(){if(this.quietCount(),this.view.counts=void 0,!this.view.tag)return;let e=new AbortController;this.counting=e,this.countTimer=setTimeout(()=>void this.countPending(e),AE)}pending(){let e=(t)=>this.view.settings[hr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:jc(e("TTHEME_FIND_ORDER")),rating:Zn(e("TTHEME_FIND_RATING")),narrow:iu(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:Oi(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:ee.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await cu(s,o.tags,r);return{site:s.name,...Number.isFinite(a)?{count:a}:{}}}catch{return{site:s.name}}}));if(this.counting===e&&this.view.panel!==void 0)this.view.counts=i,this.draw()}adopt(){let e=this.view,t=hr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=hr[i];if(s)this.values.set(s.name,r.value)});let n=hr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=Zn(this.setting("TTHEME_FIND_RATING")),e.block=Rr(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=jc(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=Oi(this.setting("TTHEME_FIND_SITES")),e.hide=zs(this.setting("TTHEME_FIND_HIDE")),e.hideTags=Fi(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=Vt(this.home,"ttheme","config.zsh");try{let n=ti(t)?vp(t,"utf8"):"";return ps(t,e.reduce((r,[i,s])=>xd(r,i,s),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}editKey(e){let t=this.view,n=t.editing??"",r=t.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=t.pick??-1,s=e==="down"?Math.min(r.length-1,i+1):i-1;t.pick=s<0?void 0:s,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(t.editing=void 0,t.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=t.pick===void 0?void 0:r[t.pick],s=i?n.replace(/\S*$/,i.value):n;if(t.editing=void 0,t.suggest=void 0,t.pick=void 0,s.trim()){this.commit(s.trim());return}if(t.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){t.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")t.editing=n+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 t=/\S*$/.exec(e.editing??"")?.[0]??"";if(!FE(t)){e.suggest=void 0;return}let n=[...new Map(Ud(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,WE);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await jf(t,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let s=new Map(i.map((a)=>[a.value,a.count])),o=new Set(n.map((a)=>a.value));e.suggest=[...n.map((a)=>({...a,count:s.get(a.value)??0})),...i.filter((a)=>!o.has(a.value))].slice(0,JE),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},TE)}async commit(e){let t=Vs(e,this.site??ee[0]);if(t){await this.jump(t.site,t.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,t){let n=++this.gen;this.tab=ee.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=na(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Pi(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,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,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(_t(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}t+=r}}openPage(){let e=this.view.tiles[this.view.focus],t=e&&this.posts.get(e.key);if(!t)return;let n=process.platform==="darwin"?"open":"xdg-open";try{ME(n,[t.site.pageUrl(t.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let t=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(t.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),t.fetching=void 0,t.mode="grid",t.error=void 0,this.draw()}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=ei(this.cols,this.rows),r=Math.floor(e.focus/t);if(r<e.top)e.top=r;if(r>e.top+n-1)e.top=r-n+1;this.board.top=e.top}query(e,t=this.view){let n=t.tag===this.entry.booru?_d(this.entry,e.key):[t.tag];if(n.length===0)return;let r=n.length>1,i=t.preset==="cutouts"?e.cutouts:"",s=r&&i.includes("~"),o=[r?n.map((c)=>`~${c}`).join(" "):n[0],e.rate(t.rating),...e.narrow(t.narrow),s?"":i,t.order==="score"?e.best:""].filter(Boolean),a=[],u=[];for(let c of o)if(au([...a,c].join(" "))<=e.tagBudget)a.push(c);else u.push(c);return{tags:a.join(" "),notes:[...u.length>0?[`${e.name} takes ${e.tagBudget} tags — ${u.join(" ")} left out`]:[],...s?[`${e.name} ORs the names, so cutouts are told by the file`]:[],...t.narrow.score>0&&!e.scored?[`${e.name} keeps no score`]:[],...t.narrow.png&&e.guesses?[`${e.name} names a file type only where danbooru holds the file`]:[]]}}async search(){let e=++this.gen,t=na(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0;let n=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),r=this.sites.filter((s)=>!n.some((o)=>o.site===s)),i=[...n.flatMap(({notes:s})=>s),...r.length>0?[`${this.entry.name} has no tag on ${r.map((s)=>s.name).join(", ")}`]:[]];if(t.note=i.length>0?i.join(" · "):void 0,n.length===0)t.searching=!1;this.show(),this.draw(),this.tally(e,t,n);try{let s=await Promise.all(n.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(e!==this.gen)return;t.sources=s.flatMap(({plan:{site:o,tags:a},owners:u})=>[...au(a)+1<=o.tagBudget?[...u.keys()].map((c)=>({site:o,tags:`${a} user:${c}`,page:0,done:!1})):[],{site:o,tags:a,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(s){this.fail(e,s)}}async tally(e,t,n){let r=await Promise.allSettled(n.map(({site:i,tags:s})=>cu(i,s,this.signal)));if(e===this.gen)t.total=r.reduce((i,s)=>i+(s.status==="fulfilled"&&Number.isFinite(s.value)?s.value:0),0),this.show(),this.draw()}fail(e,t,n=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=Wc(n?.name??this.tabName,t),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}drop(e,t,n){for(let r of e.sources)if(r.site===t)r.done=!0;e.note=[e.note,Wc(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=ei(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+$p)*e}need(){let{perRow:e,rowsVis:t}=ei(this.cols,this.rows);return(t+$p)*e}live(e){return this.boards.get(e.key)===e}page(e,t,n){let r=`${e.key}|${t}|${n}`,i=this.pages.get(r);if(!i)i=Uf(e,t,n,this.signal).then((s)=>this.borrow(e,s)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e,t){let n=e===Ut?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{_f(n,await Cf(n.map((r)=>r.md5),this.signal))}catch{}return t}async round(e){let t=ee.flatMap((a)=>{let u=e.sources.find((c)=>c.site===a&&!c.done);return u?[u]:[]}),n=await Promise.all(t.map(async(a)=>{try{return{source:a,posts:await this.page(a.site,a.tags,a.page)}}catch(u){if(e.sources.every((c)=>c.site===a.site)||this.signal.aborted)throw u;return this.drop(e,a.site,u),{source:a,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:a,posts:u}of n){if(!u)continue;a.page++,a.done=u.length<vn;let c=e.last.get(a);for(let l of u){let h=c&&op(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:h};let f=_t(a.site,l.id);if(e.seen.has(f))continue;e.seen.add(f);let d={site:a.site,post:l};if(this.eligible(d))e.kin.set(d,[h,...sp(a.site,l)]),r.push(d);else e.checked++}if(c)e.last.set(a,c)}let i=this.dedupe(e,r),s=++e.rounds,o;if(this.view.order!=="fit")o=t.length>1?rp(i):i;else{let a=ea(i,this.frame(),this.matched),u=a.slice(0,this.need());if(await this.looks(u),!this.live(e))return;o=[...ea(u,this.frame(),this.matched),...a.slice(u.length)]}for(let a of o)e.roundOf.set(a,s);e.queue.push(...o),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let t=e.queue.slice(0,this.need()).filter((n)=>!this.looking.has(_t(n.site,n.post.id)));if(t.length===0)return;this.aheading=!0,this.looks(t).then(()=>{this.aheading=!1;for(let n of new Set(t.map((r)=>e.roundOf.get(r)??0)))this.resort(e,n);this.ahead(e)})}resort(e,t){let n=e.queue.flatMap((i,s)=>e.roundOf.get(i)===t?[s]:[]),r=ea(n.map((i)=>e.queue[i]),this.frame(),this.matched);n.forEach((i,s)=>{e.queue[i]=r[s]})}dedupe(e,t){let n=[];for(let r of t){let i=Lc(r.post),s=i.map((a)=>e.same.get(a)).find(Boolean);if(!s){for(let a of i)e.same.set(a,r);n.push(r);continue}if(e.checked++,kp(r.post)<=kp(s.post))continue;for(let a of[...i,...Lc(s.post)])e.same.set(a,r);let o=n.indexOf(s);if(o>=0){n[o]=r;continue}this.replace(e,s,r)}return n}replace(e,t,n){e.roundOf.set(n,e.roundOf.get(t)??0);let r=e.queue.indexOf(t);if(r>=0){e.queue[r]=n;return}for(let i of e.groups){let s=i.posts.indexOf(t);if(s>=0){i.posts[s]=n,this.posts.set(_t(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e){let t=0;await Promise.all(Array.from({length:pp},async()=>{while(t<e.length)await this.look(e[t++])}))}look(e){let t=_t(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=Bs(e.site,e.post);await this.cached(i.site,r,i.url);let s=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(t,s),this.matched.set(e.post,s.match),s})().catch(()=>{return}),this.looking.set(t,n);return n}async pump(){let e=this.gen,t=this.board;if(this.pumping===e||t.sources.length===0)return;this.pumping=e;let n=[],r;try{t.searching=!0;while(e===this.gen){while(n.length<mp&&t.queue.length>0&&this.wants()){let o=t.queue.shift();n.push({pick:o,passed:this.vet(o)})}if(this.ahead(t),!r&&t.queue.length<mp&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.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:t}){let n=Dt(t);if(!Ds(e,t,this.view.rating)||xs(t,this.view.block).length>0||!n)return!1;if(this.view.solo&&t.solo===!1)return!1;let{score:r,size:i,png:s}=this.view.narrow;if(Math.min(t.width,t.height)<i||e.scored&&t.score<r||s&&t.ext!=="png"||Hf(t,this.view.hide).length>0||this.view.hideTags.some((o)=>t.tags.includes(o)))return!1;return this.view.preset==="all"?["png","jpg","jpeg",""].includes(n.ext):["png",""].includes(t.ext)}async vet(e){let[t]=await Promise.all([this.passes(e),this.look(e)]);return t}async passes({site:e,post:t}){return this.view.preset==="all"||e.vouched||this.transparent(e,t)}probes(e){let t=this.probed.get(e.key);if(!t)t=Jc(e,"probes.json"),this.probed.set(e.key,t);return t}async transparent(e,t){let n=this.probes(e),r=n[t.id];if(r!==void 0)return r;try{let i=await eo(e,t,this.signal),s=Xs(e,t),o=(i===void 0?await Wf(s.site,s.url,this.signal):i)?.alpha===!0;return n[t.id]=o,this.unsaved.add(e.key),o}catch{return!1}}saveProbes(){for(let e of this.unsaved){let t=ee.find((n)=>n.key===e);if(t)Kc(t,"probes.json",this.probes(t))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=_t(t,n.id);this.posts.set(i,e);let s=r.kin.get(e)??[],o=this.looked.get(i),a=o&&{hash:o.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,s,a):void 0;if(u){if(u.posts.push(e),this.register(r,u,s,a),u.open)this.thumbQueue.push(e),this.thumbs();return}let c={posts:[e],open:!1};r.groups.push(c),this.register(r,c,s,a),this.thumbQueue.push(e),this.thumbs()}kindred(e,t,n){for(let r of t){let i=e.kindred.get(r);if(i)return i}return n&&e.shapes.find((r)=>up(r.shape,n))?.group}register(e,t,n,r){for(let i of n)if(!e.kindred.has(i))e.kindred.set(i,t);if(r)e.shapes.push({shape:r,group:t})}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=wd(this.home),r=Jc(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await Pi(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);Kc(e,"owners.json",r);let a=Lf(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(ti(t))return IE(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await to(e,n,this.signal,r);return ms(ta(t),{recursive:!0}),ps(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(this.thumbing<pp&&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:t,post:n}=e,r=ot.cols*this.cell.w,i=ot.rows*this.cell.h,s=Bs(t,n),o=Vt(Nt(t),"tile",`${yp(n.id,s.url)}-${r}x${i}.png`);if(!ti(o)){let a=this.previewPath(e);await this.cached(s.site,a,s.url),await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(_t(t,n.id),o),this.show(),this.draw()}select(){let e=this.view,t=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),LE),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n||!Dt(n.post))return;let{site:r}=n,i=this.board,s=new AbortController;this.fetch=s;try{await eo(r,n.post,s.signal);let o=Dt(n.post),a=this.origPath(r,e.id,o.ext);if(!ti(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=Xs(r,n.post,o),c=await this.cached(u.site,a,u.url,(f,d)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:f,size:d},this.draw()});if(s.signal.aborted)return;if(t.fetching=void 0,i!==this.board)return;let l={site:r,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let h=await this.render(l,"plain");if(s.signal.aborted||i!==this.board)return;if(h.clear===0&&Qr()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(r,e.id,a,s.signal),s.signal.aborted||i!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let f=await this.render(l,"cut").catch(()=>{return});if(s.signal.aborted||i!==this.board)return;if(f&&Ro(f.clear))l.using="cut";else Cc(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,t.tiles[t.focus]?.key===e.key)await this.present();this.preload()}catch(o){if(!s.signal.aborted&&!this.signal.aborted)t.error=Wc(r.name,o)}finally{if(t.fetching?.id===e.key)t.fetching=void 0;if(t.preparing===e.key)t.preparing=void 0;if(t.cutting===e.key)t.cutting=void 0;this.draw()}}async cutOut(e,t,n,r){let i=Vt(Nt(e),"cut",`${t}.png`);if(ti(i))return i;try{return ms(ta(i),{recursive:!0}),await ts(n,i,r),i}catch{Cc(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 t of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=HE)return;let n=e.tiles[t],r=n&&this.posts.get(n.key);if(!r||!Dt(r.post))continue;let{site:i,post:s}=r;this.prefetching++,eo(i,s,this.signal).then(async()=>{let o=Dt(s),a=this.origPath(i,s.id,o.ext),u=Xs(i,s,o);return await this.cached(u.site,a,u.url),this.render({site:i,id:s.id,key:n.key,path:a,ext:o.ext,size:0,using:"plain",failed:!1},"plain")}).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,t){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,jE),s=Math.max(1,Math.round(r*i/n)),o=Vt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}.png`),a=`${e.site.key}:${e.id}:${t}`,u=this.clarity.get(a);if(u!==void 0&&ti(o))return{clear:u,path:o};let c=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:o,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/$u(n,r).width});return this.clarity.set(a,c),{clear:c,path:o}}async present(){let e=this.current;if(!e)return;let t=e.using,{clear:n,path:r}=await this.render(e,t);if(this.current!==e||e.using!==t)return;this.view.shown={id:e.key,clear:n,bytes:e.size,path:r,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,t=e.tiles[e.focus],n=this.current;if(!t||n?.key!==t.key||e.preparing!==void 0||e.shown?.id!==t.key)return;e.installing=t.key,e.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,blur:this.blurring});let r=Jc(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",Kc(n.site,"owners.json",r),Qt(this.home),e.saved=`Background · ${this.entry.name} ← ${n.site.name} ${n.id}`,e.installed.push(t.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=tp(this.view,this.cols,this.rows),t="\x1B[?2026h";e.lines.forEach((r,i)=>{t+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of e.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)t+=Ym(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)t+=Zm(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))t+=zm(r),this.sent.delete(r),this.placed.delete(r);this.write(`${t}\x1B[?2026l`)}}async function Sp(e){let t=ue(),n=An(t),r=nr(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Mp(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
518
- `),0;return s}function Ip(e,t){let n=ue();if(nr(An(n).palettes,e),t==="next"||t==="prev"){let{key:r,at:i,of:s}=dd(n,e,t==="next"?1:-1);return Qt(n),process.stderr.write(`Background · ${e} ${i}/${s} ${r}
519
- `),0}if(t==="drop"){let{key:r,left:i}=gd(n,e);return Qt(n),process.stderr.write(`Background · ${e} removed ${r} · ${i} left
520
- `),0}if(t==="tuned")return Qt(n),0;throw Error(`unknown image action ${t} — next, prev, drop or tuned`)}import{execFileSync as Fp,spawnSync as ZE}from"node:child_process";import{chmodSync as zE,copyFileSync as VE,existsSync as dt,mkdirSync as qc,readdirSync as XE,readFileSync as ri,rmSync as Rp,writeFileSync as BE}from"node:fs";import{homedir as xE}from"node:os";import{dirname as ni,join as Ie}from"node:path";import{availableParallelism as qE,homedir as QE}from"node:os";var YE=4;async function ra(e,t,n=QE()){let r=nt(je(e)),i=jr(e),s=new Map(An(e).palettes.map((h)=>[h.name,h.backdrop])),o=Object.entries(r.palettes).flatMap(([h,f])=>{let d=s.get(h);return d?f.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:h,key:g.key,hue:d})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=!ie(e).terminals.includes("iterm2"),u=new _c(Math.min(YE,qE()-1)),c=await u.map(o.map(({name:h,key:f,hue:d})=>({job:"redraw",home:e,user:n,name:h,key:f,hue:d,blur:i,aligns:a})));u.close();let l=[];return c.forEach((h,f)=>{let{name:d,key:g}=o[f];if(h instanceof Error||h===null){t(` ▢ ${d} ${g} — ${h instanceof Error?h.message:"no original to draw it from"}, left as it was`);return}l.push({name:d,picture:h})}),bd(e,l),Qt(e,n),l.length}async function Np(){return await ra(ue(),(e)=>process.stderr.write(`${e}
521
- `)),0}function DE(e,t,n){for(let r of XE(t))e.push({from:Ie(t,r),to:Ie(n,r)})}function Zc(e){return JSON.parse(ri(Ie(e,"dist","manifest.json"),"utf8"))}function sa(e,t){let n=Ie(t.configHome,"ttheme"),r=[{from:Ie(t.root,"bin","ttheme.js"),to:Ie(n,"ttheme.js")},{from:Ie(t.root,"bin","ttheme.js.map"),to:Ie(n,"ttheme.js.map")},{from:Ie(t.root,"shell","ttheme.zsh"),to:Ie(n,"ttheme.zsh")},{from:Ie(t.root,"shell","launch-tab.zsh"),to:Ie(n,"launch-tab.zsh"),executable:!0}];DE(r,Ie(t.root,"shell","adapters"),Ie(n,"adapters"));let i=[{file:Ie(t.zdotdir,".zshrc"),block:Vd(n)}],s=Ie(n,"config.zsh"),o=Dd(dt(s)?ri(s,"utf8"):""),a={file:s,content:o},u=[];if(e.terminals.includes("alacritty")){let h=ar(t.configHome);if(dt(h)&&zi(ri(h,"utf8"),void 0)===void 0)u.push(`${h} already imports files under [general] — ttheme left it alone; add ${Ie(t.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let h=qr(t.configHome,t.home);if(dt(h)&&Vi(ri(h,"utf8"),"")===void 0)u.push(`${h} has no \`return config\` line — ttheme left it alone; call \`dofile("${Ie(n,"wezterm.lua")}")(config)\` from it yourself`)}let c=e.terminals.includes("windows-terminal");if(c&&!t.wtHome)u.push("Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.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 l={terminals:e.terminals,palettes:e.palettes,...c&&t.wtHome?{wtHome:t.wtHome}:{},...c&&t.wtProfile?{wtProfile:t.wtProfile}:{},...e.off?{off:!0}:{}};return u.push(...yg(t.configHome,e.terminals,t.home)),{home:t.home,copies:r,edits:i,settings:a,catalog:Zc(t.root),installed:l,notes:u}}function ev(e){try{return ie(e)}catch{return}}function Pp(e){try{return _e(e,Le(e),!1).palettes}catch{return[]}}function tv(e,t){let n=Zc(t.root),r=Ze(e.markets).includes(Z)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=Pp(t.configHome).filter((o)=>!i.has(o.name)&&(Me(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function Tp(e,t){let n=an(e);return n&&t.includes(n)?n:void 0}function nv(e,t,n){let r=sa(t,n),i=Tp(e,t.palettes),{author:s,markets:o,updates:a}=e;return{...r,installed:{...r.installed,...s?{author:s}:{},...i?{startup:i}:{},...o?{markets:o}:{},...a?{updates:a}:{}}}}function rv(e,t){let n=sa({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...Pp(t.configHome)].map((l)=>l.name)),i=e.palettes.filter((l)=>r.has(l)),s=e.palettes.filter((l)=>!r.has(l)),{startup:o,...a}=e,u={...a,palettes:i,...o&&i.includes(o)?{startup:o}:{}},c=s.length>0?[`Dropped ${s.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:u,notes:c}}function iv(e){try{return Fp(process.execPath,[Ie(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function Ap(e){let t=ft(e);return[e.terminals.map((n)=>_r[n]).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function sv(e){try{return ie(e).itermBase}catch{return}}function Qc(e,t=on()){for(let s of e.copies)if(qc(ni(s.to),{recursive:!0}),Rp(s.to,{force:!0}),Rp(`${s.to}.zwc`,{force:!0}),VE(s.from,s.to),s.executable)zE(s.to,493);qc(ni(e.settings.file),{recursive:!0}),BE(e.settings.file,e.settings.content);let n=ni(ni(e.settings.file)),r=sv(n),i=Di(r?{...e.installed,itermBase:r}:e.installed,t);if(Ze(i.markets).includes(Z))mo(n,e.catalog);yt(n,i),rt(n,Le(n),i,e.home);for(let s of e.edits){qc(ni(s.file),{recursive:!0});let o=dt(s.file)?ri(s.file,"utf8"):"";pi(s.file,Yi(o,s.block))}return or(i,t)}class _n extends Error{}function ia(e){if(Be(e))throw pr("Nothing changed"),new _n;return e}function Hp(e){return ko.filter((t)=>{if(t==="iterm2")return process.platform==="darwin";if(t==="windows-terminal")return e.wtHome!==void 0;return t!=="warp"||process.platform!=="win32"})}function ov(e,t){if(e==="iterm2")return dt(Ie(t.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return t.wtHome!==void 0;if(e==="warp")return dt(ni(Mo(t.home)));if(e==="wezterm")return dt(Ie(t.configHome,"wezterm"))||dt(Ie(t.home,".wezterm.lua"));return dt(Ie(t.configHome,e))}function av(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(t,n)=>Fp(t,n,{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 uv(e,t,n){return ia(await Wl({message:"Wire which terminals?",options:Hp(n).map((r)=>({value:r,label:_r[r],hint:r===e?"detected":void 0})),initialValues:t,required:!0}))}function Yc(e){let t=[...e.copies.filter((n)=>!dt(n.to)).map((n)=>n.to),...dt(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!ri(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
515
+ }`;async function jm(){if(Tc())return;if(process.platform==="darwin"){let[e="",t=""]=(await Zt("osascript",["-l","JavaScript","-e",CE])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!_m()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await Zt("wl-paste",["--list-types"])).stdout:(await Zt("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function Wm(e){let t=[],n="",r=0;while(r<e.length){if(e[r]!=="\x1B"){n+=e[r],r++;continue}if(e.startsWith("\x1B[200~",r)){let s=e.indexOf("\x1B[201~",r+6);if(s===-1)return{events:t,keys:n,pending:e.slice(r)};t.push({kind:"paste",text:e.slice(r+6,s)}),r=s+6;continue}if(e.startsWith("\x1B]5522;",r)||e.startsWith("\x1B]72;",r)){let s=[e.indexOf("\x1B\\",r),e.indexOf("\x07",r)].filter((h)=>h!==-1);if(s.length===0)return{events:t,keys:n,pending:e.slice(r)};let o=Math.min(...s),a=e.slice(r+2,o),[u="",c="",...l]=a.split(";");t.push({kind:"osc",code:u,meta:jE(c),payload:l.join(";")}),r=o+(e[o]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(e.slice(r+1,r+64));if(i){if(i[2]==="c")t.push({kind:"attributes"});else{let[s="0",o="0"]=(i[1]??"").split(";");t.push({kind:"mode",mode:Number(s),value:Number(o)})}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:t,keys:n,pending:e.slice(r)};n+=e[r],r++}return{events:t,keys:n,pending:""}}function jE(e){let t={};for(let n of e.split(":")){let r=n.indexOf("=");if(r>0)t[n.slice(0,r)]=n.slice(r+1)}return t}var ws=(e)=>Buffer.from(e).toString("base64"),Fc=(e)=>Buffer.from(e,"base64");function Om(e,t){return t.find((n)=>e.includes(n))}class Ac{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=ws(Pm("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(e,t){this.send=e,this.deliver=t}start(){let e="\x1B[?2004h";if(this.clipboard)e+="\x1B[?5522h";if(this.drops)e+=`\x1B]72;t=a;${Rc.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=${ws("ttheme")}:pw=${this.pw};${ws(".")}\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,t){if(e.type!=="read")return;let n=e.status??"";if(n==="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(n==="DATA"){if(r.mime=e.mime?Fc(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Fc(t));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 s=i.toString("utf8").split(/\s+/).filter(Boolean),o=Om(s,[...Oc,...TE]);if(!o){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:o,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${ws(u)}:pw=${a};${ws(o)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,t){let n=e.t??"";if(n==="m"){if(e.x==="-1"){this.offered=[];return}if(t){this.offered=t.split(" ").filter(Boolean);let a=Rc.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${a.length>0?1:0};${a.join(" ")}\x1B\\`)}return}if(n==="M"){let a=t?t.split(" ").filter(Boolean):this.offered,u=Om(a,Rc);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:a,index:a.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: ${t.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(t)r.chunks.push(Fc(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?ea(a).find((c)=>ME(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(Do(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var ot={pitch:25,cols:22,rows:9,height:13},lr={cols:25,rows:16},WE=2147483648,JE=-1073741826,KE=1600,qE="\x1B[0m",cn="\x1B[1m",we="\x1B[2m",bs="\x1B[31m",zt="\x1B[32m",Et="\x1B[33m",na="\x1B[1;34m",QE="\x1B[35m",YE={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 Vm(e){let t=[],n=0;while(n<e.length){let r=e[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(e.slice(n+1));if(i){t.push(YE[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let s=e[n+1]??"";if(/^[a-z]$/.test(s)){t.push(`alt-${s}`),n+=2;continue}t.push("esc"),n++;continue}t.push(r==="\r"||r===`
516
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Xm="\x1B]1337;ReportCellSize\x07\x1B[16t",Jm="\x1B]1337;ReportCellSize=";function Gc(e){let t=e.indexOf(Jm);if(t!==-1){let i=e.slice(t+Jm.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function ei(e,t){return{perRow:Math.max(1,Math.floor((e+1)/ot.pitch)),rowsVis:Math.max(1,Math.floor((t-4)/ot.height))}}function Bm(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function xm(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 Dm(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function ep(e){return`\x1B[38;2;${qe(e).join(";")}m`}function Hc(e){return`\x1B[48;2;${qe(e).join(";")}m`}function Je(e){return Array.from(e).length}class ra{parts=[];cols;constructor(e){this.cols=e}put(e,t,n=""){return this.parts.push({col:e,text:t,sgr:n}),e+Je(t)}run(e,t){let n=e;for(let[r,i]of t)n=this.put(n,r,i);return n}right(e,t){this.run(e-t.reduce((n,[r])=>n+Je(r),0),t)}render(){let e="";for(let{col:t,text:n,sgr:r}of this.parts){if(t>=this.cols||t<0)continue;let i=Array.from(n).slice(0,this.cols-t).join("");e+=`\x1B[${t+1}G${r}${i}${r?qE:""}`}return e}}function tp(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function ZE(e,t){if(!t)return tp(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function np(e){return e.replace(/_\([^)]*\)?$/,"")}function rp(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<KE?Et:we]}function $s(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Je(s[0])]:[],...i.map(([f,d])=>Je(f)+1+Je(d))];return(r.badge?Je(r.badge)+4:0)+l.reduce((f,d)=>f+d,0)+3*Math.max(0,l.length-1)+(o?3+Je(o[0])+1+Je(o[1]):0)};while(a()>t)if(i.length>2)i.splice(-2,1);else if(o)o=void 0;else if(i.length>1)i.splice(-2,1);else break;if(s&&a()>t){let l=Math.max(0,Je(s[0])-(a()-t)-1);s=[`${Array.from(s[0]).slice(0,l).join("")}…`,s[1]]}let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[[s]]:[],...i.map(([l,h])=>[[l,cn],[` ${h}`,we]])].forEach((l,h)=>{u=e.run(u+(h?3:0),l)}),o)e.right(t,[[o[0],cn],[` ${o[1]}`,we]])}function zE(e,t,n,r,i,s){let{ansi:o,selection:a,cursor:u}=s.colors,c=r<44?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let g=0;g<8;g++)l=(e[t]?.put(l,"▀".repeat(c),ep(o[g]??u)+Hc(o[g+8]??u))??l)+1;let h=["❯ ",zt],f=[[["~/code/demo",na],[" on ",we],["main",QE],[" +2",zt],[" ~1",Et]]];if(f.push([h,["git status -sb",""]]),r>=44)f.push([["## ",""],["main",zt],["...",""],["origin/main",bs],[" [ahead 1]",Et]]);if(f.push([[" M",bs],[" src/main.rs",""]]),f.push([["??",bs],[" notes.md",""]]),f.push([]),r>=44)f.push([h,["ls",""]]),f.push([["docs",na],[" ",""],["src",na],[" ",""],["tests",na],[" Cargo.toml README.md",""]]),f.push([]);f.push([h,["cargo test",""]]),f.push([[" ✓",zt],[" parses config",""]]);let d=[[" ✗",bs],[" renders frame",""]];if(r>=44)d.push([" expected ",we],["3",zt],[", received ",we],["2",bs]);f.push(d),f.push([]),f.push([h,["echo ",""],["selected text",Hc(a)],[" ",""],[" ",Hc(u)]]),f.forEach((g,m)=>{let $=t+2+m;if($<=i)e[$]?.run(n,g)})}function VE(e,t,n,r,i,s){e[t]?.put(n,`╭${"─".repeat(i-2)}╮`,s);for(let o=t+1;o<t+r-1;o++)e[o]?.put(n,"│",s),e[o]?.put(n+i-1,"│",s);e[t+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,s)}function Lc(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function XE(e){return`${ee[Math.floor(e/xt)]?.name??"local"} ${e%xt}`}function BE(e,t,n){let r=[{name:"all",moved:!1},...ee].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Lc(n,a):[` ${a} `,we];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+Je(o),0)<=t;e.run(0,i?r:[Lc(n)])}function xE(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,we);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":we]]),s=qn.filter((u)=>!n.block.includes(u)),o=ee.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,we),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,we]);e.right(t,u)}}function DE(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,zt]];if(e.cut==="off")return[["Opaque · x cuts out",Et]];if(e.cut==="failed")return[["Opaque · no cut-out",Et]];return[e.clear>0?[`${e.clear}% transparent`,zt]:["Opaque",Et]]}function Km(e){return e.site==="all"?"any site":e.site}function ip(e){if(e.installing!==void 0)return[`Installing ${e.palette} ← ${XE(e.installing)}`,Et];if(e.hint)return[e.hint,zt];if(e.error)return[e.error,Et];if(e.waiting!==void 0)return[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,Et];if(e.fetching)return[`Fetching ${e.fetching.id%xt} · ${ZE(e.fetching.got,e.fetching.size)}`,Et];if(e.cutting!==void 0)return[`Cutting out ${e.cutting%xt}`,Et];if(e.preparing!==void 0)return[`Preparing ${e.preparing%xt}`,Et];if(e.saved)return[e.saved,zt];if(e.note)return[e.note,we];return}function e1(e,t,n,r,i,s){let{perRow:o,rowsVis:a}=ei(n,r);xE(e[0],n,i,s),BE(e[1],n,i);for(let d=0;d<o*a;d++){let g=i.top*o+d,m=i.tiles[g];if(!m)break;let $=2+Math.floor(d/o)*ot.height,p=d%o*ot.pitch,E=g===i.focus;if(E)VE(e,$,p,ot.height,ot.pitch-1,s);if(m.thumb)t.push({id:m.key,path:m.thumb,row:$+1,col:p+1,cols:ot.cols,rows:ot.rows,z:-1});if(e[$+10]?.run(p+1,[...i.installed.includes(m.key)?[["✓ ",zt]]:[],...i.site==="all"?[["● ",`\x1B[${30+m.siteAnsi}m`]]:[],[String(m.id),E?cn:""],[" ",""],rp(m)]),m.mates.length>0)e[$+10]?.put(p+ot.cols,"≈",s);let y=m.artist?np(m.artist):m.owner&&`@${m.owner}`;if(y)e[$+11]?.put(p+1,y.slice(0,ot.cols-8),we);let S=[];if(m.score>0)S.push([`★${m.score}`,we]);if(m.variants>1)S.push([` ×${m.variants}`,s]);if(S.length>0)e[$+11]?.right(p+ot.cols+1,S)}let u=i.top*o,c=i.tiles.length-(i.top+a)*o,l=[...u>0?[`↑ ${u} above`]:[],...c>0?[`↓ ${c} more`]:[]];if(l.length>0)e[r-2]?.put(0,l.join(" "),we);if(!i.searching&&i.tiles.length===0&&!i.error)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${Km(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${Km(i)} — tab tries ${i.nextSite}`,we);let h=e[r-1],f=ip(i);if(i.searching&&i.tiles.length===0&&!f){$s(h,n,s,{badge:"FIND",lead:[i.preset==="cutouts"?"Checking PNG headers":"Fetching posts",we],right:["esc","back"]});return}$s(h,n,s,{badge:"FIND",lead:f,keys:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]})}function t1(e,t,n,r,i,s){let o=i.tiles[i.focus];if(!o)return;let a=i.shown?.id===o.key?i.shown:void 0,u=[Lc(i,o.site,o.siteAnsi),[" ",""],[String(o.id),cn],[" ",""],rp(o)];if(o.artist)u.push([` · ${np(o.artist)}`,""]);if(o.score>0)u.push([` · ★${o.score}`,we]);if(a)u.push([` · ${tp(a.bytes)}`,we]);if(o.owner)u.push([` · ${o.owner}`,we]);if(o.origin)u.push([` · ${o.origin}`,we]);if(a)u.push([" ",""],...DE(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),we]]);if(zE(e,3,2,n-4,r-2,i),i.shown)t.push({id:WE+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:JE});let c=ip(i);$s(e[r-1],n,s,{badge:"TRY",lead:c,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 n1={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab all, ${ee.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"],["Advanced","a or Advanced › in settings min score, min size, sites, hide, hide tags, PNG only"],["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"]]},Uc=6,r1=24;function ks(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function i1(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function qm(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>i1(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function sp(e,t,n){let r=e.indexOf(t);if(r!==-1)return e[(r+n+e.length)%e.length];let i=Number(t)||0;return(n>0?e.find((o)=>(Number(o)||0)>i):[...e].reverse().find((o)=>(Number(o)||0)<i))??e[n>0?0:e.length-1]}function cr(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&Je(r)+1+Je(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function s1(e){if(e.entry!=="number"||e.choices.includes(e.value))return e.choices;let t=e.choices.findIndex((n)=>(Number(n)||0)>Number(e.value));return t===-1?[...e.choices,e.value]:[...e.choices.slice(0,t),e.value,...e.choices.slice(t)]}function o1(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":we}];let o=s?[]:e.value.split(" "),a=(s?e.choices:s1(e)).map((u,c)=>{let l=o.includes(u),h=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${h}7;${30+r}m`:"":h?`\x1B[4m${we}`:we}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function Qm(e){if(e.entry==="text")return[{text:" ".repeat(r1),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Uc)}█ `,sgr:""}]:t}function a1(e){return e.reduce((t,n)=>t+Je(n.text)+1,0)-1}function Ym(e,t){let n=[[]],r=0;for(let i of e){let s=Je(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+Je(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=Je(s.text)+1}return n}function Zm(e){if(e.multi&&e.choices.every((t)=>e.default.split(" ").includes(t)))return"Default all";return`Default ${e.default&&e.default!==e.multi?.none?e.default:"none"}`}function zm(e){if(!e.tag)return"";if(!e.counts)return`${e.tag}: counting…`;let t=e.counts.map(({site:n,count:r})=>`${n} ${r===void 0?"no count":r.toLocaleString("en-US")}`);return`${e.tag}: ${t.join(" · ")}`}function u1(e,t){let n=e.advanced?"basic":"advanced";if(!t)return{keys:[["↑↓","setting"],["enter",n],["s","save"]],right:["esc","undo"]};if(e.typing!==void 0)return{keys:[["⌫","erase"],["enter","done"]],right:["esc","cancel"]};if(t.entry)return{keys:[["↑↓","setting"],...t.entry==="number"?[["←→","step"]]:[],["a",n],["enter","type"],["s","save"]],right:["esc","undo"]};return{keys:[["↑↓","setting"],["←→","value"],["a",n],...t.multi?[["space","toggle"]]:[],["enter","save"]],right:["esc","undo"]}}function c1(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((H)=>Je(H.label))),c=Math.max(...r.settings.map((H)=>Je(Zm(H)))),l=u+Math.max(...r.settings.map((H)=>a1(Qm(H))))+c+5,h=Math.min(t-2,Math.max(48,l)),f=h-u-c-5,d=h-7,g=[!1,!0].map((H)=>({advanced:H,rows:ks({settings:r.settings,advanced:H}).slice(0,-1)})),m=r.settings.map((H)=>Ym(Qm(H),f).length),$=Math.max(...g.map((H)=>H.rows.reduce((A,Q)=>A+m[Q],0))),p=Math.max(...g.map((H)=>cr(qm({settings:r.settings,advanced:H.advanced}),d).length),...r.settings.map((H)=>cr(H.about,d).length)),E=`${r.tag}: ${ee.map((H)=>`${H.name} 0,000,000`).join(" · ")}`,y=r.tag?Math.max(cr(E,d).length,cr(zm(r),d).length):0,S=$+p+y+8,w=Math.floor((t-h)/2),N=Math.max(1,Math.floor((n-1-S)/2)),v=`\x1B[7;${30+r.siteAnsi}m`;e[N]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,h-13))}╮`);for(let H=N+1;H<N+S-1;H++)e[H]?.put(w,`│${" ".repeat(h-2)}│`);let O=N+2;for(let H of ks(r).slice(0,-1)){let A=r.settings[H],Q=H===s;if(Q)e[O]?.put(w+2,"▶",i);if(e[O]?.put(w+4,A.label,Q?cn:""),A.value!==A.default)e[O]?.right(w+h-3,[[Zm(A),we]]);Ym(o1(A,Q,r.typing,r.siteAnsi),f).forEach((Ne,ke)=>{let x=w+u;for(let Ge of Ne)x=e[O+ke].put(x,Ge.text,Ge.sgr)+1}),O+=m[H]}let F=g.find((H)=>H.advanced!==r.advanced)?.rows??[],L=e[N+3+$];if(s===o)L.put(w+2,"▶",i);let U=L.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?v:cn);if(F.some((H)=>r.settings[H]?.value!==r.settings[H]?.default))L.put(U+1,"•",we);e[N+5+$]?.put(w+2,"─".repeat(h-4),we),cr(r.settings[s]?.about??qm(r),d).forEach((H,A)=>{e[N+6+$+A]?.put(w+4,H)}),cr(zm(r),d).forEach((H,A)=>{e[N+6+$+p+A]?.put(w+4,H,we)}),e[N+S-1]?.put(w,`╰${"─".repeat(h-2)}╯`);let{keys:ce,right:j}=u1(r,r.settings[s]);$s(e[n-1],t,i,{badge:"SET",keys:ce,right:j})}function l1(e,t,n,r,i){let s=n1[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,f])=>Je(f)+16))),a=s.map(([f,d])=>({label:f,parts:cr(d,o-16)})),u=a.reduce((f,{parts:d})=>f+d.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Keys ${"─".repeat(o-9)}╮`);for(let f=l+1;f<l+u-1;f++)e[f]?.put(c,`│${" ".repeat(o-2)}│`);let h=l+2;for(let{label:f,parts:d}of a){e[h]?.put(c+3,f,cn);for(let g of d)e[h]?.put(c+13,g),h++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),$s(e[n-1],t,i,{badge:"KEYS",right:["? esc","close"]})}function h1(e,t,n){let r=t.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),s=Math.max(...r.map((a)=>Je(a.value))),o=Math.max(7,...i.map(Je));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?cn+n:""]]),l?.right(2+s+2+o,[[i[u],we]])})}function op(e,t,n){let r=Array.from({length:n},()=>new ra(t)),i=[],s=ep(e.colors.cursor);if(t<lr.cols||n<lr.rows)return r[0]?.put(0,"ttheme find",cn+s),r[1]?.put(0,`Needs ${lr.cols}×${lr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",we),{lines:r.map((o)=>o.render()),images:i};if(e.mode==="try")t1(r,i,t,n,e,s);else e1(r,i,t,n,e,s);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let o=1;o<n-1;o++)r[o]=new ra(t);return h1(r,e,s),{lines:r.map((o)=>o.render()),images:[]}}if(e.help||e.panel!==void 0){let o=e.mode==="try"?i:[];for(let a=0;a<n;a++)r[a]=new ra(t);if(e.help)l1(r,t,n,e,s);else c1(r,t,n,e,s);return{lines:r.map((a)=>a.render()),images:o}}return{lines:r.map((o)=>o.render()),images:i}}var f1=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),d1=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),g1=0.04,m1=0.1,p1=0.05,w1=4096;function b1(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function $1(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...b1(i)].some((l)=>o.has(l)),u=Math.min(s.width,s.height),c=s.width>0&&s.height>0?s.width/s.height/(t.w/t.h):1;return(s.solo?2:0)+([...f1].some((l)=>o.has(l))?-3:0)+([...d1].some((l)=>o.has(l))?-1.5:0)+2*Math.min(1,u/t.h)+(a?1.5:-Math.min(1.5,Math.abs(Math.log(c))))+(n>0?1.5*Math.log1p(Math.max(0,s.score))/Math.log1p(n):0)+2*r}function ia(e,t,n=new Map){let r=new Map;for(let{site:i,post:s}of e)r.set(i,Math.max(r.get(i)??0,s.score));return e.map((i,s)=>({pick:i,at:s,score:$1(i,t,r.get(i.site)??0,n.get(i.post))})).sort((i,s)=>s.score-i.score||i.at-s.at).map(({pick:i})=>i)}function up(e){let t=new Map;for(let r of e)t.set(r.site,[...t.get(r.site)??[],r]);let n=[];for(let r=0;n.length<e.length;r++)for(let i of t.values()){let s=i[r];if(s)n.push(s)}return n}function _c(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function ap(e,t,n){let[r,i,s]=[_c(e),_c(t),_c(n)],o=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*s),a=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*s),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*s);return[0.2104542553*o+0.793617785*a-0.0040720468*u,1.9779984951*o-2.428592205*a+0.4505937099*u,0.0259040371*o+0.7827717662*a-0.808675766*u]}function cp(e,t){let n=t.map((o)=>ap(...qe(o))).filter(([,o,a])=>Math.hypot(o,a)>=g1);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/w1))),i=n.map(()=>0),s=0;for(let o=0;o<e.height;o+=r)for(let a=0;a<e.width;a+=r){let u=(o*e.width+a)*4;if(e.data[u+3]<128)continue;s++;let[c,l,h]=ap(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([f,d,g],m)=>{if(Math.hypot(c-f,l-d,h-g)<m1)i[m]=i[m]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/p1),0)/n.length}import{mkdirSync as gp,readFileSync as mp,writeFileSync as pp}from"node:fs";import{dirname as wp}from"node:path";import{isMainThread as v1,parentPort as bp,Worker as M1}from"node:worker_threads";var k1=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,y1=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"],[/zerochan\.net\/(\d+)(?:[?#\s]|$)/,"zerochan"]];function Cc(e){let t=/(\d+)_p(\d+)/.exec(e.source);return[...e.md5?[`md5:${e.md5}`]:[],...t&&e.source.includes("pximg")?[`pixiv:${t[1]}_p${t[2]}`]:[]]}function lp(e,t){let n=k1.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...y1.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function hp(e,t){let n=e.owner||e.artist;return n!==""&&n===(t.owner||t.artist)&&e.width===t.width&&e.height===t.height}function fp(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),h=0;for(let f=o;f<a;f++)for(let d=c;d<l;d++){let g=(f*e.width+d)*4,m=e.data[g+3]/255,$=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];h+=$*m+255*(1-m)}r.push(h/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function E1(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function dp(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;return Math.abs(Math.log(e.width/e.height/(t.width/t.height)))<0.01&&E1(e.hash,t.hash)<=2}var S1={thumb:"tile",match:"tile",show:"view",backdrop:"view",redraw:"view"};async function I1(e){if(e.job==="redraw")return Og(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);let t=Kn(new Uint8Array(mp(e.from)),$t);if(e.job==="backdrop")return go(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(mp(e.source)),cut:e.from!==e.source},e,e.blur),0;if(e.job==="match")return{match:cp(t,e.colors),hash:fp(t)};if(e.job==="thumb")return gp(wp(e.to),{recursive:!0}),pp(e.to,xa(hf(t,e.width,e.height))),0;let n=Bt(t);return gp(wp(e.to),{recursive:!0}),pp(e.to,xa(dd(t,e.colors,e.tone,e.width,e.height,e.blur))),n}function N1(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await I1(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class jc{worker;next=1;waiting=new Map;send(e){let t=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(t,{ok:n,no:r}),i.ref(),i.postMessage({...e,id:t})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let e=new M1(import.meta.filename);e.unref(),e.on("message",({id:n,value:r,error:i})=>{let s=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)e.unref();if(i!==void 0)s?.no(Error(i));else s?.ok(r)});let t=(n)=>{if(this.worker===e)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return e.on("error",t),e.on("exit",()=>t(void 0)),this.worker=e,e}drop(e){for(let t of this.waiting.values())t.no(e);this.waiting.clear()}}class Wc{lines=new Map;run(e){let t=S1[e.job],n=this.lines.get(t);if(!n)n=new jc,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Jc{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new jc)}async map(e){let t=[],n=0;return await Promise.all(this.lines.map(async(r)=>{while(n<e.length){let i=n++;try{t[i]=await r.send(e[i])}catch(s){t[i]=s instanceof Error?s:Error(String(s))}}})),t}close(){for(let e of this.lines)e.close()}}if(!v1&&bp)N1(bp);var hr=[{name:"TTHEME_FIND_RATING",label:"Rating",about:"The ratings to list, each site read in its own words — space ticks one, and one stays ticked",choices:Ni,multi:{read:Yn}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:qn,multi:{read:Rr,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...Yr()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Rf,entry:"number",advanced:!0},{name:"TTHEME_FIND_MIN_SIZE",label:"Min size",about:"The shorter side of a picture, in px — every site filters it. ←→ steps, or type any number",choices:Ff,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:ee.map((e)=>e.name),multi:{read:Fi},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:ou,multi:{read:eo,none:"none"},advanced:!0},{name:"TTHEME_FIND_HIDE_TAGS",label:"Hide tags",about:"Posts with any of these tags are left out, spaced like cosplay multiple_girls — checked as posts arrive",choices:[],entry:"text",advanced:!0},{name:"TTHEME_FIND_PNG",label:"PNG only",about:"PNG originals only — danbooru counts it, the others are told by the file; zerochan only where danbooru holds it",choices:["off","on"],advanced:!0}];function $p(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return Oi(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var A1=["fit","newest","score"];function qc(e){return A1.find((t)=>t===e)??"fit"}function H1(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var kp=12,L1=4,G1=150,U1=300,yp=12,_1=2,C1=150,j1=30,W1=4000,J1=8000,Ep=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,K1=process.platform==="win32"?"alt+v":"ctrl+v",vp=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",q1=1280,Mp=2,Q1=3,Y1=8;function oa(e,t){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:t}}function vs(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return vs(e.errors[0]);if(e.cause)return vs(e.cause);let t=e.code;if(typeof t==="string")return t;let n=(e.message||e.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function Qc(e,t){return`${e}: ${vs(t)}`}function Sp(e){return e.width*e.height}function Ip(e,t){return`${e}-${Np("sha1").update(t).digest("hex").slice(0,8)}`}function Z1(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function Yc(e,t){try{return JSON.parse(Rp(Vt(Nt(e),t),"utf8"))}catch{return{}}}function Zc(e,t,n){ys(Nt(e),{recursive:!0}),Es(Vt(Nt(e),t),`${JSON.stringify(n)}
517
+ `)}class Fp{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(hr.map((e)=>[e.name,$p(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 Wc;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Ac((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=F1(Vt(P1(),"ttheme-find-"));home;catalog;entry;blurring;constructor(e,t,n,r){this.home=e,this.catalog=t,this.entry=n,this.tone=Ar(n,n.signatureSlots),this.blurring=Wr(e),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:qc(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Yn(this.setting("TTHEME_FIND_RATING")),block:Rr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:Fi(this.setting("TTHEME_FIND_SITES")),hide:eo(this.setting("TTHEME_FIND_HIDE")),hideTags:Oi(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:hr.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),default:$p(i,ju(i.name)),multi:i.multi&&{none:i.multi.none},about:i.about,entry:i.entry,advanced:i.advanced,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=oa(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:ee[this.tab-1]}get sites(){return this.site?[this.site]:ee.filter((e)=>this.view.enabled.includes(e.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??L1}get nextTabName(){let e=(this.tab+1)%(ee.length+1);return e===0?"all":ee[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)}narrowed(){return uu(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return Vt(Nt(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=ro(e.site,e.post);return Vt(Nt(e.site),"thumb",`${Ip(e.post.id,t)}.${vn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=_t(n,r.id),s=Dt(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,owner:r.owner,artist:n===ta?Lm(r.source):r.artist,score:r.score,variants:t,origin:xs(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let e=this.view,t=this.board;e.tiles=t.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),e.checked=t.checked,e.total=t.total,e.searching=t.searching,e.note=t.note,e.focus=Math.max(0,Math.min(t.focus,e.tiles.length-1)),e.top=t.top}syncSite(){let e=this.view;e.site=this.tabName,e.siteAnsi=this.tabAnsi,e.nextSite=this.nextTabName}async run(){let{stdin:e,stdout:t}=process;e.setRawMode(!0),e.resume(),e.on("data",this.onData),t.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((o)=>{this.done=o}),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 s=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(),this.quietCount(),clearInterval(r),e.off("data",this.onData),t.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(),Kc(this.scratch,{recursive:!0,force:!0}),jf(),s}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 t=setTimeout(()=>{this.probeWait=void 0,e(null)},1000);this.probeWait=(n)=>{clearTimeout(t),this.probeWait=void 0,e(n)},this.write(Xm)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=Gc(this.input);n;n=Gc(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=Wm(this.input);if(this.input=t.pending,this.view.editing===void 0&&t.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(t.keys))this.pasted(t.keys),t.keys="";this.typed+=t.keys;for(let n of t.events)this.inbound(n);if(clearTimeout(this.partial),Z1(this.typed)){this.partial=setTimeout(this.flushKeys,j1);return}this.flushKeys()};flushKeys=()=>{let e=Vm(this.typed);this.typed="";for(let t of e)this.key(t)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((e)=>{let t=setTimeout(()=>{this.featureWait=void 0,e()},500);this.featureWait=()=>{clearTimeout(t),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 t=this.view;if(t.editing!==void 0&&e.trim()!==""&&!this.picture(e)){t.editing+=e.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(t.installing!==void 0||t.panel!==void 0||t.help)return;if(e.trim()===""){this.fromClipboard();return}this.attach(e)}picture(e){let t=e.trim();if(/^https?:\/\/\S+$/i.test(t))return!to(t,this.site??ee[0]);return ea(t).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 — ${vp}`);return}this.pasted(e.text);return}await this.bring(()=>xo(e.bytes,e.source))}notice(e,t=W1){let n=this.view;n.error=e,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===e)n.error=void 0,this.draw()},t),this.draw()}async peek(){let e=this.view,t;try{t=await jm()}catch{return}if(!t||t.stamp===this.peeked)return;if(this.peeked=t.stamp,!t.picture||e.installing!==void 0)return;e.hint=`Picture on the clipboard · ${K1} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},J1),this.draw()}async fromClipboard(){let e=this.view;if(Tc()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("Over SSH the clipboard is not here — drop the file");return}let t;try{t=await Cm(Vt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${vs(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await Pc(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${vp}`);return}if(this.picture(n)){await this.attach(n);return}if(e.editing===void 0)e.editing="";this.pasted(n)}async attach(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let i=to(t,this.site??ee[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=ea(t).sort((i,s)=>Number(!Ep.test(i))-Number(!Ep.test(s)));if(!n){this.notice("Nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Pc(n,i),r.length)}async bring(e,t=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 e(AbortSignal.any([r.signal,this.signal]))}catch(f){if(!r.signal.aborted)n.note=void 0,this.notice(vs(f),8000);return}if(r.signal.aborted)return;n.note=t>0?`The first picture of ${t+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 s=Um(i.bytes);Gm(s,i.source);let o=this.origPath(ta,s,i.ext);ys(sa(o),{recursive:!0}),Es(o,i.bytes);let a=T1(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",artist:"",score:0,rating:"s",md5:Np("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},c={site:ta,post:u},l=this.previewPath(c);ys(sa(l),{recursive:!0}),Es(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let h=oa(`local|post:${s}`,!1);this.board=h,this.boards.set(h.key,h),this.single(h,c)}single(e,t){e.searching=!1,this.posts.set(_t(t.site,t.post.id),t),e.groups=[{posts:[t],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(t),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>En(i)>En(r)?i:r),t=Math.ceil((En(e)-Date.now())/1000),n=t>0?t:void 0;if(n!==this.view.waiting)this.view.waiting=n,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 t=this.view;if(e==="ctrl-c"){this.finish(2);return}if(t.installing!==void 0)return;if(e==="focus-in"){this.peek();return}if(e==="focus-out"||e==="nop")return;if((e==="ctrl-v"||e==="alt-v")&&t.panel===void 0){this.fromClipboard();return}if(t.editing!==void 0){this.editKey(e);return}if(t.panel!==void 0){this.panelKey(e);return}if(t.help){if(e==="?"||e==="esc")t.help=!1,this.draw();return}if(this.cols<lr.cols||this.rows<lr.rows){if(e==="esc")this.finish(2);return}if(e==="?"){t.help=!0,this.draw();return}if(t.mode==="try"){this.tryKey(e);return}this.gridKey(e)}gridKey(e){let t=this.view,{perRow:n,rowsVis:r}=ei(this.cols,this.rows),s={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-t.focus,end:t.tiles.length}[e];if(s!==void 0){this.focus(t.focus+s);return}if(e==="enter"&&t.tiles[t.focus]){t.mode="try",t.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){t.preset=t.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"){this.tab=(this.tab+1)%(ee.length+1),this.syncSite(),this.turn();return}if(e==="/"){t.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){t.panel=0,t.advanced=!1,this.recount(),this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let t=this.view,n=t.panel??0,r=t.settings[n];if(t.typing!==void 0&&r){this.typeKey(r,e);return}let i=ks(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[Math.max(0,Math.min(i.length-1,s))]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=ks(t)[0]??0,this.draw();return}if(r?.entry&&(e==="enter"||r.entry==="number"&&/^[0-9]$/.test(e))){t.typing=e==="enter"?r.entry==="text"?r.value:"":e,this.draw();return}if((e==="left"||e==="right")&&r&&r.entry!=="text"){let s=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+s+r.choices.length)%r.choices.length;else r.value=sp(r.choices,r.value,s),this.recount();this.draw();return}if(e===" "&&r?.multi){let s=r.value.split(" "),o=r.choices.filter((u,c)=>c===r.cursor?!s.includes(u):s.includes(u)),a=r.multi.none;if(o.length>0||a!==void 0)r.value=o.length>0?o.join(" "):a,this.recount(),this.draw();return}if(e==="esc"){t.settings.forEach((s,o)=>{s.value=this.setting(hr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":Oi(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<Uc:/^[\x20-\x7e]$/.test(t))n.typing=r+t,this.draw()}quietCount(){clearTimeout(this.countTimer),this.counting?.abort(),this.counting=void 0}recount(){if(this.quietCount(),this.view.counts=void 0,!this.view.tag)return;let e=new AbortController;this.counting=e,this.countTimer=setTimeout(()=>void this.countPending(e),U1)}pending(){let e=(t)=>this.view.settings[hr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:qc(e("TTHEME_FIND_ORDER")),rating:Yn(e("TTHEME_FIND_RATING")),narrow:uu(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:Fi(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:ee.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await du(s,o.tags,r);return{site:s.name,...Number.isFinite(a)?{count:a}:{}}}catch{return{site:s.name}}}));if(this.counting===e&&this.view.panel!==void 0)this.view.counts=i,this.draw()}adopt(){let e=this.view,t=hr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=hr[i];if(s)this.values.set(s.name,r.value)});let n=hr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=Yn(this.setting("TTHEME_FIND_RATING")),e.block=Rr(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=qc(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=Fi(this.setting("TTHEME_FIND_SITES")),e.hide=eo(this.setting("TTHEME_FIND_HIDE")),e.hideTags=Oi(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=Vt(this.home,"ttheme","config.zsh");try{let n=ti(t)?Rp(t,"utf8"):"";return Es(t,e.reduce((r,[i,s])=>ig(r,i,s),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}editKey(e){let t=this.view,n=t.editing??"",r=t.suggest??[];if((e==="up"||e==="down")&&r.length>0){let i=t.pick??-1,s=e==="down"?Math.min(r.length-1,i+1):i-1;t.pick=s<0?void 0:s,this.draw();return}if(e==="esc"||e==="enter")this.quietSuggest();if(e==="esc"){if(t.editing=void 0,t.tag===""){this.finish(2);return}this.draw();return}if(e==="enter"){let i=t.pick===void 0?void 0:r[t.pick],s=i?n.replace(/\S*$/,i.value):n;if(t.editing=void 0,t.suggest=void 0,t.pick=void 0,s.trim()){this.commit(s.trim());return}if(t.tag===""){this.finish(2);return}this.draw();return}if(e==="backspace"){t.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(e.length===1&&e>=" ")t.editing=n+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 t=/\S*$/.exec(e.editing??"")?.[0]??"";if(!H1(t)){e.suggest=void 0;return}let n=[...new Map(Kd(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Q1);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await qf(t,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&e.editing!==void 0){let s=new Map(i.map((a)=>[a.value,a.count])),o=new Set(n.map((a)=>a.value));e.suggest=[...n.map((a)=>({...a,count:s.get(a.value)??0})),...i.filter((a)=>!o.has(a.value))].slice(0,Y1),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},G1)}async commit(e){let t=to(e,this.site??ee[0]);if(t){await this.jump(t.site,t.id);return}if(this.picture(e)){await this.attach(e);return}this.view.tag=e,this.boards.clear(),await this.search()}async jump(e,t){let n=++this.gen;this.tab=ee.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=oa(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Pi(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,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,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(_t(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}t+=r}}openPage(){let e=this.view.tiles[this.view.focus],t=e&&this.posts.get(e.key);if(!t)return;let n=process.platform==="darwin"?"open":"xdg-open";try{R1(n,[t.site.pageUrl(t.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let t=this.view;if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(t.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),t.fetching=void 0,t.mode="grid",t.error=void 0,this.draw()}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=ei(this.cols,this.rows),r=Math.floor(e.focus/t);if(r<e.top)e.top=r;if(r>e.top+n-1)e.top=r-n+1;this.board.top=e.top}query(e,t=this.view){let n=t.tag===this.entry.booru?qd(this.entry,e.key):[t.tag];if(n.length===0)return;let r=n.length>1,i=t.preset==="cutouts"?e.cutouts:"",s=r&&i.includes("~"),o=[r?n.map((c)=>`~${c}`).join(" "):n[0],e.rate(t.rating),...e.narrow(t.narrow),s?"":i,t.order==="score"?e.best:""].filter(Boolean),a=[],u=[];for(let c of o)if(hu([...a,c].join(" "))<=e.tagBudget)a.push(c);else u.push(c);return{tags:a.join(" "),notes:[...u.length>0?[`${e.name} takes ${e.tagBudget} tags — ${u.join(" ")} left out`]:[],...s?[`${e.name} ORs the names, so cutouts are told by the file`]:[],...t.narrow.score>0&&!e.scored?[`${e.name} keeps no score`]:[],...t.narrow.png&&e.guesses?[`${e.name} names a file type only where danbooru holds the file`]:[]]}}async search(){let e=++this.gen,t=oa(this.boardKey,!0);this.board=t,this.boards.set(t.key,t),this.view.error=void 0;let n=this.sites.flatMap((s)=>{let o=this.query(s);return o?[{site:s,...o}]:[]}),r=this.sites.filter((s)=>!n.some((o)=>o.site===s)),i=[...n.flatMap(({notes:s})=>s),...r.length>0?[`${this.entry.name} has no tag on ${r.map((s)=>s.name).join(", ")}`]:[]];if(t.note=i.length>0?i.join(" · "):void 0,n.length===0)t.searching=!1;this.show(),this.draw(),this.tally(e,t,n);try{let s=await Promise.all(n.map(async(o)=>({plan:o,owners:await this.mateOwners(o.site)})));if(e!==this.gen)return;t.sources=s.flatMap(({plan:{site:o,tags:a},owners:u})=>[...hu(a)+1<=o.tagBudget?[...u.keys()].map((c)=>({site:o,tags:`${a} user:${c}`,page:0,done:!1})):[],{site:o,tags:a,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(s){this.fail(e,s)}}async tally(e,t,n){let r=await Promise.allSettled(n.map(({site:i,tags:s})=>du(i,s,this.signal)));if(e===this.gen)t.total=r.reduce((i,s)=>i+(s.status==="fulfilled"&&Number.isFinite(s.value)?s.value:0),0),this.show(),this.draw()}fail(e,t,n=this.site){if(e!==this.gen||this.signal.aborted)return;this.board.error=Qc(n?.name??this.tabName,t),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.draw()}drop(e,t,n){for(let r of e.sources)if(r.site===t)r.done=!0;e.note=[e.note,Qc(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=ei(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+Mp)*e}need(){let{perRow:e,rowsVis:t}=ei(this.cols,this.rows);return(t+Mp)*e}live(e){return this.boards.get(e.key)===e}page(e,t,n){let r=`${e.key}|${t}|${n}`,i=this.pages.get(r);if(!i)i=Wf(e,t,n,this.signal).then((s)=>this.borrow(e,s)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e,t){let n=e===Ut?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{Jf(n,await Kf(n.map((r)=>r.md5),this.signal))}catch{}return t}async round(e){let t=ee.flatMap((a)=>{let u=e.sources.find((c)=>c.site===a&&!c.done);return u?[u]:[]}),n=await Promise.all(t.map(async(a)=>{try{return{source:a,posts:await this.page(a.site,a.tags,a.page)}}catch(u){if(e.sources.every((c)=>c.site===a.site)||this.signal.aborted)throw u;return this.drop(e,a.site,u),{source:a,posts:void 0}}}));if(!this.live(e))return;let r=[];for(let{source:a,posts:u}of n){if(!u)continue;a.page++,a.done=u.length<yn;let c=e.last.get(a);for(let l of u){let h=c&&hp(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:h};let f=_t(a.site,l.id);if(e.seen.has(f))continue;e.seen.add(f);let d={site:a.site,post:l};if(this.eligible(d))e.kin.set(d,[h,...lp(a.site,l)]),r.push(d);else e.checked++}if(c)e.last.set(a,c)}let i=this.dedupe(e,r),s=++e.rounds,o;if(this.view.order!=="fit")o=t.length>1?up(i):i;else{let a=ia(i,this.frame(),this.matched),u=a.slice(0,this.need());if(await this.looks(u),!this.live(e))return;o=[...ia(u,this.frame(),this.matched),...a.slice(u.length)]}for(let a of o)e.roundOf.set(a,s);e.queue.push(...o),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let t=e.queue.slice(0,this.need()).filter((n)=>!this.looking.has(_t(n.site,n.post.id)));if(t.length===0)return;this.aheading=!0,this.looks(t).then(()=>{this.aheading=!1;for(let n of new Set(t.map((r)=>e.roundOf.get(r)??0)))this.resort(e,n);this.ahead(e)})}resort(e,t){let n=e.queue.flatMap((i,s)=>e.roundOf.get(i)===t?[s]:[]),r=ia(n.map((i)=>e.queue[i]),this.frame(),this.matched);n.forEach((i,s)=>{e.queue[i]=r[s]})}dedupe(e,t){let n=[];for(let r of t){let i=Cc(r.post),s=i.map((a)=>e.same.get(a)).find(Boolean);if(!s){for(let a of i)e.same.set(a,r);n.push(r);continue}if(e.checked++,Sp(r.post)<=Sp(s.post))continue;for(let a of[...i,...Cc(s.post)])e.same.set(a,r);let o=n.indexOf(s);if(o>=0){n[o]=r;continue}this.replace(e,s,r)}return n}replace(e,t,n){e.roundOf.set(n,e.roundOf.get(t)??0);let r=e.queue.indexOf(t);if(r>=0){e.queue[r]=n;return}for(let i of e.groups){let s=i.posts.indexOf(t);if(s>=0){i.posts[s]=n,this.posts.set(_t(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e){let t=0;await Promise.all(Array.from({length:yp},async()=>{while(t<e.length)await this.look(e[t++])}))}look(e){let t=_t(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=ro(e.site,e.post);await this.cached(i.site,r,i.url);let s=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(t,s),this.matched.set(e.post,s.match),s})().catch(()=>{return}),this.looking.set(t,n);return n}async pump(){let e=this.gen,t=this.board;if(this.pumping===e||t.sources.length===0)return;this.pumping=e;let n=[],r;try{t.searching=!0;while(e===this.gen){while(n.length<kp&&t.queue.length>0&&this.wants()){let o=t.queue.shift();n.push({pick:o,passed:this.vet(o)})}if(this.ahead(t),!r&&t.queue.length<kp&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.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:t}){let n=Dt(t);if(!so(e,t,this.view.rating)||io(t,this.view.block).length>0||!n)return!1;if(this.view.solo&&t.solo===!1)return!1;let{score:r,size:i,png:s}=this.view.narrow;if(Math.min(t.width,t.height)<i||e.scored&&t.score<r||s&&t.ext!=="png"||_f(t,this.view.hide).length>0||this.view.hideTags.some((o)=>t.tags.includes(o)))return!1;return this.view.preset==="all"?["png","jpg","jpeg",""].includes(n.ext):["png",""].includes(t.ext)}async vet(e){let[t]=await Promise.all([this.passes(e),this.look(e)]);return t}async passes({site:e,post:t}){return this.view.preset==="all"||e.vouched||this.transparent(e,t)}probes(e){let t=this.probed.get(e.key);if(!t)t=Yc(e,"probes.json"),this.probed.set(e.key,t);return t}async transparent(e,t){let n=this.probes(e),r=n[t.id];if(r!==void 0)return r;try{let i=await oo(e,t,this.signal),s=no(e,t),o=(i===void 0?await Qf(s.site,s.url,this.signal):i)?.alpha===!0;return n[t.id]=o,this.unsaved.add(e.key),o}catch{return!1}}saveProbes(){for(let e of this.unsaved){let t=ee.find((n)=>n.key===e);if(t)Zc(t,"probes.json",this.probes(t))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=_t(t,n.id);this.posts.set(i,e);let s=r.kin.get(e)??[],o=this.looked.get(i),a=o&&{hash:o.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,s,a):void 0;if(u){if(u.posts.push(e),this.register(r,u,s,a),u.open)this.thumbQueue.push(e),this.thumbs();return}let c={posts:[e],open:!1};r.groups.push(c),this.register(r,c,s,a),this.thumbQueue.push(e),this.thumbs()}kindred(e,t,n){for(let r of t){let i=e.kindred.get(r);if(i)return i}return n&&e.shapes.find((r)=>dp(r.shape,n))?.group}register(e,t,n,r){for(let i of n)if(!e.kindred.has(i))e.kindred.set(i,t);if(r)e.shapes.push({shape:r,group:t})}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=yd(this.home),r=Yc(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await Pi(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);Zc(e,"owners.json",r);let a=Cf(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(ti(t))return O1(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await ao(e,n,this.signal,r);return ys(sa(t),{recursive:!0}),Es(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(this.thumbing<yp&&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:t,post:n}=e,r=ot.cols*this.cell.w,i=ot.rows*this.cell.h,s=ro(t,n),o=Vt(Nt(t),"tile",`${Ip(n.id,s.url)}-${r}x${i}.png`);if(!ti(o)){let a=this.previewPath(e);await this.cached(s.site,a,s.url),await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(_t(t,n.id),o),this.show(),this.draw()}select(){let e=this.view,t=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),C1),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n||!Dt(n.post))return;let{site:r}=n,i=this.board,s=new AbortController;this.fetch=s;try{await oo(r,n.post,s.signal);let o=Dt(n.post),a=this.origPath(r,e.id,o.ext);if(!ti(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=no(r,n.post,o),c=await this.cached(u.site,a,u.url,(f,d)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:f,size:d},this.draw()});if(s.signal.aborted)return;if(t.fetching=void 0,i!==this.board)return;let l={site:r,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let h=await this.render(l,"plain");if(s.signal.aborted||i!==this.board)return;if(h.clear===0&&Yr()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(r,e.id,a,s.signal),s.signal.aborted||i!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let f=await this.render(l,"cut").catch(()=>{return});if(s.signal.aborted||i!==this.board)return;if(f&&Ao(f.clear))l.using="cut";else Kc(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,t.tiles[t.focus]?.key===e.key)await this.present();this.preload()}catch(o){if(!s.signal.aborted&&!this.signal.aborted)t.error=Qc(r.name,o)}finally{if(t.fetching?.id===e.key)t.fetching=void 0;if(t.preparing===e.key)t.preparing=void 0;if(t.cutting===e.key)t.cutting=void 0;this.draw()}}async cutOut(e,t,n,r){let i=Vt(Nt(e),"cut",`${t}.png`);if(ti(i))return i;try{return ys(sa(i),{recursive:!0}),await is(n,i,r),i}catch{Kc(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 t of[e.focus+this.direction,e.focus-this.direction]){if(this.prefetching>=_1)return;let n=e.tiles[t],r=n&&this.posts.get(n.key);if(!r||!Dt(r.post))continue;let{site:i,post:s}=r;this.prefetching++,oo(i,s,this.signal).then(async()=>{let o=Dt(s),a=this.origPath(i,s.id,o.ext),u=no(i,s,o);return await this.cached(u.site,a,u.url),this.render({site:i,id:s.id,key:n.key,path:a,ext:o.ext,size:0,using:"plain",failed:!1},"plain")}).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(e,t){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,q1),s=Math.max(1,Math.round(r*i/n)),o=Vt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}.png`),a=`${e.site.key}:${e.id}:${t}`,u=this.clarity.get(a);if(u!==void 0&&ti(o))return{clear:u,path:o};let c=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:o,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/Eu(n,r).width});return this.clarity.set(a,c),{clear:c,path:o}}async present(){let e=this.current;if(!e)return;let t=e.using,{clear:n,path:r}=await this.render(e,t);if(this.current!==e||e.using!==t)return;this.view.shown={id:e.key,clear:n,bytes:e.size,path:r,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,t=e.tiles[e.focus],n=this.current;if(!t||n?.key!==t.key||e.preparing!==void 0||e.shown?.id!==t.key)return;e.installing=t.key,e.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,blur:this.blurring});let r=Yc(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",Zc(n.site,"owners.json",r),Qt(this.home),e.saved=`Background · ${this.entry.name} ← ${n.site.name} ${n.id}`,e.installed.push(t.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=op(this.view,this.cols,this.rows),t="\x1B[?2026h";e.lines.forEach((r,i)=>{t+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of e.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)t+=Bm(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)t+=xm(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))t+=Dm(r),this.sent.delete(r),this.placed.delete(r);this.write(`${t}\x1B[?2026l`)}}async function Op(e){let t=ue(),n=Tn(t),r=tr(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Fp(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
518
+ `),0;return s}function Pp(e,t){let n=ue();if(tr(Tn(n).palettes,e),t==="next"||t==="prev"){let{key:r,at:i,of:s}=wd(n,e,t==="next"?1:-1);return Qt(n),process.stderr.write(`Background · ${e} ${i}/${s} ${r}
519
+ `),0}if(t==="drop"){let{key:r,left:i}=bd(n,e);return Qt(n),process.stderr.write(`Background · ${e} removed ${r} · ${i} left
520
+ `),0}if(t==="tuned")return Qt(n),0;throw Error(`unknown image action ${t} — next, prev, drop or tuned`)}import{execFileSync as Lp,spawnSync as B1}from"node:child_process";import{chmodSync as x1,copyFileSync as D1,existsSync as dt,mkdirSync as zc,readdirSync as ev,readFileSync as ri,rmSync as Ap,writeFileSync as tv}from"node:fs";import{homedir as nv}from"node:os";import{dirname as ni,join as Ie}from"node:path";import{availableParallelism as z1,homedir as V1}from"node:os";var X1=4;async function aa(e,t,n=V1()){let r=rt(je(e)),i=Wr(e),s=new Map(Tn(e).palettes.map((h)=>[h.name,h.backdrop])),o=Object.entries(r.palettes).flatMap(([h,f])=>{let d=s.get(h);return d?f.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:h,key:g.key,hue:d})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=!ie(e).terminals.includes("iterm2"),u=new Jc(Math.min(X1,z1()-1)),c=await u.map(o.map(({name:h,key:f,hue:d})=>({job:"redraw",home:e,user:n,name:h,key:f,hue:d,blur:i,aligns:a})));u.close();let l=[];return c.forEach((h,f)=>{let{name:d,key:g}=o[f];if(h instanceof Error||h===null){t(` ▢ ${d} ${g} — ${h instanceof Error?h.message:"no original to draw it from"}, left as it was`);return}l.push({name:d,picture:h})}),Ed(e,l),Qt(e,n),l.length}async function Tp(){return await aa(ue(),(e)=>process.stderr.write(`${e}
521
+ `)),0}function rv(e,t,n){for(let r of ev(t))e.push({from:Ie(t,r),to:Ie(n,r)})}function Bc(e){return JSON.parse(ri(Ie(e,"dist","manifest.json"),"utf8"))}function ca(e,t){let n=Ie(t.configHome,"ttheme"),r=[{from:Ie(t.root,"bin","ttheme.js"),to:Ie(n,"ttheme.js")},{from:Ie(t.root,"bin","ttheme.js.map"),to:Ie(n,"ttheme.js.map")},{from:Ie(t.root,"shell","ttheme.zsh"),to:Ie(n,"ttheme.zsh")},{from:Ie(t.root,"shell","launch-tab.zsh"),to:Ie(n,"launch-tab.zsh"),executable:!0}];rv(r,Ie(t.root,"shell","adapters"),Ie(n,"adapters"));let i=[{file:Ie(t.zdotdir,".zshrc"),block:tg(n)}],s=Ie(n,"config.zsh"),o=sg(dt(s)?ri(s,"utf8"):""),a={file:s,content:o},u=[];if(e.terminals.includes("alacritty")){let h=or(t.configHome);if(dt(h)&&Bi(ri(h,"utf8"),void 0)===void 0)u.push(`${h} already imports files under [general] — ttheme left it alone; add ${Ie(t.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(e.terminals.includes("wezterm")){let h=Qr(t.configHome,t.home);if(dt(h)&&xi(ri(h,"utf8"),"")===void 0)u.push(`${h} has no \`return config\` line — ttheme left it alone; call \`dofile("${Ie(n,"wezterm.lua")}")(config)\` from it yourself`)}let c=e.terminals.includes("windows-terminal");if(c&&!t.wtHome)u.push("Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(e.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 l={terminals:e.terminals,palettes:e.palettes,...c&&t.wtHome?{wtHome:t.wtHome}:{},...c&&t.wtProfile?{wtProfile:t.wtProfile}:{},...e.off?{off:!0}:{}};return u.push(...Ng(t.configHome,e.terminals,t.home)),{home:t.home,copies:r,edits:i,settings:a,catalog:Bc(t.root),installed:l,notes:u}}function iv(e){try{return ie(e)}catch{return}}function Gp(e){try{return _e(e,Le(e),!1).palettes}catch{return[]}}function sv(e,t){let n=Bc(t.root),r=Ze(e.markets).includes(Z)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=Gp(t.configHome).filter((o)=>!i.has(o.name)&&($e(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function Up(e,t){let n=on(e);return n&&t.includes(n)?n:void 0}function ov(e,t,n){let r=ca(t,n),i=Up(e,t.palettes),{author:s,markets:o,updates:a}=e;return{...r,installed:{...r.installed,...s?{author:s}:{},...i?{startup:i}:{},...o?{markets:o}:{},...a?{updates:a}:{}}}}function av(e,t){let n=ca({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...Gp(t.configHome)].map((l)=>l.name)),i=e.palettes.filter((l)=>r.has(l)),s=e.palettes.filter((l)=>!r.has(l)),{startup:o,...a}=e,u={...a,palettes:i,...o&&i.includes(o)?{startup:o}:{}},c=s.length>0?[`Dropped ${s.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:u,notes:c}}function uv(e){try{return Lp(process.execPath,[Ie(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function _p(e){let t=ft(e);return[e.terminals.map((n)=>Cr[n]).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function cv(e){try{return ie(e).itermBase}catch{return}}function Vc(e,t=sn()){for(let s of e.copies)if(zc(ni(s.to),{recursive:!0}),Ap(s.to,{force:!0}),Ap(`${s.to}.zwc`,{force:!0}),D1(s.from,s.to),s.executable)x1(s.to,493);zc(ni(e.settings.file),{recursive:!0}),tv(e.settings.file,e.settings.content);let n=ni(ni(e.settings.file)),r=cv(n),i=ns(r?{...e.installed,itermBase:r}:e.installed,t);if(Ze(i.markets).includes(Z))ko(n,e.catalog);yt(n,i),it(n,Le(n),i,e.home);for(let s of e.edits){zc(ni(s.file),{recursive:!0});let o=dt(s.file)?ri(s.file,"utf8"):"";pi(s.file,Vi(o,s.block))}return sr(i,t)}class Un extends Error{}function ua(e){if(Be(e))throw pr("Nothing changed"),new Un;return e}function Cp(e){return So.filter((t)=>{if(t==="iterm2")return process.platform==="darwin";if(t==="windows-terminal")return e.wtHome!==void 0;return t!=="warp"||process.platform!=="win32"})}function lv(e,t){if(e==="iterm2")return dt(Ie(t.home,"Library","Application Support","iTerm2"));if(e==="windows-terminal")return t.wtHome!==void 0;if(e==="warp")return dt(ni(Fo(t.home)));if(e==="wezterm")return dt(Ie(t.configHome,"wezterm"))||dt(Ie(t.home,".wezterm.lua"));return dt(Ie(t.configHome,e))}function hv(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let e=(t,n)=>Lp(t,n,{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 fv(e,t,n){return ua(await Ql({message:"Wire which terminals?",options:Cp(n).map((r)=>({value:r,label:Cr[r],hint:r===e?"detected":void 0})),initialValues:t,required:!0}))}function Xc(e){let t=[...e.copies.filter((n)=>!dt(n.to)).map((n)=>n.to),...dt(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!ri(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
522
522
  ${t.join(`
523
- `)}`)}function Lp(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function cv(e,t){let n=e.palettes.find((i)=>i.name===ft(t)),r=process.stdout.isTTY===!0&&!Un()&&!process.env.TMUX&&yo(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(Dr(n)),!0}function lv(e,t){let n=ft(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${an(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function hv(e){ZE("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Ie(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function fv(e,t,n,r){let i=Lp(e.catalog,t.palettes);jn([`${i.join(", ")} (${t.palettes.length})`,...lv(e.installed,n)].join(`
524
- `),`Installed ${t.palettes.length} palettes`),jn(["exec zsh The ttheme command in this tab",...Gp(t.terminals,e,r)].join(`
525
- `),"Next"),va("Done")}function Gp(e,t,n){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(...dv(ft(t.installed),n));return[...r,...t.notes]}function Up(e){return e?(t)=>dn.step(t):(t)=>console.log(t)}async function Op(e,t,n){let r=rv(e,t),i=on(),s=Qc(r,i);Yc(r),await ra(t.configHome,Up(n),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...Gp(r.installed.terminals,r,s&&i.running())],a=`Updated to ${Ve.version} — kept ${Ap(r.installed)}`;if(!n){console.log([a,...o].join(`
526
- `));return}jn(o.join(`
527
- `),a),va("Done")}function dv(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e)n.push(t?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e}`:`iTerm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return n}function gv(e,t){let n=[`Placed ${e.copies.length} files`,`Settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`Wired ${r.file}`)];if(t.terminals.includes("ghostty"))n.push("Restart Ghostty to pick up its config");if(t.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(t.terminals.includes("alacritty"))n.push("Alacritty reloads its config by itself");if(t.terminals.includes("wezterm")||t.terminals.includes("windows-terminal"))n.push("WezTerm and Windows Terminal reload their config by themselves");if(t.terminals.includes("iterm2"))n.push('iTerm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...e.notes),n.push("No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
528
- `))}async function _p(e={}){let t=Ie(import.meta.dirname,"..");if(!dt(Ie(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!dt(Ie(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Qo()}let n=xE(),r=ue(),i=process.env.ZDOTDIR??n,s=av(),o=process.env.WT_PROFILE_ID,a={root:t,home:n,configHome:r,zdotdir:i,...s?{wtHome:s}:{},...o?{wtProfile:o}:{}},u=yo(process.env),c=Hp(a).filter((N)=>N===u||ov(N,a));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 l=ev(r);if(e.yes&&l){await Op(l,a,!1);return}if(e.yes){if(c.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let N={terminals:c,palettes:[]},E=sa(N,a);Qc(E),Yc(E),gv(E,N);return}if(Os("ttheme init"),l){let N=iv(r);if(ia(await Ht({message:`ttheme${N?` ${N}`:""} is installed — ${Ap(l)}
529
- ${N===Ve.version?"Reinstall":"Update to"} ${Ve.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await Op(l,a,!0);return}}let h=await uv(u,l?.terminals??c,a),f=l?tv(l,a):Zc(t),d=l?await yc(f,l.palettes,"palette",!0):await yc(f,[],"series",!0);if(!d)throw pr("Nothing changed"),new _n;let g=(l&&Tp(l,d))??d[0],m=d.length>1&&yo(process.env)!=="warp",$=ia(await Ht({message:m?"Pick a default palette in ttheme preview once installed?":`Wear ${g} in every tab?`,initialValue:l?!l.off:!0})),w={terminals:h,palettes:d,off:!$},M=l?nv(l,w,a):sa(w,a);if(jn([`Install ${d.length} palettes — ${Lp(f,d).join(", ")}`,`Copy ${M.copies.length} files under ${r}`,`Write ${M.settings.file}`,...M.edits.map((N)=>`Edit ${N.file} — a ttheme block: source ttheme.zsh`),...kg(r,M.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",$?m?`Open ttheme preview — every tab wears the palette picked there, ${g} until then`:`Paint every tab with ${g}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...h.includes("iterm2")&&$?['Make "ttheme · default" the iTerm2 default profile']:[]].join(`
530
- `),`Wiring ${h.map((N)=>_r[N]).join(", ")}`),!ia(await Ht({message:"Apply these changes?"})))throw pr("Nothing changed"),new _n;let y=on(),S=Qc(M,y);if(Yc(M),await ra(r,Up(!0),n),$&&m)hv(r);let p=ie(r);fv({...M,catalog:f,installed:p},w,cv(f,p),S&&y.running())}import{existsSync as oa,readdirSync as mv,readFileSync as pv,rmSync as wv,utimesSync as bv}from"node:fs";import{homedir as $v}from"node:os";import{dirname as kv,join as ii}from"node:path";function zc(e){return oa(e)?pv(e,"utf8"):""}function yv(e){try{return ie(e)}catch{return}}function Ev(e,t){let n=So(t,e),r=zc(n);if(!Eo(r)?.includes(`path = "${pe("")}`))return;return{file:n,content:vo(r,zc(Qu(e))||qu)}}function vv(e){let{home:t,configHome:n}=e,r=yv(n),i=[],s=(c,l)=>{let h=zc(c),f=l(h);if(f!==h)i.push({file:c,content:f})};s(ii(e.zdotdir,".zshrc"),Zi),s(sr("ghostty",n),Zi),s(sr("kitty",n),Zi),s(ar(n),Zi),s(qr(n,t),ig);let o=Ev(n,t);if(o)i.push(o);let a=[];for(let c of["ghostty","kitty","alacritty","wezterm","warp"]){let l=ir(c,n,t);if(oa(l))a.push(...mv(l).flatMap((h)=>h.startsWith(pe(""))?[ii(l,h)]:[]))}let u=[es(t),...r?.wtHome?[kv(Io(r.wtHome))]:[],ii(n,"ttheme"),e.cacheDir,e.stateDir];return a.push(...u.filter((c)=>oa(c))),{edits:i,removals:a,touches:r?.wtHome?Yu(r.wtHome):[],...r?{state:r}:{}}}function Mv(e,t=on()){let n=[];for(let{file:i,content:s}of e.edits){let o=th(i,s);n.push(o==="removed"?`Removed ${i} — ttheme had created it`:o==="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&&or({...e.state,off:!0},t))n.push("Gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)wv(i,{recursive:!0,force:!0});if(e.removals.length>0)n.push(`Deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)bv(i,r,r);return n}function Sv(){let e=$v();return{home:e,configHome:ue(),zdotdir:process.env.ZDOTDIR??e,cacheDir:Or(),stateDir:ii(process.env.XDG_STATE_HOME??ii(e,".local","state"),"ttheme")}}async function Cp(e=!1){let t=Sv(),n=vv(t);if(n.edits.length===0&&n.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=ii(t.configHome,"ttheme");Os("ttheme uninstall"),jn([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${oa(ho(t.configHome))?`, and your markets under ${ho(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
531
- `),"Uninstall");let i=await Ht({message:"Remove ttheme?"});if(Be(i)||!i)throw pr("Nothing changed"),new _n}for(let r of Mv(n))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var Nv=new Set(["add","remove","market","default","on","off"]),Rv={default:([e])=>lm(e),on:()=>hm(),off:()=>fm(),browse:()=>km(),list:([e],{json:t})=>mm(e,t),add:(e,{market:t})=>um(e,t),remove:(e)=>cm(e),update:()=>pm(),market:([e,t])=>Zg(e,t),new:([e],{from:t,in:n})=>rm(e,t,n),edit:([e])=>im(e),check:([e],{fix:t})=>om(e,t),share:([e])=>am(e),init:(e,{yes:t})=>_p({yes:t}),uninstall:(e,{yes:t})=>Cp(t),build:(e,{only:t})=>Qo({only:t}),find:([e])=>Sp(e),image:([e,t])=>Ip(e,t),redraw:()=>Np()},Ov=Ki.map((e)=>({...e,run:Rv[e.name]}));class fr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function jp(e){let t=Ov.find((n)=>n.name===e);if(!t)throw new fr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function Fv(e,t){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:s,multiple:o}]of Object.entries(e.flags??{}))n[r]={type:i,multiple:o===!0,...s?{short:s}:{}};try{return Iv({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new fr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function Pv(e){let[t,...n]=e;if(t===void 0)return{kind:"help",code:1};if(t==="-h"||t==="--help")return{kind:"help",code:0};if(t==="-V"||t==="--version")return{kind:"version"};if(t==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:jp(n[0]),code:0}}let r=jp(t),i=Fv(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:h}]of Object.entries(r.flags??{}))for(let f of[i.values[l]??[]].flat())if(h&&!h.includes(String(f)))throw new fr(`--${l} takes ${h.join(", ")} — not ${f}`,r);let s=i.positionals,o=r.args.filter((l)=>l.startsWith("<")).length,a=r.args.some((l)=>l.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(s.length<o)throw new fr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new fr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function Wp(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function Vc(e,t=!1){if(!e)return qi(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Ji(e)}`,"",e.about,...e.actions?["","Actions:",...Wp(e.actions)]:[],...n.length>0?["","Options:",...Wp(n)]:[]].join(`
532
- `)}async function Jp(e){let t;try{let n=Pv(e);if(n.kind==="version")return console.log(Ve.version),0;if(n.kind==="help"){if(n.code===0)console.log(Vc(n.verb,n.all));else console.error(Vc(n.verb,n.all));return n.code}if(t=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");if(Nv.has(n.verb.name))await Fg();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof fr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
523
+ `)}`)}function jp(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function dv(e,t){let n=e.palettes.find((i)=>i.name===ft(t)),r=process.stdout.isTTY===!0&&!Gn()&&!process.env.TMUX&&Io(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(Dr(n)),!0}function gv(e,t){let n=ft(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${on(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function mv(e){B1("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Ie(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function pv(e,t,n,r){let i=jp(e.catalog,t.palettes);Cn([`${i.join(", ")} (${t.palettes.length})`,...gv(e.installed,n)].join(`
524
+ `),`Installed ${t.palettes.length} palettes`),Cn(["exec zsh The ttheme command in this tab",...Wp(t.terminals,e,r)].join(`
525
+ `),"Next"),Na("Done")}function Wp(e,t,n){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(...wv(ft(t.installed),n));return[...r,...t.notes]}function Jp(e){return e?(t)=>hn.step(t):(t)=>console.log(t)}async function Hp(e,t,n){let r=av(e,t),i=sn(),s=Vc(r,i);Xc(r),await aa(t.configHome,Jp(n),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...Wp(r.installed.terminals,r,s&&i.running())],a=`Updated to ${Ve.version} — kept ${_p(r.installed)}`;if(!n){console.log([a,...o].join(`
526
+ `));return}Cn(o.join(`
527
+ `),a),Na("Done")}function wv(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e)n.push(t?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e}`:`iTerm2 default "ttheme · default" wears ${e} and follows \`ttheme default\``);return n}function bv(e,t){let n=[`Placed ${e.copies.length} files`,`Settings in ${e.settings.file} — edit later with \`ttheme config\``,...e.edits.map((r)=>`Wired ${r.file}`)];if(t.terminals.includes("ghostty"))n.push("Restart Ghostty to pick up its config");if(t.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(t.terminals.includes("alacritty"))n.push("Alacritty reloads its config by itself");if(t.terminals.includes("wezterm")||t.terminals.includes("windows-terminal"))n.push("WezTerm and Windows Terminal reload their config by themselves");if(t.terminals.includes("iterm2"))n.push('iTerm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...e.notes),n.push("No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
528
+ `))}async function Kp(e={}){let t=Ie(import.meta.dirname,"..");if(!dt(Ie(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!dt(Ie(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Vo()}let n=nv(),r=ue(),i=process.env.ZDOTDIR??n,s=hv(),o=process.env.WT_PROFILE_ID,a={root:t,home:n,configHome:r,zdotdir:i,...s?{wtHome:s}:{},...o?{wtProfile:o}:{}},u=Io(process.env),c=Cp(a).filter((N)=>N===u||lv(N,a));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 l=iv(r);if(e.yes&&l){await Hp(l,a,!1);return}if(e.yes){if(c.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let N={terminals:c,palettes:[]},v=ca(N,a);Vc(v),Xc(v),bv(v,N);return}if(Ls("ttheme init"),l){let N=uv(r);if(ua(await Ht({message:`ttheme${N?` ${N}`:""} is installed — ${_p(l)}
529
+ ${N===Ve.version?"Reinstall":"Update to"} ${Ve.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await Hp(l,a,!0);return}}let h=await fv(u,l?.terminals??c,a),f=l?sv(l,a):Bc(t),d=l?await Sc(f,l.palettes,"palette",!0):await Sc(f,[],"series",!0);if(!d)throw pr("Nothing changed"),new Un;let g=(l&&Up(l,d))??d[0],m=d.length>1&&Io(process.env)!=="warp",$=ua(await Ht({message:m?"Pick a default palette in ttheme preview once installed?":`Wear ${g} in every tab?`,initialValue:l?!l.off:!0})),p={terminals:h,palettes:d,off:!$},E=l?ov(l,p,a):ca(p,a);if(Cn([`Install ${d.length} palettes — ${jp(f,d).join(", ")}`,`Copy ${E.copies.length} files under ${r}`,`Write ${E.settings.file}`,...E.edits.map((N)=>`Edit ${N.file} — a ttheme block: source ttheme.zsh`),...Ig(r,E.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",$?m?`Open ttheme preview — every tab wears the palette picked there, ${g} until then`:`Paint every tab with ${g}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...h.includes("iterm2")&&$?['Make "ttheme · default" the iTerm2 default profile']:[]].join(`
530
+ `),`Wiring ${h.map((N)=>Cr[N]).join(", ")}`),!ua(await Ht({message:"Apply these changes?"})))throw pr("Nothing changed"),new Un;let y=sn(),S=Vc(E,y);if(Xc(E),await aa(r,Jp(!0),n),$&&m)mv(r);let w=ie(r);pv({...E,catalog:f,installed:w},p,dv(f,w),S&&y.running())}import{existsSync as la,readdirSync as $v,readFileSync as kv,rmSync as yv,utimesSync as Ev}from"node:fs";import{homedir as vv}from"node:os";import{dirname as Mv,join as ii}from"node:path";function xc(e){return la(e)?kv(e,"utf8"):""}function Sv(e){try{return ie(e)}catch{return}}function Iv(e,t){let n=Oo(t,e),r=xc(n);if(!No(r)?.includes(`path = "${pe("")}`))return;return{file:n,content:Ro(r,xc(zu(e))||Zu)}}function Nv(e){let{home:t,configHome:n}=e,r=Sv(n),i=[],s=(c,l)=>{let h=xc(c),f=l(h);if(f!==h)i.push({file:c,content:f})};s(ii(e.zdotdir,".zshrc"),Xi),s(ir("ghostty",n),Xi),s(ir("kitty",n),Xi),s(or(n),Xi),s(Qr(n,t),lg);let o=Iv(n,t);if(o)i.push(o);let a=[];for(let c of["ghostty","kitty","alacritty","wezterm","warp"]){let l=rr(c,n,t);if(la(l))a.push(...$v(l).flatMap((h)=>h.startsWith(pe(""))?[ii(l,h)]:[]))}let u=[rs(t),...r?.wtHome?[Mv(Po(r.wtHome))]:[],ii(n,"ttheme"),e.cacheDir,e.stateDir];return a.push(...u.filter((c)=>la(c))),{edits:i,removals:a,touches:r?.wtHome?Vu(r.wtHome):[],...r?{state:r}:{}}}function Rv(e,t=sn()){let n=[];for(let{file:i,content:s}of e.edits){let o=sh(i,s);n.push(o==="removed"?`Removed ${i} — ttheme had created it`:o==="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&&sr({...e.state,off:!0},t))n.push("Gave iTerm2 its own default profile back — it takes it at its next start");for(let i of e.removals)yv(i,{recursive:!0,force:!0});if(e.removals.length>0)n.push(`Deleted ${e.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of e.touches)Ev(i,r,r);return n}function Fv(){let e=vv();return{home:e,configHome:ue(),zdotdir:process.env.ZDOTDIR??e,cacheDir:Fr(),stateDir:ii(process.env.XDG_STATE_HOME??ii(e,".local","state"),"ttheme")}}async function qp(e=!1){let t=Fv(),n=Nv(t);if(n.edits.length===0&&n.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=ii(t.configHome,"ttheme");Ls("ttheme uninstall"),Cn([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${la(wo(t.configHome))?`, and your markets under ${wo(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
531
+ `),"Uninstall");let i=await Ht({message:"Remove ttheme?"});if(Be(i)||!i)throw pr("Nothing changed"),new Un}for(let r of Rv(n))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var Pv=new Set(["add","remove","market","default","on","off"]),Tv={default:([e])=>wm(e),on:()=>bm(),off:()=>$m(),browse:()=>Sm(),list:([e],{json:t})=>Em(e,t),add:(e,{market:t})=>mm(e,t),remove:(e)=>pm(e),update:()=>vm(),market:([e,t])=>Bg(e,t),new:([e],{from:t,in:n})=>lm(e,t,n),edit:([e])=>hm(e),check:([e],{fix:t})=>dm(e,t),share:([e])=>gm(e),init:(e,{yes:t})=>Kp({yes:t}),uninstall:(e,{yes:t})=>qp(t),build:(e,{only:t})=>Vo({only:t}),find:([e])=>Op(e),image:([e,t])=>Pp(e,t),redraw:()=>Tp()},Av=Yi.map((e)=>({...e,run:Tv[e.name]}));class fr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function Qp(e){let t=Av.find((n)=>n.name===e);if(!t)throw new fr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function Hv(e,t){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:s,multiple:o}]of Object.entries(e.flags??{}))n[r]={type:i,multiple:o===!0,...s?{short:s}:{}};try{return Ov({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new fr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function Lv(e){let[t,...n]=e;if(t===void 0)return{kind:"help",code:1};if(t==="-h"||t==="--help")return{kind:"help",code:0};if(t==="-V"||t==="--version")return{kind:"version"};if(t==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:Qp(n[0]),code:0}}let r=Qp(t),i=Hv(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:h}]of Object.entries(r.flags??{}))for(let f of[i.values[l]??[]].flat())if(h&&!h.includes(String(f)))throw new fr(`--${l} takes ${h.join(", ")} — not ${f}`,r);let s=i.positionals,o=r.args.filter((l)=>l.startsWith("<")).length,a=r.args.some((l)=>l.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(s.length<o)throw new fr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new fr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function Yp(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function Dc(e,t=!1){if(!e)return Zi(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Qi(e)}`,"",e.about,...e.actions?["","Actions:",...Yp(e.actions)]:[],...n.length>0?["","Options:",...Yp(n)]:[]].join(`
532
+ `)}async function Zp(e){let t;try{let n=Lv(e);if(n.kind==="version")return console.log(Ve.version),0;if(n.kind==="help"){if(n.code===0)console.log(Dc(n.verb,n.all));else console.error(Dc(n.verb,n.all));return n.code}if(t=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");if(Pv.has(n.verb.name))await Gg();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof fr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
533
533
 
534
- ${Vc(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof _n)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
535
- ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(Av)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=Tv(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await Jp(process.argv.slice(2));
534
+ ${Dc(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof Un)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
535
+ ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(Uv)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=Gv(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await Zp(process.argv.slice(2));
536
536
 
537
- //# debugId=0C89DBC96CF7E3EE64756E2164756E21
537
+ //# debugId=AC42ED9A3B59380264756E2164756E21
538
538
  //# sourceMappingURL=ttheme.js.map