@kecan0406/ttheme 1.2.7 → 1.2.9

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,86 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as K$}from"node:module";var L$=Object.create;var{getPrototypeOf:C$,defineProperty:Td,getOwnPropertyNames:_$}=Object;var G$=Object.prototype.hasOwnProperty;function W$(e){return this[e]}var U$,j$,Ho=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?U$??=new WeakMap:j$??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?L$(C$(e)):{};let o=t||!e||!e.__esModule?Td(n,"default",{value:e,enumerable:!0}):n;for(let a of _$(e))if(!G$.call(o,a))Td(o,a,{get:W$.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var He=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ot=K$(import.meta.url);var Vu=He((fR,Vd)=>{var qu={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"},ik={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},sk={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?qu.up():"");if(e)t+=qu.left;return t}};Vd.exports={cursor:qu,scroll:ik,erase:sk,beep:"\x07"}});var Ih=He((JR,Jo)=>{var Sh=Sh||function(e){return Buffer.from(e).toString("base64")};function Dk(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,f,d=Array(65535),h=Array(65535),g=Array(64),b=Array(64),p=[],m=0,k=7,v=Array(64),M=Array(64),w=Array(64),I=Array(256),$=Array(2048),N,R=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],F=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],x=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],W=[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],A=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],T=[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],Ee=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function be(y){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 V=0;V<64;V++){var j=r((G[V]*y+50)/100);if(j<1)j=1;else if(j>255)j=255;i[R[V]]=j}var te=[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 re=0;re<64;re++){var me=r((te[re]*y+50)/100);if(me<1)me=1;else if(me>255)me=255;s[R[re]]=me}var pe=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],je=0;for(var Te=0;Te<8;Te++)for(var P=0;P<8;P++)o[je]=1/(i[R[je]]*pe[Te]*pe[P]*8),a[je]=1/(s[R[je]]*pe[Te]*pe[P]*8),je++}function Y(y,G){var V=0,j=0,te=[];for(var re=1;re<=16;re++){for(var me=1;me<=y[re];me++)te[G[j]]=[],te[G[j]][0]=V,te[G[j]][1]=re,j++,V++;V*=2}return te}function Ae(){u=Y(F,x),c=Y(A,T),l=Y(C,W),f=Y(q,Ee)}function he(){var y=1,G=2;for(var V=1;V<=15;V++){for(var j=y;j<G;j++)h[32767+j]=V,d[32767+j]=[],d[32767+j][1]=V,d[32767+j][0]=j;for(var te=-(G-1);te<=-y;te++)h[32767+te]=V,d[32767+te]=[],d[32767+te][1]=V,d[32767+te][0]=G-1+te;y<<=1,G<<=1}}function ce(){for(var y=0;y<256;y++)$[y]=19595*y,$[y+256>>0]=38470*y,$[y+512>>0]=7471*y+32768,$[y+768>>0]=-11059*y,$[y+1024>>0]=-21709*y,$[y+1280>>0]=32768*y+8421375,$[y+1536>>0]=-27439*y,$[y+1792>>0]=-5329*y}function se(y){var G=y[0],V=y[1]-1;while(V>=0){if(G&1<<V)m|=1<<k;if(V--,k--,k<0){if(m==255)E(255),E(0);else E(m);k=7,m=0}}}function E(y){p.push(y)}function U(y){E(y>>8&255),E(y&255)}function Ne(y,G){var V,j,te,re,me,pe,je,Te,P=0,L,Z=8,Ge=64;for(L=0;L<Z;++L){V=y[P],j=y[P+1],te=y[P+2],re=y[P+3],me=y[P+4],pe=y[P+5],je=y[P+6],Te=y[P+7];var ie=V+Te,le=V-Te,Re=j+je,z=j-je,we=te+pe,nt=te-pe,Le=re+me,Ot=re-me,Zt=ie+Le,Er=ie-Le,Xr=Re+we,Dr=Re-we;y[P]=Zt+Xr,y[P+4]=Zt-Xr;var Yi=(Dr+Er)*0.707106781;y[P+2]=Er+Yi,y[P+6]=Er-Yi,Zt=Ot+nt,Xr=nt+z,Dr=z+le;var Qi=(Zt-Dr)*0.382683433,Ro=0.5411961*Zt+Qi,Zi=1.306562965*Dr+Qi,Xi=Xr*0.707106781,Di=le+Xi,es=le-Xi;y[P+5]=es+Ro,y[P+3]=es-Ro,y[P+1]=Di+Zi,y[P+7]=Di-Zi,P+=8}P=0;for(L=0;L<Z;++L){V=y[P],j=y[P+8],te=y[P+16],re=y[P+24],me=y[P+32],pe=y[P+40],je=y[P+48],Te=y[P+56];var $d=V+Te,Uu=V-Te,kd=j+je,yd=j-je,Ed=te+pe,vd=te-pe,Md=re+me,A$=re-me,ts=$d+Md,ju=$d-Md,Oo=kd+Ed,Fo=kd-Ed;y[P]=ts+Oo,y[P+32]=ts-Oo;var Sd=(Fo+ju)*0.707106781;y[P+16]=ju+Sd,y[P+48]=ju-Sd,ts=A$+vd,Oo=vd+yd,Fo=yd+Uu;var Id=(ts-Fo)*0.382683433,Nd=0.5411961*ts+Id,Pd=1.306562965*Fo+Id,Rd=Oo*0.707106781,Od=Uu+Rd,Fd=Uu-Rd;y[P+40]=Fd+Nd,y[P+24]=Fd-Nd,y[P+8]=Od+Pd,y[P+56]=Od-Pd,P++}var To;for(L=0;L<Ge;++L)To=y[L]*G[L],g[L]=To>0?To+0.5|0:To-0.5|0;return g}function Pe(){U(65504),U(16),E(74),E(70),E(73),E(70),E(0),E(1),E(1),E(0),U(1),U(1),E(0),E(0)}function fe(y){if(!y)return;if(U(65505),y[0]===69&&y[1]===120&&y[2]===105&&y[3]===102)U(y.length+2);else U(y.length+5+2),E(69),E(120),E(105),E(102),E(0);for(var G=0;G<y.length;G++)E(y[G])}function de(y,G){U(65472),U(17),E(8),U(G),U(y),E(3),E(1),E(17),E(0),E(2),E(17),E(1),E(3),E(17),E(1)}function oe(){U(65499),U(132),E(0);for(var y=0;y<64;y++)E(i[y]);E(1);for(var G=0;G<64;G++)E(s[G])}function H(){U(65476),U(418),E(0);for(var y=0;y<16;y++)E(F[y+1]);for(var G=0;G<=11;G++)E(x[G]);E(16);for(var V=0;V<16;V++)E(C[V+1]);for(var j=0;j<=161;j++)E(W[j]);E(1);for(var te=0;te<16;te++)E(A[te+1]);for(var re=0;re<=11;re++)E(T[re]);E(17);for(var me=0;me<16;me++)E(q[me+1]);for(var pe=0;pe<=161;pe++)E(Ee[pe])}function O(y){if(typeof y>"u"||y.constructor!==Array)return;y.forEach((G)=>{if(typeof G!=="string")return;U(65534);var V=G.length;U(V+2);var j;for(j=0;j<V;j++)E(G.charCodeAt(j))})}function Fe(){U(65498),U(12),E(3),E(1),E(0),E(2),E(17),E(3),E(17),E(0),E(63),E(0)}function Q(y,G,V,j,te){var re=te[0],me=te[240],pe,je=16,Te=63,P=64,L=Ne(y,G);for(var Z=0;Z<P;++Z)b[R[Z]]=L[Z];var Ge=b[0]-V;if(V=b[0],Ge==0)se(j[0]);else pe=32767+Ge,se(j[h[pe]]),se(d[pe]);var ie=63;for(;ie>0&&b[ie]==0;ie--);if(ie==0)return se(re),V;var le=1,Re;while(le<=ie){var z=le;for(;b[le]==0&&le<=ie;++le);var we=le-z;if(we>=je){Re=we>>4;for(var nt=1;nt<=Re;++nt)se(me);we=we&15}pe=32767+b[le],se(te[(we<<4)+h[pe]]),se(d[pe]),le++}if(ie!=Te)se(re);return V}function ae(){var y=String.fromCharCode;for(var G=0;G<256;G++)I[G]=y(G)}this.encode=function(y,G){var V=new Date().getTime();if(G)Rt(G);p=[],m=0,k=7,U(65496),Pe(),O(y.comments),fe(y.exifBuffer),oe(),de(y.width,y.height),H(),Fe();var j=0,te=0,re=0;m=0,k=7,this.encode.displayName="_encode_";var{data:me,width:pe,height:je}=y,Te=pe*4,P=pe*3,L,Z=0,Ge,ie,le,Re,z,we,nt,Le;while(Z<je){L=0;while(L<Te){Re=Te*Z+L,z=Re,we=-1,nt=0;for(Le=0;Le<64;Le++){if(nt=Le>>3,we=(Le&7)*4,z=Re+nt*Te+we,Z+nt>=je)z-=Te*(Z+1+nt-je);if(L+we>=Te)z-=L+we-Te+4;Ge=me[z++],ie=me[z++],le=me[z++],v[Le]=($[Ge]+$[ie+256>>0]+$[le+512>>0]>>16)-128,M[Le]=($[Ge+768>>0]+$[ie+1024>>0]+$[le+1280>>0]>>16)-128,w[Le]=($[Ge+1280>>0]+$[ie+1536>>0]+$[le+1792>>0]>>16)-128}j=Q(v,o,j,u,l),te=Q(M,a,te,c,f),re=Q(w,a,re,c,f),L+=32}Z+=8}if(k>=0){var Ot=[];Ot[1]=k+1,Ot[0]=(1<<k+1)-1,se(Ot)}if(U(65497),typeof Jo>"u")return new Uint8Array(p);return Buffer.from(p);var Zt,Er};function Rt(y){if(y<=0)y=1;if(y>100)y=100;if(N==y)return;var G=0;if(y<50)G=Math.floor(5000/y);else G=Math.floor(200-y*2);be(G),N=y}function Ut(){var y=new Date().getTime();if(!e)e=50;ae(),Ae(),he(),ce(),Rt(e);var G=new Date().getTime()-y}Ut()}if(typeof Jo<"u")Jo.exports=Mh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Mh;function Mh(e,t){if(typeof t>"u")t=50;var n=new Dk(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var Ph=He((qR,hc)=>{var dc=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 f(k,v){var M=0,w=[],I,$,N=16;while(N>0&&!k[N-1])N--;w.push({children:[],index:0});var R=w[0],F;for(I=0;I<N;I++){for($=0;$<k[I];$++){R=w.pop(),R.children[R.index]=v[M];while(R.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");R=w.pop()}R.index++,w.push(R);while(w.length<=I)w.push(F={children:[],index:0}),R.children[R.index]=F.children,R=F;M++}if(I+1<N)w.push(F={children:[],index:0}),R.children[R.index]=F.children,R=F}return w[0].children}function d(k,v,M,w,I,$,N,R,F,x){var{precision:C,samplesPerLine:W,scanLines:A,mcusPerLine:T,progressive:q,maxH:Ee,maxV:be}=M,Y=v,Ae=0,he=0;function ce(){if(he>0)return he--,Ae>>he&1;if(Ae=k[v++],Ae==255){var P=k[v++];if(P)throw Error("unexpected marker: "+(Ae<<8|P).toString(16))}return he=7,Ae>>>7}function se(P){var L=P,Z;while((Z=ce())!==null){if(L=L[Z],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function E(P){var L=0;while(P>0){var Z=ce();if(Z===null)return;L=L<<1|Z,P--}return L}function U(P){var L=E(P);if(L>=1<<P-1)return L;return L+(-1<<P)+1}function Ne(P,L){var Z=se(P.huffmanTableDC),Ge=Z===0?0:U(Z);L[0]=P.pred+=Ge;var ie=1;while(ie<64){var le=se(P.huffmanTableAC),Re=le&15,z=le>>4;if(Re===0){if(z<15)break;ie+=16;continue}ie+=z;var we=t[ie];L[we]=U(Re),ie++}}function Pe(P,L){var Z=se(P.huffmanTableDC),Ge=Z===0?0:U(Z)<<F;L[0]=P.pred+=Ge}function fe(P,L){L[0]|=ce()<<F}var de=0;function oe(P,L){if(de>0){de--;return}var Z=$,Ge=N;while(Z<=Ge){var ie=se(P.huffmanTableAC),le=ie&15,Re=ie>>4;if(le===0){if(Re<15){de=E(Re)+(1<<Re)-1;break}Z+=16;continue}Z+=Re;var z=t[Z];L[z]=U(le)*(1<<F),Z++}}var H=0,O;function Fe(P,L){var Z=$,Ge=N,ie=0;while(Z<=Ge){var le=t[Z],Re=L[le]<0?-1:1;switch(H){case 0:var z=se(P.huffmanTableAC),we=z&15,ie=z>>4;if(we===0)if(ie<15)de=E(ie)+(1<<ie),H=4;else ie=16,H=1;else{if(we!==1)throw Error("invalid ACn encoding");O=U(we),H=ie?2:3}continue;case 1:case 2:if(L[le])L[le]+=(ce()<<F)*Re;else if(ie--,ie===0)H=H==2?3:0;break;case 3:if(L[le])L[le]+=(ce()<<F)*Re;else L[le]=O<<F,H=0;break;case 4:if(L[le])L[le]+=(ce()<<F)*Re;break}Z++}if(H===4){if(de--,de===0)H=0}}function Q(P,L,Z,Ge,ie){var le=Z/T|0,Re=Z%T,z=le*P.v+Ge,we=Re*P.h+ie;if(P.blocks[z]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[z][we])}function ae(P,L,Z){var Ge=Z/P.blocksPerLine|0,ie=Z%P.blocksPerLine;if(P.blocks[Ge]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[Ge][ie])}var Rt=w.length,Ut,y,G,V,j,te;if(q)if($===0)te=R===0?Pe:fe;else te=R===0?oe:Fe;else te=Ne;var re=0,me,pe;if(Rt==1)pe=w[0].blocksPerLine*w[0].blocksPerColumn;else pe=T*M.mcusPerColumn;if(!I)I=pe;var je,Te;while(re<pe){for(y=0;y<Rt;y++)w[y].pred=0;if(de=0,Rt==1){Ut=w[0];for(j=0;j<I;j++)ae(Ut,te,re),re++}else for(j=0;j<I;j++){for(y=0;y<Rt;y++){Ut=w[y],je=Ut.h,Te=Ut.v;for(G=0;G<Te;G++)for(V=0;V<je;V++)Q(Ut,te,re,G,V)}if(re++,re===pe)break}if(re===pe)do{if(k[v]===255){if(k[v+1]!==0)break}v+=1}while(v<k.length-2);if(he=0,me=k[v]<<8|k[v+1],me<65280)throw Error("marker was not found");if(me>=65488&&me<=65495)v+=2;else break}return v-Y}function h(k,v){var M=[],w=v.blocksPerLine,I=v.blocksPerColumn,$=w<<3,N=new Int32Array(64),R=new Uint8Array(64);function F(Y,Ae,he){var ce=v.quantizationTable,se,E,U,Ne,Pe,fe,de,oe,H,O=he,Fe;for(Fe=0;Fe<64;Fe++)O[Fe]=Y[Fe]*ce[Fe];for(Fe=0;Fe<8;++Fe){var Q=8*Fe;if(O[1+Q]==0&&O[2+Q]==0&&O[3+Q]==0&&O[4+Q]==0&&O[5+Q]==0&&O[6+Q]==0&&O[7+Q]==0){H=u*O[0+Q]+512>>10,O[0+Q]=H,O[1+Q]=H,O[2+Q]=H,O[3+Q]=H,O[4+Q]=H,O[5+Q]=H,O[6+Q]=H,O[7+Q]=H;continue}se=u*O[0+Q]+128>>8,E=u*O[4+Q]+128>>8,U=O[2+Q],Ne=O[6+Q],Pe=c*(O[1+Q]-O[7+Q])+128>>8,oe=c*(O[1+Q]+O[7+Q])+128>>8,fe=O[3+Q]<<4,de=O[5+Q]<<4,H=se-E+1>>1,se=se+E+1>>1,E=H,H=U*a+Ne*o+128>>8,U=U*o-Ne*a+128>>8,Ne=H,H=Pe-de+1>>1,Pe=Pe+de+1>>1,de=H,H=oe+fe+1>>1,fe=oe-fe+1>>1,oe=H,H=se-Ne+1>>1,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t}}m($*I*8);var x,C;for(var W=0;W<I;W++){var A=W<<3;for(x=0;x<8;x++)M.push(new Uint8Array($));for(var T=0;T<w;T++){F(v.blocks[W][T],R,N);var q=0,Ee=T<<3;for(C=0;C<8;C++){var be=M[A+C];for(x=0;x<8;x++)be[Ee+x]=R[q++]}}}return M}function g(k){return k<0?0:k>255?255:k}l.prototype={load:function(v){var M=new XMLHttpRequest;M.open("GET",v,!0),M.responseType="arraybuffer",M.onload=function(){var w=new Uint8Array(M.response||M.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),M.send(null)},parse:function(v){var M=this.opts.maxResolutionInMP*1000*1000,w=0,I=v.length;function $(){var z=v[w]<<8|v[w+1];return w+=2,z}function N(){var z=$(),we=v.subarray(w,w+z-2);return w+=we.length,we}function R(z){var we=1,nt=1,Le,Ot;for(Ot in z.components)if(z.components.hasOwnProperty(Ot)){if(Le=z.components[Ot],we<Le.h)we=Le.h;if(nt<Le.v)nt=Le.v}var Zt=Math.ceil(z.samplesPerLine/8/we),Er=Math.ceil(z.scanLines/8/nt);for(Ot in z.components)if(z.components.hasOwnProperty(Ot)){Le=z.components[Ot];var Xr=Math.ceil(Math.ceil(z.samplesPerLine/8)*Le.h/we),Dr=Math.ceil(Math.ceil(z.scanLines/8)*Le.v/nt),Yi=Zt*Le.h,Qi=Er*Le.v,Ro=Qi*Yi,Zi=[];m(Ro*256);for(var Xi=0;Xi<Qi;Xi++){var Di=[];for(var es=0;es<Yi;es++)Di.push(new Int32Array(64));Zi.push(Di)}Le.blocksPerLine=Xr,Le.blocksPerColumn=Dr,Le.blocks=Zi}z.maxH=we,z.maxV=nt,z.mcusPerLine=Zt,z.mcusPerColumn=Er}var F=null,x=null,C=null,W,A,T=[],q=[],Ee=[],be=[],Y=$(),Ae=-1;if(this.comments=[],Y!=65496)throw Error("SOI not found");Y=$();while(Y!=65497){var he,ce,se;switch(Y){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 E=N();if(Y===65534){var U=String.fromCharCode.apply(null,E);this.comments.push(U)}if(Y===65504){if(E[0]===74&&E[1]===70&&E[2]===73&&E[3]===70&&E[4]===0)F={version:{major:E[5],minor:E[6]},densityUnits:E[7],xDensity:E[8]<<8|E[9],yDensity:E[10]<<8|E[11],thumbWidth:E[12],thumbHeight:E[13],thumbData:E.subarray(14,14+3*E[12]*E[13])}}if(Y===65505){if(E[0]===69&&E[1]===120&&E[2]===105&&E[3]===102&&E[4]===0)this.exifBuffer=E.subarray(5,E.length)}if(Y===65518){if(E[0]===65&&E[1]===100&&E[2]===111&&E[3]===98&&E[4]===101&&E[5]===0)x={version:E[6],flags0:E[7]<<8|E[8],flags1:E[9]<<8|E[10],transformCode:E[11]}}break;case 65499:var Ne=$(),Pe=Ne+w-2;while(w<Pe){var fe=v[w++];m(256);var de=new Int32Array(64);if(fe>>4===0)for(ce=0;ce<64;ce++){var oe=t[ce];de[oe]=v[w++]}else if(fe>>4===1)for(ce=0;ce<64;ce++){var oe=t[ce];de[oe]=$()}else throw Error("DQT: invalid table spec");T[fe&15]=de}break;case 65472:case 65473:case 65474:$(),W={},W.extended=Y===65473,W.progressive=Y===65474,W.precision=v[w++],W.scanLines=$(),W.samplesPerLine=$(),W.components={},W.componentsOrder=[];var H=W.scanLines*W.samplesPerLine;if(H>M){var O=Math.ceil((H-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${O}MP`)}var Fe=v[w++],Q,ae=0,Rt=0;for(he=0;he<Fe;he++){Q=v[w];var Ut=v[w+1]>>4,y=v[w+1]&15,G=v[w+2];if(Ut<=0||y<=0)throw Error("Invalid sampling factor, expected values above 0");W.componentsOrder.push(Q),W.components[Q]={h:Ut,v:y,quantizationIdx:G},w+=3}R(W),q.push(W);break;case 65476:var V=$();for(he=2;he<V;){var j=v[w++],te=new Uint8Array(16),re=0;for(ce=0;ce<16;ce++,w++)re+=te[ce]=v[w];m(16+re);var me=new Uint8Array(re);for(ce=0;ce<re;ce++,w++)me[ce]=v[w];he+=17+re,(j>>4===0?be:Ee)[j&15]=f(te,me)}break;case 65501:$(),A=$();break;case 65500:$(),$();break;case 65498:var pe=$(),je=v[w++],Te=[],P;for(he=0;he<je;he++){P=W.components[v[w++]];var L=v[w++];P.huffmanTableDC=be[L>>4],P.huffmanTableAC=Ee[L&15],Te.push(P)}var Z=v[w++],Ge=v[w++],ie=v[w++],le=d(v,w,W,Te,A,Z,Ge,ie>>4,ie&15,this.opts);w+=le;break;case 65535:if(v[w]!==255)w--;break;default:if(v[w-3]==255&&v[w-2]>=192&&v[w-2]<=254){w-=3;break}else if(Y===224||Y==225){if(Ae!==-1)throw Error(`first unknown JPEG marker at offset ${Ae.toString(16)}, second unknown JPEG marker ${Y.toString(16)} at offset ${(w-1).toString(16)}`);Ae=w-1;let z=$();if(v[w+z-2]===255){w+=z-2;break}}throw Error("unknown JPEG marker "+Y.toString(16))}Y=$()}if(q.length!=1)throw Error("only single frame JPEGs supported");for(var he=0;he<q.length;he++){var Re=q[he].components;for(var ce in Re)Re[ce].quantizationTable=T[Re[ce].quantizationIdx],delete Re[ce].quantizationIdx}this.width=W.samplesPerLine,this.height=W.scanLines,this.jfif=F,this.adobe=x,this.components=[];for(var he=0;he<W.componentsOrder.length;he++){var P=W.components[W.componentsOrder[he]];this.components.push({lines:h(W,P),scaleX:P.h/W.maxH,scaleY:P.v/W.maxV})}},getData:function(v,M){var w=this.width/v,I=this.height/M,$,N,R,F,x,C,W,A,T,q,Ee=0,be,Y,Ae,he,ce,se,E,U,Ne,Pe,fe,de=v*M*this.components.length;m(de);var oe=new Uint8Array(de);switch(this.components.length){case 1:$=this.components[0];for(q=0;q<M;q++){x=$.lines[0|q*$.scaleY*I];for(T=0;T<v;T++)be=x[0|T*$.scaleX*w],oe[Ee++]=be}break;case 2:$=this.components[0],N=this.components[1];for(q=0;q<M;q++){x=$.lines[0|q*$.scaleY*I],C=N.lines[0|q*N.scaleY*I];for(T=0;T<v;T++)be=x[0|T*$.scaleX*w],oe[Ee++]=be,be=C[0|T*N.scaleX*w],oe[Ee++]=be}break;case 3:if(fe=!0,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;$=this.components[0],N=this.components[1],R=this.components[2];for(q=0;q<M;q++){x=$.lines[0|q*$.scaleY*I],C=N.lines[0|q*N.scaleY*I],W=R.lines[0|q*R.scaleY*I];for(T=0;T<v;T++){if(!fe)U=x[0|T*$.scaleX*w],Ne=C[0|T*N.scaleX*w],Pe=W[0|T*R.scaleX*w];else be=x[0|T*$.scaleX*w],Y=C[0|T*N.scaleX*w],Ae=W[0|T*R.scaleX*w],U=g(be+1.402*(Ae-128)),Ne=g(be-0.3441363*(Y-128)-0.71413636*(Ae-128)),Pe=g(be+1.772*(Y-128));oe[Ee++]=U,oe[Ee++]=Ne,oe[Ee++]=Pe}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(fe=!1,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;$=this.components[0],N=this.components[1],R=this.components[2],F=this.components[3];for(q=0;q<M;q++){x=$.lines[0|q*$.scaleY*I],C=N.lines[0|q*N.scaleY*I],W=R.lines[0|q*R.scaleY*I],A=F.lines[0|q*F.scaleY*I];for(T=0;T<v;T++){if(!fe)ce=x[0|T*$.scaleX*w],se=C[0|T*N.scaleX*w],E=W[0|T*R.scaleX*w],he=A[0|T*F.scaleX*w];else be=x[0|T*$.scaleX*w],Y=C[0|T*N.scaleX*w],Ae=W[0|T*R.scaleX*w],he=A[0|T*F.scaleX*w],ce=255-g(be+1.402*(Ae-128)),se=255-g(be-0.3441363*(Y-128)-0.71413636*(Ae-128)),E=255-g(be+1.772*(Y-128));oe[Ee++]=255-ce,oe[Ee++]=255-se,oe[Ee++]=255-E,oe[Ee++]=255-he}}break;default:throw Error("Unsupported color mode")}return oe},copyToImageData:function(v,M){var{width:w,height:I,data:$}=v,N=this.getData(w,I),R=0,F=0,x,C,W,A,T,q,Ee,be,Y;switch(this.components.length){case 1:for(C=0;C<I;C++)for(x=0;x<w;x++)if(W=N[R++],$[F++]=W,$[F++]=W,$[F++]=W,M)$[F++]=255;break;case 3:for(C=0;C<I;C++)for(x=0;x<w;x++)if(Ee=N[R++],be=N[R++],Y=N[R++],$[F++]=Ee,$[F++]=be,$[F++]=Y,M)$[F++]=255;break;case 4:for(C=0;C<I;C++)for(x=0;x<w;x++)if(T=N[R++],q=N[R++],W=N[R++],A=N[R++],Ee=255-g(T*(1-A/255)+A),be=255-g(q*(1-A/255)+A),Y=255-g(W*(1-A/255)+A),$[F++]=Ee,$[F++]=be,$[F++]=Y,M)$[F++]=255;break;default:throw Error("Unsupported color mode")}}};var b=0,p=0;function m(k=0){var v=b+k;if(v>p){var M=Math.ceil((v-p)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}b=v}return l.resetMaxMemoryUsage=function(k){b=0,p=k},l.getBytesAllocated=function(){return b},l.requestMemoryAllocation=m,l}();if(typeof hc<"u")hc.exports=Nh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Nh;function Nh(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 dc;s.opts=r,dc.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{dc.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 Oh=He((VR,Rh)=>{var ey=Ih(),ty=Ph();Rh.exports={encode:ey,decode:ty}});var gc=He((zR,Th)=>{var ny=ot("util"),Fh=ot("stream"),Kt=Th.exports=function(){Fh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ny.inherits(Kt,Fh);Kt.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))};Kt.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};Kt.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()};Kt.prototype.destroySoon=Kt.prototype.end;Kt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Kt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Kt.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)};Kt.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)};Kt.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 mc=He((ry)=>{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]}];ry.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 f=0;f<u.x.length;f++)if(u.x[f]<r)c++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};ry.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 pc=He((QR,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 bc=He((ZR,Ah)=>{var oy=mc(),ay=pc();function xh(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var ai=Ah.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=oy.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:xh(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:xh(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};ai.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ai.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}};ai.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}};ai.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}};ai.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,f=ay(c,u,l);t[o]=a+f}};ai.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 _h=He((XR,Ch)=>{var uy=ot("util"),Lh=gc(),cy=bc(),ly=Ch.exports=function(e){Lh.call(this);let t=[],n=this;this._filter=new cy(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};uy.inherits(ly,Lh)});var ui=He((DR,Gh)=>{Gh.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 kc=He((eO,Wh)=>{var wc=[];(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;wc[e]=t}})();var $c=Wh.exports=function(){this._crc=-1};$c.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=wc[(this._crc^e[t])&255]^this._crc>>>8;return!0};$c.prototype.crc32=function(){return this._crc^-1};$c.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=wc[(t^e[n])&255]^t>>>8;return t^-1}});var yc=He((tO,Uh)=>{var Ze=ui(),fy=kc(),tt=Uh.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[Ze.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ze.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ze.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ze.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ze.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ze.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(){}};tt.prototype.start=function(){this.read(Ze.PNG_SIGNATURE.length,this._parseSignature.bind(this))};tt.prototype._parseSignature=function(e){let t=Ze.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))};tt.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!==Ze.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new fy,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))};tt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};tt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};tt.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))};tt.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};tt.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 Ze.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=Ze.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&Ze.COLORTYPE_PALETTE),color:Boolean(i&Ze.COLORTYPE_COLOR),alpha:Boolean(i&Ze.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};tt.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};tt.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()};tt.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};tt.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ze.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===Ze.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ze.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};tt.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};tt.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ze.GAMMA_DIVISION),this._handleChunkEnd()};tt.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};tt.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Ze.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()};tt.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};tt.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ec=He((by)=>{var jh=mc(),dy=[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]}],hy=[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 gy(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,f,d,h;switch(t){default:throw Error("unrecognised depth");case 16:d=e[r],r++,n.push((s<<8)+d);break;case 4:d=s&15,h=s>>4,n.push(h,d);break;case 2:l=s&3,f=s>>2&3,d=s>>4&3,h=s>>6&3,n.push(h,d,f,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,f=s>>5&1,d=s>>6&1,h=s>>7&1,n.push(h,d,f,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 my(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 f=n(l,c,u);dy[r](t,i,f,s),s+=r}return s}function py(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 f=i.get(r),d=n(l,c,u);hy[r](t,f,d,s)}i.resetAfterLine()}}by.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=gy(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,f,d;if(o)f=jh.getImagePasses(n,r),d=jh.getInterlaceIterator(n,r);else{let h=0;d=function(){let g=h;return h+=4,g},f=[{width:n,height:r}]}for(let h=0;h<f.length;h++)if(i===8)l=my(f[h],u,d,s,e,l);else py(f[h],u,d,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var vc=He((rO,Kh)=>{function $y(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 ky(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 yy(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}}Kh.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)$y(e,c,i,s,u);else{if(a)ky(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);yy(e,c,i,s,r)}}return c}});var qh=He((iO,Jh)=>{var Ey=ot("util"),Mc=ot("zlib"),Bh=gc(),vy=_h(),My=yc(),Sy=Ec(),Iy=vc(),tn=Jh.exports=function(e){Bh.call(this),this._parser=new My(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()};Ey.inherits(tn,Bh);tn.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};tn.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Mc.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,Mc.Z_MIN_CHUNK);this._inflate=Mc.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)};tn.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new vy(this._bitmapInfo)};tn.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};tn.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};tn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};tn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};tn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};tn.prototype._complete=function(e){if(this.errord)return;let t;try{let n=Sy.dataToBitMap(e,this._bitmapInfo);t=Iy(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var zh=He((sO,Vh)=>{var xt=ui();Vh.exports=function(e,t,n,r){let i=[xt.COLORTYPE_COLOR_ALPHA,xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[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=xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,f=0,d=r.bgColor||{};if(d.red===void 0)d.red=o;if(d.green===void 0)d.green=o;if(d.blue===void 0)d.blue=o;function h(){let g,b,p,m=o;switch(r.inputColorType){case xt.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],b=s[l+1],p=s[l+2];break;case xt.COLORTYPE_COLOR:g=s[l],b=s[l+1],p=s[l+2];break;case xt.COLORTYPE_ALPHA:m=s[l+1],g=s[l],b=g,p=g;break;case xt.COLORTYPE_GRAYSCALE:g=s[l],b=g,p=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)m/=o,g=Math.min(Math.max(Math.round((1-m)*d.red+m*g),0),o),b=Math.min(Math.max(Math.round((1-m)*d.green+m*b),0),o),p=Math.min(Math.max(Math.round((1-m)*d.blue+m*p),0),o)}return{red:g,green:b,blue:p,alpha:m}}for(let g=0;g<n;g++)for(let b=0;b<t;b++){let p=h(s,l);switch(r.colorType){case xt.COLORTYPE_COLOR_ALPHA:case xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[f]=p.red,c[f+1]=p.green,c[f+2]=p.blue,i)c[f+3]=p.alpha}else if(c.writeUInt16BE(p.red,f),c.writeUInt16BE(p.green,f+2),c.writeUInt16BE(p.blue,f+4),i)c.writeUInt16BE(p.alpha,f+6);break;case xt.COLORTYPE_ALPHA:case xt.COLORTYPE_GRAYSCALE:{let m=(p.red+p.green+p.blue)/3;if(r.bitDepth===8){if(c[f]=m,i)c[f+1]=p.alpha}else if(c.writeUInt16BE(m,f),i)c.writeUInt16BE(p.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=u}return c}});var Zh=He((oO,Qh)=>{var Yh=pc();function Ny(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Py(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Ry(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 Oy(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 Fy(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 Ty(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 Hy(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 xy(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 Ay(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]-Yh(a,u,c);r[i+o]=l}}function Ly(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]-Yh(o,a,u);i+=Math.abs(c)}return i}var Cy={0:Ny,1:Ry,2:Fy,3:Hy,4:Ay},_y={0:Py,1:Oy,2:Ty,3:xy,4:Ly};Qh.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 f=0;f<n;f++){if(s.length>1){let d=1/0;for(let h=0;h<s.length;h++){let g=_y[s[h]](e,u,o,i);if(g<d)l=s[h],d=g}}c[a]=l,a++,Cy[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var Sc=He((aO,Xh)=>{var ut=ui(),Gy=kc(),Wy=zh(),Uy=Zh(),jy=ot("zlib"),Un=Xh.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||jy.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:ut.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:ut.COLORTYPE_COLOR_ALPHA,[ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.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")};Un.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Un.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Un.prototype.filterData=function(e,t,n){let r=Wy(e,t,n,this._options),i=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Uy(r,t,n,this._options,i)};Un.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(Gy.crc32(r.slice(4,r.length-4)),r.length-4),r};Un.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*ut.GAMMA_DIVISION),0),this._packChunk(ut.TYPE_gAMA,t)};Un.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(ut.TYPE_IHDR,n)};Un.prototype.packIDAT=function(e){return this._packChunk(ut.TYPE_IDAT,e)};Un.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var ng=He((uO,tg)=>{var Ky=ot("util"),Dh=ot("stream"),By=ui(),Jy=Sc(),eg=tg.exports=function(e){Dh.call(this);let t=e||{};this._packer=new Jy(t),this._deflate=this._packer.createDeflate(),this.readable=!0};Ky.inherits(eg,Dh);eg.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(By.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 ug=He((us,ag)=>{var rg=ot("assert").ok,ci=ot("zlib"),qy=ot("util"),ig=ot("buffer").kMaxLength;function Nr(e){if(!(this instanceof Nr))return new Nr(e);if(e&&e.chunkSize<ci.Z_MIN_CHUNK)e.chunkSize=ci.Z_MIN_CHUNK;if(ci.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 Vy(e){return new Nr(e)}function sg(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Nr.prototype._processChunk=function(e,t,n){if(typeof n==="function")return ci.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 f(g,b){if(r._hadError)return;let p=s-b;if(rg(p>=0,"have should not go down"),p>0){let m=r._buffer.slice(r._offset,r._offset+p);if(r._offset+=p,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(b===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(b===0)return a+=i-g,i=g,!0;return!1}rg(this._handle,"zlib binding closed");let d;do d=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,s),d=d||this._writeState;while(!this._hadError&&f(d[0],d[1]));if(this._hadError)throw l;if(c>=ig)throw sg(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ig.toString(16)+" bytes");let h=Buffer.concat(u,c);return sg(this),h};qy.inherits(Nr,ci.Inflate);function zy(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=ci.Z_FINISH;return e._processChunk(t,n)}function og(e,t){return zy(new Nr(t),e)}ag.exports=us=og;us.Inflate=Nr;us.createInflate=Vy;us.inflateSync=og});var Ic=He((cO,lg)=>{var cg=lg.exports=function(e){this._buffer=e,this._reads=[]};cg.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};cg.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 fg=He((Zy)=>{var Yy=Ic(),Qy=bc();Zy.process=function(e,t){let n=[],r=new Yy(e);return new Qy(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var mg=He((fO,gg)=>{var dg=!0,hg=ot("zlib"),Dy=ug();if(!hg.deflateSync)dg=!1;var e1=Ic(),t1=fg(),n1=yc(),r1=Ec(),i1=vc();gg.exports=function(e,t){if(!dg)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(M){n=M}let i;function s(M){i=M}function o(M){i.transColor=M}function a(M){i.palette=M}function u(){i.alpha=!0}let c;function l(M){c=M}let f=[];function d(M){f.push(M)}let h=new e1(e);if(new n1(t,{read:h.read.bind(h),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:d,simpleTransparency:u}).start(),h.process(),n)throw n;let b=Buffer.concat(f);f.length=0;let p;if(i.interlace)p=hg.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;p=Dy(b,{chunkSize:w,maxLength:w})}if(b=null,!p||!p.length)throw Error("bad png - invalid inflate data response");let m=t1.process(p,i);b=null;let k=r1.dataToBitMap(m,i);m=null;let v=i1(k,i,t.skipRescale);return i.data=v,i.gamma=c||0,i}});var $g=He((dO,wg)=>{var pg=!0,bg=ot("zlib");if(!bg.deflateSync)pg=!1;var s1=ui(),o1=Sc();wg.exports=function(e,t){if(!pg)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new o1(t||{}),i=[];if(i.push(Buffer.from(s1.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=bg.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 kg=He((c1)=>{var a1=mg(),u1=$g();c1.read=function(e,t){return a1(e,t||{})};c1.write=function(e,t){return u1(e,t)}});var Eg=He((p1)=>{var d1=ot("util"),yg=ot("stream"),h1=qh(),g1=ng(),m1=kg(),lt=p1.PNG=function(e){if(yg.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 h1(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 g1(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"))};d1.inherits(lt,yg);lt.sync=m1;lt.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};lt.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};lt.prototype.write=function(e){return this._parser.write(e),!0};lt.prototype.end=function(e){this._parser.end(e)};lt.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};lt.prototype._gamma=function(e){this.gamma=e};lt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};lt.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)};lt.prototype.bitblt=function(e,t,n,r,i,s,o){return lt.bitblt(this,e,t,n,r,i,s,o),this};lt.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}};lt.prototype.adjustGamma=function(){lt.adjustGamma(this)}});import{spawnSync as DP}from"node:child_process";import{isMainThread as eR}from"node:worker_threads";import{parseArgs as JP}from"node:util";var et={name:"@kecan0406/ttheme",version:"1.2.7",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, Warp and Konsole",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","konsole"],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","@xterm/headless":"6.0.0","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 DN,readFileSync as a$}from"node:fs";import{styleText as _o}from"node:util";import{stdout as Qd,stdin as ok}from"node:process";import ak from"node:readline";var Hd=(()=>{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}})(),xd=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Ad=(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 J$=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,q$=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ld=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,V$=/\t{1,1000}/y,Cd=/[\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,z$=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Y$=/\p{M}+/gu,Q$={limit:1/0,ellipsis:""},_d=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?_d(i,Q$,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,f=n.regularWidth??1,d=n.wideWidth??2,h=[[z$,f],[J$,0],[q$,a],[V$,u],[Cd,c],[Ld,d]],g=0,b=0,p=e.length,m=0,k=!1,v=p,M=Math.max(0,r-s),w=0,I=0,$=0,N=0;e:while(!0){if(I>w||b>=p&&b>g){let R=e.slice(w,I)||e.slice(g,b);m=0;for(let F of R.replaceAll(Y$,"")){let x=F.codePointAt(0)||0;if(xd(x))N=2;else if(Ad(x))N=d;else N=f;if($+N>M)v=Math.min(v,Math.max(w,g)+m);if($+N>r){k=!0;break e}m+=F.length,$+=N}w=I=0}if(b>=p)break e;for(let R=0,F=h.length;R<F;R++){let[x,C]=h[R];if(x.lastIndex=b,x.test(e)){if(m=x===Ld?Hd(e.slice(b,x.lastIndex)):x===Cd?1:x.lastIndex-b,N=m*C,$+N>M)v=Math.min(v,b+Math.floor((M-$)/C));if($+N>r){k=!0;break e}$+=N,w=g,I=b,b=g=x.lastIndex;continue e}}b+=1}return{width:k?M:$,index:k?v:p,truncated:k,ellipsed:k&&r>=s}},Gd=_d;var Z$={limit:1/0,ellipsis:"",ellipsisWidth:0},X$=(e,t={})=>{return Gd(e,Z$,t).width},$e=X$;var xo="\x1B",Bd="›",D$=39,Bu="\x07",Jd="[",ek="]",qd="m",Ju=`${ek}8;;`,Wd=new RegExp(`(?:\\${Jd}(?<code>\\d+)m|\\${Ju}(?<uri>.*)${Bu})`,"y"),Ud=(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},jd=(e)=>`${xo}${Jd}${e}${qd}`,Kd=(e)=>`${xo}${Ju}${e}${Bu}`,Ku=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:$e(o),u=r.next(),c=r.next(),l=0;while(!u.done){let f=u.value,d=$e(f);if(a+d<=n)e[e.length-1]+=f;else e.push(f),a=0;if(f===xo||f===Bd)i=!0,s=t.startsWith(Ju,l+1);if(i){if(s){if(f===Bu)i=!1,s=!1}else if(f===qd)i=!1}else if(a+=d,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=f.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},tk=(e)=>{let t=e.split(" "),n=t.length;while(n){if($e(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},nk=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let f=0;f<o.length;f++){let d=o[f];if(n.trim!==!1){let g=a.at(-1)??"",b=g.trimStart();if(g.length!==b.length)a[a.length-1]=b,u=$e(b)}if(f!==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 h=$e(d);if(n.hard&&h>t){let g=t-u,b=1+Math.floor((h-g-1)/t);if(Math.floor((h-1)/t)<b)a.push("");Ku(a,d,t),u=$e(a.at(-1)??"");continue}if(u+h>t&&u&&h){if(n.wordWrap===!1&&u<t){Ku(a,d,t),u=$e(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>t&&n.wordWrap===!1){Ku(a,d,t),u=$e(a.at(-1)??"");continue}a[a.length-1]+=d,u+=h}if(n.trim!==!1)a=a.map((f)=>tk(f));let c=a.join(`
3
- `),l=!1;for(let f=0;f<c.length;f++){let d=c[f];if(r+=d,!l){if(l=d>="\uD800"&&d<="\uDBFF",l)continue}else l=!1;if(d===xo||d===Bd){Wd.lastIndex=f+1;let g=Wd.exec(c)?.groups;if(g?.code!==void 0){let b=Number.parseFloat(g.code);i=b===D$?void 0:b}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[f+1]===`
4
- `){if(s)r+=Kd("");let h=i?Ud(i):void 0;if(i&&h)r+=jd(h)}else if(d===`
5
- `){if(i&&Ud(i))r+=jd(i);if(s)r+=Kd(s)}}return r},rk=/\r?\n/;function Hn(e,t,n){return String(e).normalize().split(rk).map((r)=>nk(r,t,n)).join(`
6
- `)}var pt=Ho(Vu(),1);function ei(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?ei(s,t<0?-1:1,n):s}function Ao(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 uk=["up","down","left","right","space","enter","cancel"],ck=["January","February","March","April","May","June","July","August","September","October","November","December"],at={actions:new Set(uk),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:[...ck],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 Zd(e,t){if(typeof e=="string")return at.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Zd(n,t))return!0;return!1}function lk(e,t){if(e===t)return;let n=e.split(`
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 pR=globalThis.process.platform.startsWith("win"),Yu=Symbol("clack:cancel");function ht(e){return e===Yu}function Lo(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Go=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Zu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ns(e,t,n,r=n,i=n,s){let o=Go(e??Qd);return Hn(t,o-n.length,{hard:!0,trim:!1}).split(`
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 Xd(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 Ft{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=ok,output:r=Qd,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(Yu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ak.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),Lo(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),Lo(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),Lo(this.input,!1),e(Yu)})})}_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&&at.aliases.has(t.name)&&this.emit("cursor",at.aliases.get(t.name)),at.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=Xd(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")}Zd([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
- `),Lo(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Hn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(pt.cursor.move(-999,e*-1))}render(){let e=Hn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(pt.cursor.hide);else{let t=lk(this._prevFrame,e),n=Zu(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(pt.cursor.move(0,s-i)),this.output.write(pt.erase.lines(1));let o=e.split(`
14
- `);this.output.write(o[s]),this._prevFrame=e,this.output.write(pt.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(pt.cursor.move(0,a))}this.output.write(pt.erase.down());let o=e.split(`
15
- `).slice(s);this.output.write(o.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(pt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function fk(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 dk(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function hk(e,t){if(t)return e?t:t[0]}var gk=class extends Ft{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return _o(["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}${_o("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??dk;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=ei(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=hk(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=fk(this.focusedValue,this.filteredOptions);this.#t=ei(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 Xu extends Ft{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(pt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var mk={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function zd(e){return[...e].map((t)=>mk[t])}function pk(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 zu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Co(e){return{year:zu(e.year),month:zu(e.month),day:zu(e.day)}}function Qu(e,t){return new Date(e||2001,t||1,0).getDate()}function Dd(e){let{year:t,month:n,day:r}=Co(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 Yd(e){let t=Dd(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function bk(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:Qu(t.year,t.month)}}class eh extends Ft{#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.#f(this.#e)}#f(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#f(this.#e)),this._setValue(Yd(this.#e)??void 0)}constructor(e){let t=e.format?{segments:zd(e.format),separator:e.separator??"/"}:pk(e.locale),n=e.separator??t.separator,r=e.format?zd(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)}#d(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=bk(n.type,Co(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.#d(1);case"down":return this.#d(-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 d=this.#o+e,h={...this.#e,[r.type]:d},g=this.#h(h,r);if(g){this.inlineError=g,this.#o=null,this.#i=!1;return}this.inlineError="",this.#e[r.type]=d,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 d=Number.parseInt(e,10);u=`0${e}`,c=d<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!u.includes("_")){let d={...this.#e,[r.type]:u},h=this.#h(d,r);if(h){this.inlineError=h;return}}this.inlineError="",this.#e[r.type]=u;let l=u.includes("_")?void 0:Dd(this.#e);if(l){let{year:d,month:h}=l,g=Qu(d,h);this.#e={year:String(Math.max(0,Math.min(9999,d))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#u();let f=u.indexOf("_");c?(this.#i=!0,this.#o=e):f>=0?this.#r.positionInSegment=f: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)}}#h(e,t){let{month:n,day:r}=Co(e);if(t.type==="month"&&(n<0||n>12))return at.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return at.date.messages.invalidDay(31,"any month")}#p(e){let{year:t,month:n,day:r}=Co(this.#e);if(t&&n&&r){let i=Qu(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Yd(this.#e)??e.defaultValue??void 0}}var wk=class extends Ft{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}})}},$k=new Set(["up","down","left","right"]);class th extends Ft{#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
- `?`${t}█
18
- ${r}`:`${t}${_o("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=Ao(this._cursor,0,-1,t);return;case"down":this._cursor=Ao(this._cursor,0,1,t);return;case"left":this._cursor=Ao(this._cursor,-1,0,t);return;case"right":this._cursor=Ao(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
19
- `),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
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&&$k.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 Du extends Ft{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?ei(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=ei(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ei(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class ec extends Ft{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}${_o("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 S,stripVTControlCharacters as SR}from"node:util";import Tt from"node:process";var ch=Ho(Vu(),1);function kk(){if(Tt.platform!=="win32")return Tt.env.TERM!=="linux";return Boolean(Tt.env.CI)||Boolean(Tt.env.WT_SESSION)||Boolean(Tt.env.TERMINUS_SUBLIME)||Tt.env.ConEmuTask==="{cmd::Cmder}"||Tt.env.TERM_PROGRAM==="Terminus-Sublime"||Tt.env.TERM_PROGRAM==="vscode"||Tt.env.TERM==="xterm-256color"||Tt.env.TERM==="alacritty"||Tt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var yk=kk();var Oe=(e,t)=>yk?e:t,Ek=Oe("◆","*"),vk=Oe("■","x"),Mk=Oe("▲","x"),tc=Oe("◇","o"),Sk=Oe("┌","T"),ke=Oe("│","|"),An=Oe("└","—"),RR=Oe("┐","T"),OR=Oe("┘","—"),nh=Oe("●",">"),rh=Oe("○"," "),Ik=Oe("◻","[•]"),ih=Oe("◼","[+]"),sh=Oe("◻","[ ]"),FR=Oe("▪","•"),oh=Oe("─","-"),Nk=Oe("╮","+"),Pk=Oe("├","+"),Rk=Oe("╯","+"),Ok=Oe("╰","+"),TR=Oe("╭","+"),Fk=Oe("●","•"),Tk=Oe("◆","*"),Hk=Oe("▲","!"),xk=Oe("■","x"),nc=(e)=>{switch(e){case"initial":case"active":return S("cyan",Ek);case"cancel":return S("red",vk);case"error":return S("yellow",Mk);case"submit":return S("green",tc)}},Ak=(e)=>{switch(e){case"initial":case"active":return S("cyan",ke);case"cancel":return S("red",ke);case"error":return S("yellow",ke);case"submit":return S("green",ke)}};function Lk(e,t){let n=[`${t?`${S("cyan",ke)} `:""}${e.join(" • ")}`];return t&&n.push(S("cyan",An)),n}var ah=(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}},uh=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Go(r)-s,u=Zu(r),c=S("dim","..."),l=Math.max(u-o,0),f=Math.max(Math.min(i,l),5),d=0;e>=f-3&&(d=Math.max(Math.min(e-f+3,t.length-f),0));let h=f<t.length&&d>0,g=f<t.length&&d+f<t.length,b=Math.min(d+f,t.length),p=[],m=0;h&&m++,g&&m++;let k=d+(h?1:0),v=b-(g?1:0);for(let w=k;w<v;w++){let I=t[w],$=I?n(I,w===e):"",N=Hn($,a,{hard:!0,trim:!1}).split(`
22
- `);p.push(N),m+=N.length}if(m>l){let w=0,I=0,$=m,N=e-k,R=l,F=()=>ah(p,$,0,N,R),x=()=>ah(p,$,N+1,p.length,R,!0);h?({lineCount:$,removals:w}=F(),$>R&&(g||(R-=1),{lineCount:$,removals:I}=x())):(g||(R-=1),{lineCount:$,removals:I}=x(),$>R&&(R-=1,{lineCount:$,removals:w}=F())),w>0&&(h=!0,p.splice(0,w)),I>0&&(g=!0,p.splice(p.length-I,I))}let M=[];h&&M.push(c);for(let w of p)for(let I of w)M.push(I);return g&&M.push(c),M};var bn=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Xu({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??at.withGuide,i=`${nc(this.state)} `,s=r?`${S("gray",ke)} `:"",o=ns(e.output,e.message,s,i),a=`${r?`${S("gray",ke)}
23
- `:""}${o}
24
- `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${S("gray",ke)} `:"";return`${a}${c}${S("dim",u)}`}case"cancel":{let c=r?`${S("gray",ke)} `:"";return`${a}${c}${S(["strikethrough","dim"],u)}${r?`
25
- ${S("gray",ke)}`:""}`}default:{let c=r?`${S("cyan",ke)} `:"",l=r?S("cyan",An):"";return`${a}${c}${this.value?`${S("green",nh)} ${t}`:`${S("dim",rh)} ${S("dim",t)}`}${e.vertical?r?`
26
- ${S("cyan",ke)} `:`
27
- `:` ${S("dim","/")} `}${this.value?`${S("dim",rh)} ${S("dim",n)}`:`${S("green",nh)} ${n}`}
28
- ${l}
29
- `}}}}).prompt()};var Ck=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Space:")} select`,`${S("dim","Enter:")} confirm`],rs=(e,t)=>e.split(`
30
- `).map((n)=>t(n)).join(`
31
- `),lh=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${S("gray",sh)} ${rs(o,(a)=>S(["strikethrough","gray"],a))}${i.hint?` ${S("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${S("cyan",Ik)} ${o}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${S("green",ih)} ${rs(o,(a)=>S("dim",a))}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${rs(o,(a)=>S(["strikethrough","dim"],a))}`:s==="active-selected"?`${S("green",ih)} ${o}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${rs(o,(a)=>S("dim",a))}`:`${S("dim",sh)} ${rs(o,(a)=>S("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Du({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
- ${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??at.withGuide,s=ns(e.output,e.message,i?`${Ak(this.state)} `:"",`${nc(this.state)} `),o=`${i?`${S("gray",ke)}
2
+ import{createRequire as R1}from"node:module";var v1=Object.create;var{getPrototypeOf:E1,defineProperty:nh,getOwnPropertyNames:S1}=Object;var M1=Object.prototype.hasOwnProperty;function I1(t){return this[t]}var O1,N1,Yc=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var i=e?O1??=new WeakMap:N1??=new WeakMap,o=i.get(t);if(o)return o}n=t!=null?v1(E1(t)):{};let s=e||!t||!t.__esModule?nh(n,"default",{value:t,enumerable:!0}):n;for(let a of S1(t))if(!M1.call(s,a))nh(s,a,{get:I1.bind(t,a),enumerable:!0});if(r)i.set(t,s);return s};var mt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var xt=R1(import.meta.url);var Xc=mt((PH,bh)=>{var Qc={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},z1={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},K1={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Qc.up():"");if(t)e+=Qc.left;return e}};bh.exports={cursor:Qc,scroll:z1,erase:K1,beep:"\x07"}});var $u=mt((cF,Vh)=>{var jv=xt("util"),Dh=xt("stream"),$e=Vh.exports=function(){Dh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};jv.inherits($e,Dh);$e.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};$e.prototype.write=function(t,e){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(t))n=t;else n=Buffer.from(t,e||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};$e.prototype.end=function(t,e){if(t)this.write(t,e);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};$e.prototype.destroySoon=$e.prototype.end;$e.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};$e.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};$e.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];if(e.length>t.length)this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length));else this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e)};$e.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);while(e<t.length){let i=this._buffers[n++],o=Math.min(i.length,t.length-e);if(i.copy(r,e,0,o),e+=o,o!==i.length)this._buffers[--n]=i.slice(o)}if(n>0)this._buffers.splice(0,n);this._buffered-=t.length,t.func.call(this,r)};$e.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var ku=mt((Gv)=>{var In=[{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]}];Gv.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,o=(t-r)/8,s=(e-i)/8;for(let a=0;a<In.length;a++){let c=In[a],u=o*c.x.length,l=s*c.y.length;for(let f=0;f<c.x.length;f++)if(c.x[f]<r)u++;else break;for(let f=0;f<c.y.length;f++)if(c.y[f]<i)l++;else break;if(u>0&&l>0)n.push({width:u,height:l,index:a})}return n};Gv.getInterlaceIterator=function(t){return function(e,n,r){let i=e%In[r].x.length,o=(e-i)/In[r].x.length*8+In[r].x[i],s=n%In[r].y.length,a=(n-s)/In[r].y.length*8+In[r].y[s];return o*4+a*t*4}}});var yu=mt((lF,Zh)=>{Zh.exports=function(e,n,r){let i=e+n-r,o=Math.abs(i-e),s=Math.abs(i-n),a=Math.abs(i-r);if(o<=s&&o<=a)return e;if(s<=a)return n;return r}});var vu=mt((fF,Xh)=>{var _v=ku(),Bv=yu();function Qh(t,e,n){let r=t*e;if(n!==8)r=Math.ceil(r/(8/n));return r}var ii=Xh.exports=function(t,e){let{width:n,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let a=_v.getImagePasses(n,r);for(let c=0;c<a.length;c++)this._images.push({byteWidth:Qh(a[c].width,o,s),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:Qh(n,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};ii.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ii.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let o=0;o<n;o++){let s=t[1+o],a=o>i?e[o-r]:0;e[o]=s+a}};ii.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let o=t[1+i],s=r?r[i]:0;e[i]=o+s}};ii.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let a=t[1+s],c=o?o[s]:0,u=s>i?e[s-r]:0,l=Math.floor((u+c)/2);e[s]=a+l}};ii.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let a=t[1+s],c=o?o[s]:0,u=s>i?e[s-r]:0,l=s>i&&o?o[s-r]:0,f=Bv(u,c,l);e[s]=a+f}};ii.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw Error("Unrecognised filter type - "+e)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var nm=mt((dF,em)=>{var zv=xt("util"),tm=$u(),Kv=vu(),qv=em.exports=function(t){tm.call(this);let e=[],n=this;this._filter=new Kv(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};zv.inherits(qv,tm)});var oi=mt((hF,rm)=>{rm.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 Mu=mt((mF,im)=>{var Eu=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)if(e&1)e=3988292384^e>>>1;else e=e>>>1;Eu[t]=e}})();var Su=im.exports=function(){this._crc=-1};Su.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Eu[(this._crc^t[e])&255]^this._crc>>>8;return!0};Su.prototype.crc32=function(){return this._crc^-1};Su.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Eu[(e^t[n])&255]^e>>>8;return e^-1}});var Iu=mt((gF,om)=>{var St=oi(),Jv=Mu(),Nt=om.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[St.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[St.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[St.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[St.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[St.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[St.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Nt.prototype.start=function(){this.read(St.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Nt.prototype._parseSignature=function(t){let e=St.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Nt.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&n!==St.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Jv,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};Nt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Nt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Nt.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(Error("Crc error - "+e+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Nt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Nt.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in St.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let c=St.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&St.COLORTYPE_PALETTE),color:Boolean(i&St.COLORTYPE_COLOR),alpha:Boolean(i&St.COLORTYPE_ALPHA),bpp:c,colorType:i}),this._handleChunkEnd()};Nt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Nt.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Nt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Nt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===St.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}if(this._colorType===St.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===St.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Nt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Nt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/St.GAMMA_DIVISION),this._handleChunkEnd()};Nt.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Nt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===St.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(e);let n=t-e.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Nt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Nt.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ou=mt((Xv)=>{var sm=ku(),Yv=[function(){},function(t,e,n,r){if(r===e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Dv=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Vv(t,e){let n=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,a,c,u,l,f,d,m;switch(e){default:throw Error("unrecognised depth");case 16:d=t[r],r++,n.push((o<<8)+d);break;case 4:d=o&15,m=o>>4,n.push(m,d);break;case 2:l=o&3,f=o>>2&3,d=o>>4&3,m=o>>6&3,n.push(m,d,f,l);break;case 1:s=o&1,a=o>>1&1,c=o>>2&1,u=o>>3&1,l=o>>4&1,f=o>>5&1,d=o>>6&1,m=o>>7&1,n.push(m,d,f,l,u,c,a,s);break}}return{get:function(o){while(n.length<o)i();let s=n.slice(0,o);return n=n.slice(o),s},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Zv(t,e,n,r,i,o){let{width:s,height:a,index:c}=t;for(let u=0;u<a;u++)for(let l=0;l<s;l++){let f=n(l,u,c);Yv[r](e,i,f,o),o+=r}return o}function Qv(t,e,n,r,i,o){let{width:s,height:a,index:c}=t;for(let u=0;u<a;u++){for(let l=0;l<s;l++){let f=i.get(r),d=n(l,u,c);Dv[r](e,f,d,o)}i.resetAfterLine()}}Xv.dataToBitMap=function(t,e){let{width:n,height:r,depth:i,bpp:o,interlace:s}=e,a;if(i!==8)a=Vv(t,i);let c;if(i<=8)c=Buffer.alloc(n*r*4);else c=new Uint16Array(n*r*4);let u=Math.pow(2,i)-1,l=0,f,d;if(s)f=sm.getImagePasses(n,r),d=sm.getInterlaceIterator(n,r);else{let m=0;d=function(){let g=m;return m+=4,g},f=[{width:n,height:r}]}for(let m=0;m<f.length;m++)if(i===8)l=Zv(f[m],c,d,o,t,l);else Qv(f[m],c,d,o,a,u);if(i===8){if(l!==t.length)throw Error("extra data found")}else a.end();return c}});var Nu=mt((bF,am)=>{function eE(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let a=0;a<n;a++){let c=i[t[o]];if(!c)throw Error("index "+t[o]+" not in palette");for(let u=0;u<4;u++)e[o+u]=c[u];o+=4}}function nE(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let a=0;a<n;a++){let c=!1;if(i.length===1){if(i[0]===t[o])c=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])c=!0;if(c)for(let u=0;u<4;u++)e[o+u]=0;o+=4}}function rE(t,e,n,r,i){let o=255,s=Math.pow(2,i)-1,a=0;for(let c=0;c<r;c++)for(let u=0;u<n;u++){for(let l=0;l<4;l++)e[a+l]=Math.floor(t[a+l]*o/s+0.5);a+=4}}am.exports=function(t,e,n=!1){let{depth:r,width:i,height:o,colorType:s,transColor:a,palette:c}=e,u=t;if(s===3)eE(t,u,i,o,c);else{if(a)nE(t,u,i,o,a);if(r!==8&&!n){if(r===16)u=Buffer.alloc(i*o*4);rE(t,u,i,o,r)}}return u}});var lm=mt((wF,um)=>{var iE=xt("util"),Ru=xt("zlib"),cm=$u(),oE=nm(),sE=Iu(),aE=Ou(),cE=Nu(),Ce=um.exports=function(t){cm.call(this),this._parser=new sE(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};iE.inherits(Ce,cm);Ce.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};Ce.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ru.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,Ru.Z_MIN_CHUNK);this._inflate=Ru.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;o(a)}),this._filter.on("complete",this._complete.bind(this));let s=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,s(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Ce.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new oE(this._bitmapInfo)};Ce.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Ce.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Ce.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Ce.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Ce.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Ce.prototype._complete=function(t){if(this.errord)return;let e;try{let n=aE.dataToBitMap(t,this._bitmapInfo);e=cE(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var dm=mt(($F,fm)=>{var ue=oi();fm.exports=function(t,e,n,r){let i=[ue.COLORTYPE_COLOR_ALPHA,ue.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let $=new ArrayBuffer(2);return new DataView($).setInt16(0,256,!0),new Int16Array($)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,a=ue.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let c=ue.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,c*=2;let u=Buffer.alloc(e*n*c),l=0,f=0,d=r.bgColor||{};if(d.red===void 0)d.red=s;if(d.green===void 0)d.green=s;if(d.blue===void 0)d.blue=s;function m(){let g,$,w,b=s;switch(r.inputColorType){case ue.COLORTYPE_COLOR_ALPHA:b=o[l+3],g=o[l],$=o[l+1],w=o[l+2];break;case ue.COLORTYPE_COLOR:g=o[l],$=o[l+1],w=o[l+2];break;case ue.COLORTYPE_ALPHA:b=o[l+1],g=o[l],$=g,w=g;break;case ue.COLORTYPE_GRAYSCALE:g=o[l],$=g,w=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)b/=s,g=Math.min(Math.max(Math.round((1-b)*d.red+b*g),0),s),$=Math.min(Math.max(Math.round((1-b)*d.green+b*$),0),s),w=Math.min(Math.max(Math.round((1-b)*d.blue+b*w),0),s)}return{red:g,green:$,blue:w,alpha:b}}for(let g=0;g<n;g++)for(let $=0;$<e;$++){let w=m(o,l);switch(r.colorType){case ue.COLORTYPE_COLOR_ALPHA:case ue.COLORTYPE_COLOR:if(r.bitDepth===8){if(u[f]=w.red,u[f+1]=w.green,u[f+2]=w.blue,i)u[f+3]=w.alpha}else if(u.writeUInt16BE(w.red,f),u.writeUInt16BE(w.green,f+2),u.writeUInt16BE(w.blue,f+4),i)u.writeUInt16BE(w.alpha,f+6);break;case ue.COLORTYPE_ALPHA:case ue.COLORTYPE_GRAYSCALE:{let b=(w.red+w.green+w.blue)/3;if(r.bitDepth===8){if(u[f]=b,i)u[f+1]=w.alpha}else if(u.writeUInt16BE(b,f),i)u.writeUInt16BE(w.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=c}return u}});var gm=mt((kF,mm)=>{var hm=yu();function uE(t,e,n,r,i){for(let o=0;o<n;o++)r[i+o]=t[e+o]}function lE(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++)r+=Math.abs(t[o]);return r}function fE(t,e,n,r,i,o){for(let s=0;s<n;s++){let a=s>=o?t[e+s-o]:0,c=t[e+s]-a;r[i+s]=c}}function dE(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,a=t[e+o]-s;i+=Math.abs(a)}return i}function hE(t,e,n,r,i){for(let o=0;o<n;o++){let s=e>0?t[e+o-n]:0,a=t[e+o]-s;r[i+o]=a}}function mE(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++){let s=e>0?t[o-n]:0,a=t[o]-s;r+=Math.abs(a)}return r}function gE(t,e,n,r,i,o){for(let s=0;s<n;s++){let a=s>=o?t[e+s-o]:0,c=e>0?t[e+s-n]:0,u=t[e+s]-(a+c>>1);r[i+s]=u}}function pE(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,a=e>0?t[e+o-n]:0,c=t[e+o]-(s+a>>1);i+=Math.abs(c)}return i}function bE(t,e,n,r,i,o){for(let s=0;s<n;s++){let a=s>=o?t[e+s-o]:0,c=e>0?t[e+s-n]:0,u=e>0&&s>=o?t[e+s-(n+o)]:0,l=t[e+s]-hm(a,c,u);r[i+s]=l}}function wE(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,a=e>0?t[e+o-n]:0,c=e>0&&o>=r?t[e+o-(n+r)]:0,u=t[e+o]-hm(s,a,c);i+=Math.abs(u)}return i}var $E={0:uE,1:fE,2:hE,3:gE,4:bE},kE={0:lE,1:dE,2:mE,3:pE,4:wE};mm.exports=function(t,e,n,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=e*i,a=0,c=0,u=Buffer.alloc((s+1)*n),l=o[0];for(let f=0;f<n;f++){if(o.length>1){let d=1/0;for(let m=0;m<o.length;m++){let g=kE[o[m]](t,c,s,i);if(g<d)l=o[m],d=g}}u[a]=l,a++,$E[l](t,c,s,u,a,i),a+=s,c+=s}return u}});var Pu=mt((yF,pm)=>{var Tt=oi(),yE=Mu(),vE=dm(),EE=gm(),SE=xt("zlib"),On=pm.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||SE.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Tt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Tt.COLORTYPE_COLOR_ALPHA,[Tt.COLORTYPE_GRAYSCALE,Tt.COLORTYPE_COLOR,Tt.COLORTYPE_COLOR_ALPHA,Tt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Tt.COLORTYPE_GRAYSCALE,Tt.COLORTYPE_COLOR,Tt.COLORTYPE_COLOR_ALPHA,Tt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};On.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};On.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};On.prototype.filterData=function(t,e,n){let r=vE(t,e,n,this._options),i=Tt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return EE(r,e,n,this._options,i)};On.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e)e.copy(r,8);return r.writeInt32BE(yE.crc32(r.slice(4,r.length-4)),r.length-4),r};On.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Tt.GAMMA_DIVISION),0),this._packChunk(Tt.TYPE_gAMA,e)};On.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Tt.TYPE_IHDR,n)};On.prototype.packIDAT=function(t){return this._packChunk(Tt.TYPE_IDAT,t)};On.prototype.packIEND=function(){return this._packChunk(Tt.TYPE_IEND,null)}});var km=mt((vF,$m)=>{var ME=xt("util"),bm=xt("stream"),IE=oi(),OE=Pu(),wm=$m.exports=function(t){bm.call(this);let e=t||{};this._packer=new OE(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ME.inherits(wm,bm);wm.prototype.pack=function(t,e,n,r){if(this.emit("data",Buffer.from(IE.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var Im=mt((eo,Mm)=>{var ym=xt("assert").ok,si=xt("zlib"),NE=xt("util"),vm=xt("buffer").kMaxLength;function vr(t){if(!(this instanceof vr))return new vr(t);if(t&&t.chunkSize<si.Z_MIN_CHUNK)t.chunkSize=si.Z_MIN_CHUNK;if(si.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function RE(t){return new vr(t)}function Em(t,e){if(e)process.nextTick(e);if(!t._handle)return;t._handle.close(),t._handle=null}vr.prototype._processChunk=function(t,e,n){if(typeof n==="function")return si.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,a=0,c=[],u=0,l;this.on("error",function(g){l=g});function f(g,$){if(r._hadError)return;let w=o-$;if(ym(w>=0,"have should not go down"),w>0){let b=r._buffer.slice(r._offset,r._offset+w);if(r._offset+=w,b.length>s)b=b.slice(0,s);if(c.push(b),u+=b.length,s-=b.length,s===0)return!1}if($===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if($===0)return a+=i-g,i=g,!0;return!1}ym(this._handle,"zlib binding closed");let d;do d=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,o),d=d||this._writeState;while(!this._hadError&&f(d[0],d[1]));if(this._hadError)throw l;if(u>=vm)throw Em(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+vm.toString(16)+" bytes");let m=Buffer.concat(c,u);return Em(this),m};NE.inherits(vr,si.Inflate);function PE(t,e){if(typeof e==="string")e=Buffer.from(e);if(!(e instanceof Buffer))throw TypeError("Not a string or buffer");let n=t._finishFlushFlag;if(n==null)n=si.Z_FINISH;return t._processChunk(e,n)}function Sm(t,e){return PE(new vr(e),t)}Mm.exports=eo=Sm;eo.Inflate=vr;eo.createInflate=RE;eo.inflateSync=Sm});var Hu=mt((EF,Nm)=>{var Om=Nm.exports=function(t){this._buffer=t,this._reads=[]};Om.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Om.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Rm=mt((xE)=>{var HE=Hu(),FE=vu();xE.process=function(t,e){let n=[],r=new HE(t);return new FE(e,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var xm=mt((MF,Fm)=>{var Pm=!0,Hm=xt("zlib"),TE=Im();if(!Hm.deflateSync)Pm=!1;var AE=Hu(),CE=Rm(),jE=Iu(),GE=Ou(),UE=Nu();Fm.exports=function(t,e){if(!Pm)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 o(S){i=S}function s(S){i.transColor=S}function a(S){i.palette=S}function c(){i.alpha=!0}let u;function l(S){u=S}let f=[];function d(S){f.push(S)}let m=new AE(t);if(new jE(e,{read:m.read.bind(m),error:r,metadata:o,gamma:l,palette:a,transColor:s,inflateData:d,simpleTransparency:c}).start(),m.process(),n)throw n;let $=Buffer.concat(f);f.length=0;let w;if(i.interlace)w=Hm.inflateSync($);else{let I=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;w=TE($,{chunkSize:I,maxLength:I})}if($=null,!w||!w.length)throw Error("bad png - invalid inflate data response");let b=CE.process(w,i);$=null;let v=GE.dataToBitMap(b,i);b=null;let R=UE(v,i,e.skipRescale);return i.data=R,i.gamma=u||0,i}});var Cm=mt((IF,Am)=>{var Lm=!0,Tm=xt("zlib");if(!Tm.deflateSync)Lm=!1;var WE=oi(),_E=Pu();Am.exports=function(t,e){if(!Lm)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new _E(e||{}),i=[];if(i.push(Buffer.from(WE.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Tm.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var jm=mt((KE)=>{var BE=xm(),zE=Cm();KE.read=function(t,e){return BE(t,e||{})};KE.write=function(t,e){return zE(t,e)}});var Um=mt((QE)=>{var YE=xt("util"),Gm=xt("stream"),DE=lm(),VE=km(),ZE=jm(),Gt=QE.PNG=function(t){if(Gm.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new DE(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new VE(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};YE.inherits(Gt,Gm);Gt.sync=ZE;Gt.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};Gt.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};Gt.prototype.write=function(t){return this._parser.write(t),!0};Gt.prototype.end=function(t){this._parser.end(t)};Gt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Gt.prototype._gamma=function(t){this.gamma=t};Gt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Gt.bitblt=function(t,e,n,r,i,o,s,a){if(n|=0,r|=0,i|=0,o|=0,s|=0,a|=0,n>t.width||r>t.height||n+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>e.width||a>e.height||s+i>e.width||a+o>e.height)throw Error("bitblt writing outside image");for(let c=0;c<o;c++)t.data.copy(e.data,(a+c)*e.width+s<<2,(r+c)*t.width+n<<2,(r+c)*t.width+n+i<<2)};Gt.prototype.bitblt=function(t,e,n,r,i,o,s){return Gt.bitblt(this,t,e,n,r,i,o,s),this};Gt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Gt.prototype.adjustGamma=function(){Gt.adjustGamma(this)}});import{spawnSync as wH}from"node:child_process";import{isMainThread as $H}from"node:worker_threads";import{parseArgs as lH}from"node:util";var Ot={name:"@kecan0406/ttheme",version:"1.2.9",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, Warp and Konsole",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","konsole"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@jsquash/jpeg":"^1.6.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","@xterm/headless":"6.0.0","fast-string-width":"^3.0.2",pngjs:"7.0.0","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{existsSync as gP,readFileSync as V$}from"node:fs";import{styleText as Ls}from"node:util";import{stdout as kh,stdin as q1}from"node:process";import J1 from"node:readline";var rh=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),ih=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},oh=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var H1=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,F1=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,sh=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,x1=/\t{1,1000}/y,ah=/[\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,L1=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,T1=/\p{M}+/gu,A1={limit:1/0,ellipsis:""},ch=(t,e={},n={})=>{let r=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?ch(i,A1,n).width:0),s=0,a=n.controlWidth??0,c=n.tabWidth??8,u=n.emojiWidth??2,l=2,f=n.regularWidth??1,d=n.wideWidth??2,m=[[L1,f],[H1,0],[F1,a],[x1,c],[ah,u],[sh,d]],g=0,$=0,w=t.length,b=0,v=!1,R=w,S=Math.max(0,r-o),I=0,P=0,O=0,F=0;t:while(!0){if(P>I||$>=w&&$>g){let j=t.slice(I,P)||t.slice(g,$);b=0;for(let W of j.replaceAll(T1,"")){let D=W.codePointAt(0)||0;if(ih(D))F=2;else if(oh(D))F=d;else F=f;if(O+F>S)R=Math.min(R,Math.max(I,g)+b);if(O+F>r){v=!0;break t}b+=W.length,O+=F}I=P=0}if($>=w)break t;for(let j=0,W=m.length;j<W;j++){let[D,_]=m[j];if(D.lastIndex=$,D.test(t)){if(b=D===sh?rh(t.slice($,D.lastIndex)):D===ah?1:D.lastIndex-$,F=b*_,O+F>S)R=Math.min(R,$+Math.floor((S-O)/_));if(O+F>r){v=!0;break t}O+=F,I=g,P=$,$=g=D.lastIndex;continue t}}$+=1}return{width:v?S:O,index:v?R:w,truncated:v,ellipsed:v&&r>=o}},uh=ch;var C1={limit:1/0,ellipsis:"",ellipsisWidth:0},j1=(t,e={})=>{return uh(t,C1,e).width},tt=j1;var Ps="\x1B",mh="›",G1=39,Vc="\x07",gh="[",U1="]",ph="m",Zc=`${U1}8;;`,lh=new RegExp(`(?:\\${gh}(?<code>\\d+)m|\\${Zc}(?<uri>.*)${Vc})`,"y"),fh=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},dh=(t)=>`${Ps}${gh}${t}${ph}`,hh=(t)=>`${Ps}${Zc}${t}${Vc}`,Dc=(t,e,n)=>{let r=e[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),a=s===void 0?0:tt(s),c=r.next(),u=r.next(),l=0;while(!c.done){let f=c.value,d=tt(f);if(a+d<=n)t[t.length-1]+=f;else t.push(f),a=0;if(f===Ps||f===mh)i=!0,o=e.startsWith(Zc,l+1);if(i){if(o){if(f===Vc)i=!1,o=!1}else if(f===ph)i=!1}else if(a+=d,a===n&&!u.done)t.push(""),a=0;c=u,u=r.next(),l+=f.length}if(s=t.at(-1),!a&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},W1=(t)=>{let e=t.split(" "),n=e.length;while(n){if(tt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},_1=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),a=[""],c=0;for(let f=0;f<s.length;f++){let d=s[f];if(n.trim!==!1){let g=a.at(-1)??"",$=g.trimStart();if(g.length!==$.length)a[a.length-1]=$,c=tt($)}if(f!==0){if(c>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let m=tt(d);if(n.hard&&m>e){let g=e-c,$=1+Math.floor((m-g-1)/e);if(Math.floor((m-1)/e)<$)a.push("");Dc(a,d,e),c=tt(a.at(-1)??"");continue}if(c+m>e&&c&&m){if(n.wordWrap===!1&&c<e){Dc(a,d,e),c=tt(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>e&&n.wordWrap===!1){Dc(a,d,e),c=tt(a.at(-1)??"");continue}a[a.length-1]+=d,c+=m}if(n.trim!==!1)a=a.map((f)=>W1(f));let u=a.join(`
3
+ `),l=!1;for(let f=0;f<u.length;f++){let d=u[f];if(r+=d,!l){if(l=d>="\uD800"&&d<="\uDBFF",l)continue}else l=!1;if(d===Ps||d===mh){lh.lastIndex=f+1;let g=lh.exec(u)?.groups;if(g?.code!==void 0){let $=Number.parseFloat(g.code);i=$===G1?void 0:$}else if(g?.uri!==void 0)o=g.uri.length===0?void 0:g.uri}if(u[f+1]===`
4
+ `){if(o)r+=hh("");let m=i?fh(i):void 0;if(i&&m)r+=dh(m)}else if(d===`
5
+ `){if(i&&fh(i))r+=dh(i);if(o)r+=hh(o)}}return r},B1=/\r?\n/;function kn(t,e,n){return String(t).normalize().split(B1).map((r)=>_1(r,e,n)).join(`
6
+ `)}var Jt=Yc(Xc(),1);function tn(t,e,n){if(!n.some((s)=>!s.disabled))return t;let r=t+e,i=Math.max(n.length-1,0),o=r<0?i:r>i?0:r;return n[o]?.disabled?tn(o,e<0?-1:1,n):o}function Hs(t,e,n,r){let i=r.split(`
7
+ `),o=0,s=t;for(let c of i){if(s<=c.length)break;s-=c.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+n)),s=Math.min(s,i[o].length)+e;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let a=0;for(let c=0;c<o;c++)a+=i[c].length+1;return a+s}var Y1=["up","down","left","right","space","enter","cancel"],D1=["January","February","March","April","May","June","July","August","September","October","November","December"],Pt={actions:new Set(Y1),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:[...D1],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function yh(t,e){if(typeof t=="string")return Pt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&yh(n,e))return!0;return!1}function V1(t,e){if(t===e)return;let n=t.split(`
8
+ `),r=e.split(`
9
+ `),i=Math.max(n.length,r.length),o=[];for(let s=0;s<i;s++)n[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var TH=globalThis.process.platform.startsWith("win"),eu=Symbol("clack:cancel");function Lt(t){return t===eu}function Fs(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Ts=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,ru=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function yn(t,e,n,r=n,i=n,o){let s=Ts(t??kh);return kn(e,s-n.length,{hard:!0,trim:!1}).split(`
10
+ `).map((a,c,u)=>{let l=o?o(a,c):a;return c===0?`${r}${l}`:c===u.length-1?`${i}${l}`:`${n}${l}`}).join(`
11
+ `)}function vh(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}class Yt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=q1,output:r=kh,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],r=[];for(let i of n)i.cb(...e),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(eu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=J1.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),Fs(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Jt.cursor.show),this.output.off("resize",this.render),Fs(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Jt.cursor.show),this.output.off("resize",this.render),Fs(this.input,!1),t(eu)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&Pt.aliases.has(e.name)&&this.emit("cursor",Pt.aliases.get(e.name)),Pt.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=vh(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")}yh([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
12
+ `),Fs(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=kn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(Jt.cursor.move(-999,t*-1))}render(){let t=kn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Jt.cursor.hide);else{let e=V1(this._prevFrame,t),n=ru(this.output);if(this.restoreCursor(),e){let r=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),o=e.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(Jt.cursor.move(0,o-i)),this.output.write(Jt.erase.lines(1));let s=t.split(`
14
+ `);this.output.write(s[o]),this._prevFrame=t,this.output.write(Jt.cursor.move(0,s.length-o-1));return}else if(e.lines.length>1){if(r<i)o=r;else{let a=o-i;a>0&&this.output.write(Jt.cursor.move(0,a))}this.output.write(Jt.erase.down());let s=t.split(`
15
+ `).slice(o);this.output.write(s.join(`
16
+ `)),this._prevFrame=t;return}}this.output.write(Jt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function Z1(t,e){if(t===void 0||e.length===0)return 0;let n=e.findIndex((r)=>r.value===t);return n!==-1?n:0}function Q1(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function X1(t,e){if(e)return t?e:e[0]}var tv=class extends Yt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#n="";#t;#o;#a;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return Ls(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${e}${Ls("inverse",n)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#a=e.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=e.multiple===!0,this.#t=typeof e.options=="function"?e.filter:e.filter??Q1;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=n.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#e=o)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,o)=>this.#r(i,o)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(e,n){return e==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&e!==void 0&&e!==""}#r(e,n){let r=n.name==="up",i=n.name==="down",o=n.name==="return",s=this.userInput===""||this.userInput==="\t",a=this.#a,c=this.options,u=a!==void 0&&a!==""&&c.some((l)=>!l.disabled&&(this.#t?this.#t(a,l):!0));if(n.name==="tab"&&s&&u){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#e=tn(this.#e,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=X1(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((n)=>n!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#i(e){if(e!==this.#n){this.#n=e;let n=this.options;e&&this.#t?this.filteredOptions=n.filter((o)=>this.#t?.(e,o)):this.filteredOptions=[...n];let r=Z1(this.focusedValue,this.filteredOptions);this.#e=tn(r,0,this.filteredOptions);let i=this.filteredOptions[this.#e];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class iu extends Yt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(Jt.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var ev={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function wh(t){return[...t].map((e)=>ev[e])}function nv(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of e)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function tu(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function xs(t){return{year:tu(t.year),month:tu(t.month),day:tu(t.day)}}function nu(t,e){return new Date(t||2001,e||1,0).getDate()}function Eh(t){let{year:e,month:n,day:r}=xs(t);if(!e||e<0||e>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(e,n-1,r));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:e,month:n,day:r}}function $h(t){let e=Eh(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function rv(t,e,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&e.year===i.year?i.month:1,max:o&&e.year===o.year?o.month:12}:{min:i&&e.year===i.year&&e.month===i.month?i.day:1,max:o&&e.year===o.year&&e.month===o.month?o.day:nu(e.year,e.month)}}class Sh extends Yt{#e;#n;#t;#o;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#t}}get segments(){return this.#e}get separator(){return this.#n}get formattedValue(){return this.#f(this.#t)}#f(t){return this.#e.map((e)=>t[e.type]).join(this.#n)}#c(){this._setUserInput(this.#f(this.#t)),this._setValue($h(this.#t)??void 0)}constructor(t){let e=t.format?{segments:wh(t.format),separator:t.separator??"/"}:nv(t.locale),n=t.separator??e.separator,r=t.format?wh(t.format):e.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((a)=>o[a.type]).join(n);super({...t,initialUserInput:s},!1),this.#e=r,this.#n=n,this.#t=o,this.#o=t.minDate,this.#a=t.maxDate,this.#c(),this.on("cursor",(a)=>this.#m(a)),this.on("key",(a,c)=>this.#g(a,c)),this.on("finalize",()=>this.#p(t))}#u(){let t=Math.max(0,Math.min(this.#r.segmentIndex,this.#e.length-1)),e=this.#e[t];if(e)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,e.len-1)),{segment:e,index:t}}#l(t){this.inlineError="",this.#s=null;let e=this.#u();e&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#e.length-1,e.index+t)),this.#r.positionInSegment=0,this.#i=!0)}#d(t){let e=this.#u();if(!e)return;let{segment:n}=e,r=this.#t[n.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=rv(n.type,xs(this.#t),this.#o,this.#a),a;i?a=t===1?s.min:s.max:a=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[n.type]:a.toString().padStart(n.len,"0")},this.#i=!0,this.#s=null,this.#c()}#m(t){if(t)switch(t){case"right":return this.#l(1);case"left":return this.#l(-1);case"up":return this.#d(1);case"down":return this.#d(-1)}}#g(t,e){if(e?.name==="backspace"||e?.sequence===""||e?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let n=this.#u();if(!n)return;if(!this.#t[n.segment.type].replace(/_/g,"")){this.#l(-1);return}this.#t[n.segment.type]="_".repeat(n.segment.len),this.#i=!0,this.#r.positionInSegment=0,this.#c();return}if(e?.name==="tab"){this.inlineError="";let n=this.#u();if(!n)return;let r=e.shift?-1:1,i=n.index+r;i>=0&&i<this.#e.length&&(this.#r.segmentIndex=i,this.#r.positionInSegment=0,this.#i=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#u();if(!n)return;let{segment:r}=n,i=!this.#t[r.type].replace(/_/g,"");if(this.#i&&this.#s!==null&&!i){let d=this.#s+t,m={...this.#t,[r.type]:d},g=this.#h(m,r);if(g){this.inlineError=g,this.#s=null,this.#i=!1;return}this.inlineError="",this.#t[r.type]=d,this.#s=null,this.#i=!1,this.#c(),n.index<this.#e.length-1&&(this.#r.segmentIndex=n.index+1,this.#r.positionInSegment=0,this.#i=!0);return}this.#i&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#r.positionInSegment=0),this.#i=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),a=s>=0?s:Math.min(this.#r.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let c=o.slice(0,a)+t+o.slice(a+1),u=!1;if(a===0&&o==="__"&&(r.type==="month"||r.type==="day")){let d=Number.parseInt(t,10);c=`0${t}`,u=d<=(r.type==="month"?1:2)}if(r.type==="year"&&(c=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!c.includes("_")){let d={...this.#t,[r.type]:c},m=this.#h(d,r);if(m){this.inlineError=m;return}}this.inlineError="",this.#t[r.type]=c;let l=c.includes("_")?void 0:Eh(this.#t);if(l){let{year:d,month:m}=l,g=nu(d,m);this.#t={year:String(Math.max(0,Math.min(9999,d))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,m))).padStart(2,"0"),day:String(Math.max(1,Math.min(g,l.day))).padStart(2,"0")}}this.#c();let f=c.indexOf("_");u?(this.#i=!0,this.#s=t):f>=0?this.#r.positionInSegment=f:s>=0&&n.index<this.#e.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)}}#h(t,e){let{month:n,day:r}=xs(t);if(e.type==="month"&&(n<0||n>12))return Pt.date.messages.invalidMonth;if(e.type==="day"&&(r<0||r>31))return Pt.date.messages.invalidDay(31,"any month")}#p(t){let{year:e,month:n,day:r}=xs(this.#t);if(e&&n&&r){let i=nu(e,n);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=$h(this.#t)??t.defaultValue??void 0}}var iv=class extends Yt{options;cursor=0;#e;getGroupItems(e){return this.options.filter((n)=>n.group===e)}isGroupSelected(e){let n=this.getGroupItems(e),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let n=e.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(e.value);this.value=n?this.value.filter((r)=>r!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:n}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),this.#e?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},ov=new Set(["up","down","left","right"]);class Mh extends Yt{#e=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return n===`
17
+ `?`${e}█
18
+ ${r}`:`${e}${Ls("inverse",n)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let e=this.value??"";switch(t){case"up":this._cursor=Hs(this._cursor,0,-1,e);return;case"down":this._cursor=Hs(this._cursor,0,1,e);return;case"left":this._cursor=Hs(this._cursor,-1,0,e);return;case"right":this._cursor=Hs(this._cursor,1,0,e);return}}_shouldSubmit(t,e){if(this.#n)return this.focused==="submit"?!0:(this.#t(`
19
+ `),this._cursor++,!1);let n=this.#e;return this.#e=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
20
+ `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
21
+ `),this._cursor++,!1)}constructor(t){let e=t.initialUserInput??t.initialValue;super({...t,initialUserInput:e},!1),e!==void 0&&(this._cursor=e.length),this.#n=t.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&ov.has(r.name)){this.#e=!1,this.#o(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#e=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#t(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class ou extends Yt{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?tn(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=tn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Ih=class extends Yt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:i})=>i===e.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?tn(r,1,this.options):r,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=tn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tn(this.cursor,1,this.options);break}this.changeValue()})}};class su extends Yt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return`${e}${Ls("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as E,stripVTControlCharacters as BH}from"node:util";import ce from"node:process";var Hh=Yc(Xc(),1);function sv(){if(ce.platform!=="win32")return ce.env.TERM!=="linux";return Boolean(ce.env.CI)||Boolean(ce.env.WT_SESSION)||Boolean(ce.env.TERMINUS_SUBLIME)||ce.env.ConEmuTask==="{cmd::Cmder}"||ce.env.TERM_PROGRAM==="Terminus-Sublime"||ce.env.TERM_PROGRAM==="vscode"||ce.env.TERM==="xterm-256color"||ce.env.TERM==="alacritty"||ce.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var av=sv();var ot=(t,e)=>av?t:e,cv=ot("◆","*"),uv=ot("■","x"),lv=ot("▲","x"),uu=ot("◇","o"),fv=ot("┌","T"),Z=ot("│","|"),en=ot("└","—"),JH=ot("┐","T"),YH=ot("┘","—"),au=ot("●",">"),Cs=ot("○"," "),dv=ot("◻","[•]"),Oh=ot("◼","[+]"),Nh=ot("◻","[ ]"),DH=ot("▪","•"),Rh=ot("─","-"),hv=ot("╮","+"),mv=ot("├","+"),gv=ot("╯","+"),pv=ot("╰","+"),VH=ot("╭","+"),bv=ot("●","•"),wv=ot("◆","*"),$v=ot("▲","!"),kv=ot("■","x"),js=(t)=>{switch(t){case"initial":case"active":return E("cyan",cv);case"cancel":return E("red",uv);case"error":return E("yellow",lv);case"submit":return E("green",uu)}},Fh=(t)=>{switch(t){case"initial":case"active":return E("cyan",Z);case"cancel":return E("red",Z);case"error":return E("yellow",Z);case"submit":return E("green",Z)}};function xh(t,e){let n=[`${e?`${E("cyan",Z)} `:""}${t.join(" • ")}`];return e&&n.push(E("cyan",en)),n}var Ph=(t,e,n,r,i,o=!1)=>{let s=e,a=0;if(o)for(let c=r-1;c>=n;c--){let u=t[c];if(u&&(s-=u.length),a++,s<=i)break}else for(let c=n;c<r;c++){let u=t[c];if(u&&(s-=u.length),a++,s<=i)break}return{lineCount:s,removals:a}},cu=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let a=Ts(r)-o,c=ru(r),u=E("dim","..."),l=Math.max(c-s,0),f=Math.max(Math.min(i,l),5),d=0;t>=f-3&&(d=Math.max(Math.min(t-f+3,e.length-f),0));let m=f<e.length&&d>0,g=f<e.length&&d+f<e.length,$=Math.min(d+f,e.length),w=[],b=0;m&&b++,g&&b++;let v=d+(m?1:0),R=$-(g?1:0);for(let I=v;I<R;I++){let P=e[I],O=P?n(P,I===t):"",F=kn(O,a,{hard:!0,trim:!1}).split(`
22
+ `);w.push(F),b+=F.length}if(b>l){let I=0,P=0,O=b,F=t-v,j=l,W=()=>Ph(w,O,0,F,j),D=()=>Ph(w,O,F+1,w.length,j,!0);m?({lineCount:O,removals:I}=W(),O>j&&(g||(j-=1),{lineCount:O,removals:P}=D())):(g||(j-=1),{lineCount:O,removals:P}=D(),O>j&&(j-=1,{lineCount:O,removals:I}=W())),I>0&&(m=!0,w.splice(0,I)),P>0&&(g=!0,w.splice(w.length-P,P))}let S=[];m&&S.push(u);for(let I of w)for(let P of I)S.push(P);return g&&S.push(u),S};var nn=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new iu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Pt.withGuide,i=`${js(this.state)} `,o=r?`${E("gray",Z)} `:"",s=yn(t.output,t.message,o,i),a=`${r?`${E("gray",Z)}
33
23
  `:""}${s}
34
- `,a=this.value??[],u=(c,l)=>{if(c.disabled)return t(c,"disabled");let f=a.includes(c.value);return l&&f?t(c,"active-selected"):f?t(c,"selected"):t(c,l?"active":"inactive")};switch(this.state){case"submit":{let c=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"submitted")).join(S("dim",", "))||S("dim","none"),l=ns(e.output,c,i?`${S("gray",ke)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"cancelled")).join(S("dim",", "));if(c.trim()==="")return`${o}${S("gray",ke)}`;let l=ns(e.output,c,i?`${S("gray",ke)} `:"");return`${o}${l}${i?`
35
- ${S("gray",ke)}`:""}`}case"error":{let c=i?`${S("yellow",ke)} `:"",l=this.error.split(`
36
- `).map((h,g)=>g===0?`${i?`${S("yellow",An)} `:""}${S("yellow",h)}`:` ${h}`).join(`
37
- `),f=o.split(`
24
+ `,c=this.value?e:n;switch(this.state){case"submit":{let u=r?`${E("gray",Z)} `:"";return`${a}${u}${E("dim",c)}`}case"cancel":{let u=r?`${E("gray",Z)} `:"";return`${a}${u}${E(["strikethrough","dim"],c)}${r?`
25
+ ${E("gray",Z)}`:""}`}default:{let u=r?`${E("cyan",Z)} `:"",l=r?E("cyan",en):"";return`${a}${u}${this.value?`${E("green",au)} ${e}`:`${E("dim",Cs)} ${E("dim",e)}`}${t.vertical?r?`
26
+ ${E("cyan",Z)} `:`
27
+ `:` ${E("dim","/")} `}${this.value?`${E("dim",Cs)} ${E("dim",n)}`:`${E("green",au)} ${n}`}
28
+ ${l}
29
+ `}}}}).prompt()};var yv=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Space:")} select`,`${E("dim","Enter:")} confirm`],Zi=(t,e)=>t.split(`
30
+ `).map((n)=>e(n)).join(`
31
+ `),Lh=(t)=>{let e=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${E("gray",Nh)} ${Zi(s,(a)=>E(["strikethrough","gray"],a))}${i.hint?` ${E("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${E("cyan",dv)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${E("green",Oh)} ${Zi(s,(a)=>E("dim",a))}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${Zi(s,(a)=>E(["strikethrough","dim"],a))}`:o==="active-selected"?`${E("green",Oh)} ${s}${i.hint?` ${E("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${Zi(s,(a)=>E("dim",a))}`:`${E("dim",Nh)} ${Zi(s,(a)=>E("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new ou({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
32
+ ${E("reset",E("dim",`Press ${E(["gray","bgWhite","inverse"]," space ")} to select, ${E("gray",E("bgWhite",E("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??Pt.withGuide,o=yn(t.output,t.message,i?`${Fh(this.state)} `:"",`${js(this.state)} `),s=`${i?`${E("gray",Z)}
33
+ `:""}${o}
34
+ `,a=this.value??[],c=(u,l)=>{if(u.disabled)return e(u,"disabled");let f=a.includes(u.value);return l&&f?e(u,"active-selected"):f?e(u,"selected"):e(u,l?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:f})=>a.includes(f)).map((f)=>e(f,"submitted")).join(E("dim",", "))||E("dim","none"),l=yn(t.output,u,i?`${E("gray",Z)} `:"");return`${s}${l}`}case"cancel":{let u=this.options.filter(({value:f})=>a.includes(f)).map((f)=>e(f,"cancelled")).join(E("dim",", "));if(u.trim()==="")return`${s}${E("gray",Z)}`;let l=yn(t.output,u,i?`${E("gray",Z)} `:"");return`${s}${l}${i?`
35
+ ${E("gray",Z)}`:""}`}case"error":{let u=i?`${E("yellow",Z)} `:"",l=this.error.split(`
36
+ `).map((m,g)=>g===0?`${i?`${E("yellow",en)} `:""}${E("yellow",m)}`:` ${m}`).join(`
37
+ `),f=s.split(`
38
38
  `).length,d=l.split(`
39
- `).length+1;return`${o}${c}${uh({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:f+d,style:u}).join(`
40
- ${c}`)}
39
+ `).length+1;return`${s}${u}${cu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:f+d,style:c}).join(`
40
+ ${u}`)}
41
41
  ${l}
42
- `}default:{let c=i?`${S("cyan",ke)} `:"",l=o.split(`
43
- `).length,f=r?Lk(Ck,i):i?[S("cyan",An)]:[],d=f.join(`
44
- `),h=f.length+1;return`${o}${c}${uh({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+h,style:u}).join(`
45
- ${c}`)}
42
+ `}default:{let u=i?`${E("cyan",Z)} `:"",l=s.split(`
43
+ `).length,f=r?xh(yv,i):i?[E("cyan",en)]:[],d=f.join(`
44
+ `),m=f.length+1;return`${s}${u}${cu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:u.length,rowPadding:l+m,style:c}).join(`
45
+ ${u}`)}
46
46
  ${d}
47
- `}}}}).prompt()};var xn={message:(e=[],{symbol:t=S("gray",ke),secondarySymbol:n=S("gray",ke),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??at.withGuide,u=a?n:"",c=a?`${t} `:"",l=a?`${n} `:"";for(let d=0;d<i;d++)o.push(u);let f=Array.isArray(e)?e:e.split(`
48
- `);if(f.length>0){let[d,...h]=f;d.length>0?o.push(`${c}${d}`):o.push(a?t:"");for(let g of h)g.length>0?o.push(`${l}${g}`):o.push(a?n:"")}r.write(`${o.join(`
47
+ `}}}}).prompt()};var vn={message:(t=[],{symbol:e=E("gray",Z),secondarySymbol:n=E("gray",Z),output:r=process.stdout,spacing:i=1,withGuide:o}={})=>{let s=[],a=o??Pt.withGuide,c=a?n:"",u=a?`${e} `:"",l=a?`${n} `:"";for(let d=0;d<i;d++)s.push(c);let f=Array.isArray(t)?t:t.split(`
48
+ `);if(f.length>0){let[d,...m]=f;d.length>0?s.push(`${u}${d}`):s.push(a?e:"");for(let g of m)g.length>0?s.push(`${l}${g}`):s.push(a?n:"")}r.write(`${s.join(`
49
49
  `)}
50
- `)},info:(e,t)=>{xn.message(e,{...t,symbol:S("blue",Fk)})},success:(e,t)=>{xn.message(e,{...t,symbol:S("green",Tk)})},step:(e,t)=>{xn.message(e,{...t,symbol:S("green",tc)})},warn:(e,t)=>{xn.message(e,{...t,symbol:S("yellow",Hk)})},warning:(e,t)=>{xn.warn(e,t)},error:(e,t)=>{xn.message(e,{...t,symbol:S("red",xk)})}},ti=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${S("gray",An)} `:"";n.write(`${r}${S("red",e)}
50
+ `)},info:(t,e)=>{vn.message(t,{...e,symbol:E("blue",bv)})},success:(t,e)=>{vn.message(t,{...e,symbol:E("green",wv)})},step:(t,e)=>{vn.message(t,{...e,symbol:E("green",uu)})},warn:(t,e)=>{vn.message(t,{...e,symbol:E("yellow",$v)})},warning:(t,e)=>{vn.warn(t,e)},error:(t,e)=>{vn.message(t,{...e,symbol:E("red",kv)})}},Zr=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pt.withGuide?`${E("gray",en)} `:"";n.write(`${r}${E("red",t)}
51
51
 
52
- `)},Wo=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${S("gray",Sk)} `:"";n.write(`${r}${e}
53
- `)},rc=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${S("gray",ke)}
54
- ${S("gray",An)} `:"";n.write(`${r}${e}
52
+ `)},Gs=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pt.withGuide?`${E("gray",fv)} `:"";n.write(`${r}${t}
53
+ `)},lu=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Pt.withGuide?`${E("gray",Z)}
54
+ ${E("gray",en)} `:"";n.write(`${r}${t}
55
55
 
56
- `)};var _k=(e)=>e,Gk=(e,t,n)=>{let r={hard:!0,trim:!1},i=Hn(e,t,r).split(`
57
- `),s=i.reduce((u,c)=>Math.max($e(c),u),0),o=i.map(n).reduce((u,c)=>Math.max($e(c),u),0),a=t-(o-s);return Hn(e,a,r)},vr=(e="",t="",n)=>{let r=n?.output??Tt.stdout,i=n?.withGuide??at.withGuide,s=n?.format??_k,o=["",...Gk(e,Go(r)-6,s).split(`
58
- `).map(s),""],a=$e(t),u=Math.max(o.reduce((d,h)=>{let g=$e(h);return g>d?g:d},0),a)+2,c=o.map((d)=>`${S("gray",ke)} ${d}${" ".repeat(u-$e(d))}${S("gray",ke)}`).join(`
59
- `),l=i?`${S("gray",ke)}
60
- `:"",f=i?Pk:Ok;r.write(`${l}${S("green",tc)} ${S("reset",t)} ${S("gray",oh.repeat(Math.max(u-a-1,1))+Nk)}
61
- ${c}
62
- ${S("gray",f+oh.repeat(u+2)+Rk)}
63
- `)};var HR={light:Oe("─","-"),heavy:Oe("━","="),block:Oe("█","#")};var xR=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Enter:")} confirm`];var AR=`${S("gray",ke)} `;var ic=(e)=>new ec({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??at.withGuide,n=`${`${t?`${S("gray",ke)}
64
- `:""}${nc(this.state)} `}${e.message}
65
- `,r=e.placeholder&&e.placeholder.length>0?S("inverse",e.placeholder[0])+S("dim",e.placeholder.slice(1)):S(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${S("yellow",this.error)}`:"",a=t?`${S("yellow",ke)} `:"",u=t?S("yellow",An):"";return`${n.trim()}
56
+ `)};var vv=(t)=>t,Ev=(t,e,n)=>{let r={hard:!0,trim:!1},i=kn(t,e,r).split(`
57
+ `),o=i.reduce((c,u)=>Math.max(tt(u),c),0),s=i.map(n).reduce((c,u)=>Math.max(tt(u),c),0),a=e-(s-o);return kn(t,a,r)},wr=(t="",e="",n)=>{let r=n?.output??ce.stdout,i=n?.withGuide??Pt.withGuide,o=n?.format??vv,s=["",...Ev(t,Ts(r)-6,o).split(`
58
+ `).map(o),""],a=tt(e),c=Math.max(s.reduce((d,m)=>{let g=tt(m);return g>d?g:d},0),a)+2,u=s.map((d)=>`${E("gray",Z)} ${d}${" ".repeat(c-tt(d))}${E("gray",Z)}`).join(`
59
+ `),l=i?`${E("gray",Z)}
60
+ `:"",f=i?mv:pv;r.write(`${l}${E("green",uu)} ${E("reset",e)} ${E("gray",Rh.repeat(Math.max(c-a-1,1))+hv)}
61
+ ${u}
62
+ ${E("gray",f+Rh.repeat(c+2)+gv)}
63
+ `)};var ZH={light:ot("─","-"),heavy:ot("━","="),block:ot("█","#")};var Sv=[`${E("dim","↑/↓")} to navigate`,`${E("dim","Enter:")} confirm`],As=(t,e)=>t.includes(`
64
+ `)?t.split(`
65
+ `).map((n)=>e(n)).join(`
66
+ `):e(t),Th=(t)=>{let e=(r,i)=>{if(r===void 0)return"";let o=r.label??String(r.value);switch(i){case"disabled":return`${E("gray",Cs)} ${As(o,(s)=>E("gray",s))}${r.hint?` ${E("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${As(o,(s)=>E("dim",s))}`;case"active":return`${E("green",au)} ${o}${r.hint?` ${E("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${As(o,(s)=>E(["strikethrough","dim"],s))}`;default:return`${E("dim",Cs)} ${As(o,(s)=>E("dim",s))}`}},n=t.showInstructions??!0;return new Ih({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??Pt.withGuide,i=`${js(this.state)} `,o=`${Fh(this.state)} `,s=yn(t.output,t.message,o,i),a=`${r?`${E("gray",Z)}
67
+ `:""}${s}
68
+ `;switch(this.state){case"submit":{let c=r?`${E("gray",Z)} `:"",u=yn(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${u}`}case"cancel":{let c=r?`${E("gray",Z)} `:"",u=yn(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${u}${r?`
69
+ ${E("gray",Z)}`:""}`}default:{let c=r?`${E("cyan",Z)} `:"",u=a.split(`
70
+ `).length,l=n?xh(Sv,r):r?[E("cyan",en)]:[],f=l.join(`
71
+ `),d=l.length+1;return`${a}${c}${cu({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:u+d,style:(m,g)=>e(m,m.disabled?"disabled":g?"active":"inactive")}).join(`
72
+ ${c}`)}
73
+ ${f}
74
+ `}}}}).prompt()};var QH=`${E("gray",Z)} `;var fu=(t)=>new su({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??Pt.withGuide,n=`${`${e?`${E("gray",Z)}
75
+ `:""}${js(this.state)} `}${t.message}
76
+ `,r=t.placeholder&&t.placeholder.length>0?E("inverse",t.placeholder[0])+E("dim",t.placeholder.slice(1)):E(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,o=this.value??"";switch(this.state){case"error":{let s=this.error?` ${E("yellow",this.error)}`:"",a=e?`${E("yellow",Z)} `:"",c=e?E("yellow",en):"";return`${n.trim()}
66
77
  ${a}${i}
67
- ${u}${o}
68
- `}case"submit":{let o=s?` ${S("dim",s)}`:"",a=t?S("gray",ke):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${S(["strikethrough","dim"],s)}`:"",a=t?S("gray",ke):"";return`${n}${a}${o}${s.trim()?`
69
- ${a}`:""}`}default:{let o=t?`${S("cyan",ke)} `:"",a=t?S("cyan",An):"";return`${n}${o}${i}
78
+ ${c}${s}
79
+ `}case"submit":{let s=o?` ${E("dim",o)}`:"",a=e?E("gray",Z):"";return`${n}${a}${s}`}case"cancel":{let s=o?` ${E(["strikethrough","dim"],o)}`:"",a=e?E("gray",Z):"";return`${n}${a}${s}${o.trim()?`
80
+ ${a}`:""}`}default:{let s=e?`${E("cyan",Z)} `:"",a=e?E("cyan",en):"";return`${n}${s}${i}
70
81
  ${a}
71
- `}}}}).prompt();function sc(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 Xt(e){return`\x1B[38;2;${sc(e)}m`}function Uo(e,t){return`\x1B[48;2;${sc(e)};38;2;${sc(t)}m`}function fh(e,t="\x1B[39m"){return`${e.map((n)=>`${Xt(n)}■`).join(" ")}${t}`}var ss="⧉";function jo(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function Wk(e,t){if(e[t]!=="\x1B")return 0;if(e[t+1]==="]"){let r=e.indexOf("\x07",t+2),i=e.indexOf("\x1B\\",t+2),s=r!==-1&&(i===-1||r<i)?r+1:i!==-1?i+2:0;return s?s-t:0}if(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 dh(e,t){let n="",r=0,i=0;while(i<e.length){let s=Wk(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=$e(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r}}function rt(e,t,n=!0){if(t<=0)return"";let r=$e(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=dh(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function wn(e,t,n){let r=n-$e(t)-1;return r<=0?rt(e,n):`${rt(e,r)} ${t}`}function Qe(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if($e(s)<=t){r=s;continue}if(r)n.push(r);while($e(i)>t){let{head:o}=dh(i,t),a=Math.max(o.lastIndexOf("/")+1,o.lastIndexOf("#")),u=a>0?a:o.length;n.push(i.slice(0,u)),i=i.slice(u)}r=i}if(r)n.push(r);return n}import{existsSync as gp,readFileSync as ml}from"node:fs";import{join as mp}from"node:path";var Uk=/^#[0-9a-f]{6}$/;function Ht(e){return Uk.test(e)}function ve(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function it(e,t,n){let r=ve(e),i=ve(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function ze(e){let[t,n,r]=ve(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 Be(e,t){let n=ze(e),r=ze(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Ko(e,t){return Math.round(Be(e,t)*100)/100}function jk(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Je(e){let[t,n,r]=ve(e).map(jk),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 Ln=7,hh=3,oc=0.15,gh=1.6,uc=[1,2,3,4,5,6,9,10,11,12,13,14],mh=[7,15],Cn=[1,2,3,4,5,6],kn={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}},as=0.03,jt=25,ri=15,ii=0.08;function $n(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function ac(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=$n(e,i);return Be(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Ko(s,r)}:1, needs ${n}:1`]:[]})}function ph(e,t){return Math.min(...t.map((n)=>Be($n(e,n),e.background)))}var bh=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Ln,measure:({foreground:e,background:t})=>Be(e,t),check:({foreground:e,background:t})=>Be(e,t)<Ln?[`foreground ${e} on ${t} is ${Ko(e,t)}:1, needs ${Ln}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:hh,measure:(e)=>ph(e,uc),check:(e)=>ac(e,uc,hh)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:oc,measure:(e)=>ze($n(e,0)),check:(e)=>{let t=$n(e,0);return ze(t)>oc?[`ANSI 0 ${t} has luminance ${ze(t).toFixed(3)}, needs <= ${oc}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Ln,measure:(e)=>ph(e,mh),check:(e)=>ac(e,mh,Ln)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:gh,measure:(e)=>Be($n(e,8),e.background),check:(e)=>ac(e,[8],gh)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Ln,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Be(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Be(e,t)<Ln?[`foreground ${e} on selection ${t} is ${Ko(e,t)}:1, needs ${Ln}:1`]:[]}];function Dt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var _n=(e)=>e>8?e-8:e;function si(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Cn.includes(_n(n))?[n,n>8?n-8:n+8]:[n]))}function os(e,t){let n=Je($n(e,t));return n.c<as?void 0:n}function ni(e){let t=si(e);return uc.flatMap((n)=>{let r=os(e,n),i=kn[_n(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Dt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function Mr(e){let t=new Set(e.signatureSlots);return Cn.flatMap((n)=>{let r=os(e,n),i=os(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Dt(r.h,i.h)}]})}function Sr(e){let t=si(e);return[0,8].flatMap((n)=>Cn.flatMap((r)=>Cn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=os(e,s),u=os(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Dt(a.h,u.h)<ri&&Math.abs(a.l-u.l)<ii?[[s,o]]:[]})))}var Kk=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...ni(e).map((t)=>t.over)),check:(e)=>ni(e).map(({slot:t,hue:n,over:r})=>{let i=kn[_n(t)];return`ANSI ${t} ${$n(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:jt,measure:(e)=>Math.max(0,...Mr(e).map((t)=>t.gap)),check:(e)=>Mr(e).filter((t)=>t.gap>jt).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${jt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>Sr(e).length,check:(e)=>Sr(e).map(([t,n])=>`ANSI ${t} ${$n(e,t)} and ANSI ${n} ${$n(e,n)} are within ${ri}° hue and ${ii} lightness`)}],Bo=[...bh,...Kk],cc=Bo.map((e)=>e.rule),bt=Bo.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 Gn(e){return Bo.map((t)=>Math.round(t.measure(e)*1000)/1000)}function wh(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 Ir(e){return wh(Bo,e)}function $h(e){return wh(bh,e)}function kh(e){return e.flatMap(Ir)}import{chmodSync as Bk,copyFileSync as Jk,existsSync as oi,mkdirSync as qk,readFileSync as lc,realpathSync as Vk,renameSync as zk,rmSync as yh,statSync as Yk,writeFileSync as Qk}from"node:fs";import{dirname as Zk}from"node:path";function Eh(e){return`${e}.ttheme.bak`}var Xk=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function fc(e){let t=Eh(e);if(oi(e)&&!oi(t)&&!Xk.test(lc(e,"utf8")))Jk(e,t)}function K(e,t){let n=oi(e)?Vk(e):e;qk(Zk(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(Qk(r,t),oi(n))Bk(r,Yk(n).mode&4095);zk(r,n)}function en(e,t){if((oi(e)?lc(e,"utf8"):void 0)===t)return!1;return fc(e),K(e,t),!0}function vh(e,t){let n=Eh(e),r=oi(n)?lc(n,"utf8"):void 0;if(t===""&&r===void 0)return yh(e,{force:!0}),"removed";if(K(e,t),r===void 0||r===t)return yh(n,{force:!0}),"restored";return"kept backup"}import{createHash as Tm}from"node:crypto";import{copyFileSync as RE,existsSync as Qc,mkdirSync as OE,readdirSync as FE,readFileSync as ha,renameSync as Hm,rmSync as $i}from"node:fs";import{basename as xm,isAbsolute as TE,join as D}from"node:path";var Sg=Ho(Oh(),1),qo=Ho(Eg(),1);import{deflateSync as Mg}from"node:zlib";var li=[137,80,78,71,13,10,26,10],Ig=13,Ng=3;function fi(e){return e.length>=li.length&&li.every((t,n)=>e[n]===t)}function At(e){let t=qo.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Kn(e,t){if(fi(e)){let n=Jn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return At(e)}if(e[0]===255&&e[1]===216){let n=Sg.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 Pg(e,t){let{width:n,height:r,at:i}=t,s=Math.max(0,i.x),o=Math.max(0,i.y),a=Math.min(n,i.x+i.w),u=Math.min(r,i.y+i.h);if(a<=s||u<=o)return;let c={x:s,y:o,w:a-s,h:u-o};if(i.w===e.width&&i.h===e.height)return{part:e,box:c,dx:s-i.x,dy:o-i.y};let l={x:(s-i.x)*e.width/i.w,y:(o-i.y)*e.height/i.h,w:c.w*e.width/i.w,h:c.h*e.height/i.h};return{part:cs(e,l,c.w,c.h),box:c,dx:0,dy:0}}function Rg(e,t){let n=new Uint8Array(t.width*t.height*4),r=Pg(e,t);if(r){let{part:i,box:s,dx:o,dy:a}=r;for(let u=0;u<s.h;u++){let c=((u+a)*i.width+o)*4;n.set(i.data.subarray(c,c+s.w*4),((s.y+u)*t.width+s.x)*4)}}return{width:t.width,height:t.height,data:n}}function Vo(e,t,n,r={width:e.width,height:e.height,at:{x:0,y:0,w:e.width,h:e.height}}){let i=ve(t),{width:s,height:o}=r,a=new Uint8Array(s*o*3);for(let h=0;h<s*3;h+=3)a.set(i,h);for(let h=1;h<o;h++)a.copyWithin(h*s*3,0,s*3);let u=Pg(e,r);if(!u)return{width:s,height:o,data:a};let{part:c,box:l,dx:f,dy:d}=u;for(let h=0;h<l.h;h++)for(let g=0;g<l.w;g++){let b=((h+d)*c.width+g+f)*4,p=((l.y+h)*s+l.x+g)*3,m=c.data[b+3]/255*n;for(let k=0;k<3;k++)a[p+k]=Math.round(i[k]*(1-m)+c.data[b+k]*m)}return{width:s,height:o,data:a}}function Bn(e){let t=new qo.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),qo.PNG.sync.write(t)}function vg(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 Jn(e){if(e.length<33||!fi(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=vg(e,"IDAT");return{width:n,height:r,alpha:vg(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function Og(e,t=Ig){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 yn(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)<Ig)n++;return Math.round(n*100/(t.w*t.h))}function Fg(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=cs(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 b1(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 Nc(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,f)=>t+f),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 f=t+(l+0.5)*i,d=Math.floor(f-o-0.5),h=Math.max(0,Math.min(e-a,d));u[l]=h;let g=0;for(let b=d;b<=Math.ceil(f+o-0.5);b++){let p=b1((b+0.5-f)/s),m=l*a+Math.min(e-1,Math.max(0,b))-h;c[m]=(c[m]??0)+p,g+=p}for(let b=l*a;b<(l+1)*a;b++)c[b]=(c[b]??0)/g}return{first:u,size:a,weights:c}}function Tg(e,t,n,r,i,s){let o=Nc(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 f=o.first[l]??0;for(let h of c.keys())if(h<f)c.delete(h);let d=l*a;for(let h=0;h<o.size;h++){let g=o.weights[l*o.size+h]??0;if(g===0)continue;let b=c.get(f+h);if(!b)b=new Float32Array(a),s(f+h,b),c.set(f+h,b);for(let p=0;p<a;p++)u[d+p]=(u[d+p]??0)+(b[p]??0)*g}}return u}function cs(e,t,n,r){let i=Nc(e.width,t.x,t.w,n),s=e.data,o=Tg(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let f=0;f<n;f++){let d=l+(i.first[f]??0),h=f*i.size,g=0,b=0,p=0,m=0;for(let k=0;k<i.size;k++){let v=(d+k)*4,M=(i.weights[h+k]??0)*(s[v+3]??0);g+=(s[v]??0)*M,b+=(s[v+1]??0)*M,p+=(s[v+2]??0)*M,m+=M}c[f*4]=g,c[f*4+1]=b,c[f*4+2]=p,c[f*4+3]=m}}),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 Hg(e,t,n,r){let i=Nc(e.width,t.x,t.w,n),s=e.data,o=Tg(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let f=c+(i.first[l]??0),d=l*i.size,h=0;for(let g=0;g<i.size;g++)h+=(s[f+g]??0)*(i.weights[d+g]??0);u[l]=h}});return{width:n,height:r,data:o}}function ls(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,f)=>Math.exp(-((f-n)**2)/(2*t*t))),i=r.reduce((l,f)=>l+f,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=0;d<s;d++){let h=0;for(let g=-n;g<=n;g++)h+=(a[f+Math.min(s-1,Math.max(0,d+g))]??0)*(r[g+n]??0);u[f+d]=h/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=-n;d<=n;d++){let h=(r[d+n]??0)/i,g=Math.min(o-1,Math.max(0,l+d))*s;for(let b=0;b<s;b++)c[f+b]=(c[f+b]??0)+(u[g+b]??0)*h}}return{width:s,height:o,data:c}}function fs(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 ds(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 w1=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 $1(e){let t=4294967295;for(let n of e)t=(w1[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function jn(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($1(n.subarray(4,8+t.length)),8+t.length),n}function k1(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,f=s>0?e[u+c]??0:0,d=c>0&&s>0?e[u+c-1]??0:0,h=Math.abs(f-d),g=Math.abs(l-d),b=Math.abs(l+f-2*d);i[o+1+c]=(e[a+c]??0)-(h<=g&&h<=b?l:g<=b?f:d)&255}}return i}function xg(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(li),jn("IHDR",r),...n,jn("IDAT",Mg(k1(e.data,e.width,e.height))),jn("IEND",new Uint8Array)])}function Ag(e){let[t,n,r]=ve(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return jn("PLTE",i)}function Lg(e,t,n,r,i){let s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=n;let o=e*r,a=new Uint8Array(t*(o+1));for(let u=0;u<t;u++)a.set(i.subarray(u*o,(u+1)*o),u*(o+1)+1);return Buffer.concat([Buffer.from(li),jn("IHDR",s),jn("IDAT",Mg(a,{level:1})),jn("IEND",new Uint8Array)])}function zo(e){return Lg(e.width,e.height,2,3,e.data)}function Cg(e){return Lg(e.width,e.height,6,4,e.data)}function hs(e,t){return xg(e,Ng,[Ag(t),jn("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function Pc(e){return xg(e,0,[])}function _g(e,t){if(!fi(e)||e[25]!==Ng)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(li)],i=li.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?Ag(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as bE,readFileSync as $m}from"node:fs";import{basename as wE,join as km}from"node:path";/*!
82
+ `}}}}).prompt();function du(t){let e=t.replace("#","");return[e.slice(0,2),e.slice(2,4),e.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function xe(t){return`\x1B[38;2;${du(t)}m`}function Us(t,e){return`\x1B[48;2;${du(t)};38;2;${du(e)}m`}function Ah(t,e="\x1B[39m"){return`${t.map((n)=>`${xe(n)}■`).join(" ")}${e}`}var Qi="⧉";function Ws(t,e){return e?`\x1B]8;;${e}\x1B\\${t}\x1B]8;;\x1B\\`:t}function Mv(t,e){if(t[e]!=="\x1B")return 0;if(t[e+1]==="]"){let r=t.indexOf("\x07",e+2),i=t.indexOf("\x1B\\",e+2),o=r!==-1&&(i===-1||r<i)?r+1:i!==-1?i+2:0;return o?o-e:0}if(t[e+1]!=="[")return 0;let n=e+2;while(n<t.length&&!/[@-~]/.test(t[n]))n++;return n<t.length?n-e+1:0}function Ch(t,e){let n="",r=0,i=0;while(i<t.length){let o=Mv(t,i);if(o>0){n+=t.slice(i,i+o),i+=o;continue}let s=String.fromCodePoint(t.codePointAt(i)),a=tt(s);if(r+a>e)break;n+=s,r+=a,i+=s.length}return{head:n,used:r}}function Et(t,e,n=!0){if(e<=0)return"";let r=tt(t);if(r<=e)return n?t+" ".repeat(e-r):t;let{head:i,used:o}=Ch(t,e-1);return`${i}${t.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(e-1-o):""}`}function be(t,e,n){let r=n-tt(e)-1;return r<=0?Et(t,n):`${Et(t,r)} ${e}`}function kt(t,e){let n=[],r="";for(let i of t.split(/\s+/).filter(Boolean)){let o=r?`${r} ${i}`:i;if(tt(o)<=e){r=o;continue}if(r)n.push(r);while(tt(i)>e){let{head:s}=Ch(i,e),a=Math.max(s.lastIndexOf("/")+1,s.lastIndexOf("#")),c=a>0?a:s.length;n.push(i.slice(0,c)),i=i.slice(c)}r=i}if(r)n.push(r);return n}import{existsSync as Dp,readFileSync as vl}from"node:fs";import{join as Vp}from"node:path";var Iv=/^#[0-9a-f]{6}$/;function Bt(t){return Iv.test(t)}function nt(t){let e=Number.parseInt(t.slice(1),16);return[e>>16&255,e>>8&255,e&255]}function Ht(t,e,n){let r=nt(t),i=nt(e);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*n).toString(16).padStart(2,"0")).join("")}`}function yt(t){let[e,n,r]=nt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*e+0.7152*n+0.0722*r}function pt(t,e){let n=yt(t),r=yt(e);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function _s(t,e){return Math.round(pt(t,e)*100)/100}function Ov(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function dt(t){let[e,n,r]=nt(t).map(Ov),i=Math.cbrt(0.4122214708*e+0.5363325363*n+0.0514459929*r),o=Math.cbrt(0.2119034982*e+0.6806995451*n+0.1073969566*r),s=Math.cbrt(0.0883024619*e+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*o+0.4505937099*s,c=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(a,c),h:(Math.atan2(c,a)*180/Math.PI+360)%360}}var En=7,jh=3,hu=0.15,Gh=1.6,gu=[1,2,3,4,5,6,9,10,11,12,13,14],Uh=[7,15],Sn=[1,2,3,4,5,6],on={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}},to=0.03,we=25,ti=15,ei=0.08;function rn(t,e){let n=t.ansi[e];if(n===void 0)throw Error(`${t.name}: missing ANSI ${e}`);return n}function mu(t,e,n){let r=t.background;return e.flatMap((i)=>{let o=rn(t,i);return pt(o,r)<n?[`ANSI ${i} ${o} on ${r} is ${_s(o,r)}:1, needs ${n}:1`]:[]})}function Wh(t,e){return Math.min(...e.map((n)=>pt(rn(t,n),t.background)))}var _h=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:En,measure:({foreground:t,background:e})=>pt(t,e),check:({foreground:t,background:e})=>pt(t,e)<En?[`foreground ${t} on ${e} is ${_s(t,e)}:1, needs ${En}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:jh,measure:(t)=>Wh(t,gu),check:(t)=>mu(t,gu,jh)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:hu,measure:(t)=>yt(rn(t,0)),check:(t)=>{let e=rn(t,0);return yt(e)>hu?[`ANSI 0 ${e} has luminance ${yt(e).toFixed(3)}, needs <= ${hu}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:En,measure:(t)=>Wh(t,Uh),check:(t)=>mu(t,Uh,En)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Gh,measure:(t)=>pt(rn(t,8),t.background),check:(t)=>mu(t,[8],Gh)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:En,measure:({foreground:t,selectionBackground:e})=>e===void 0?Number.NaN:pt(t,e),check:({foreground:t,selectionBackground:e})=>e!==void 0&&pt(t,e)<En?[`foreground ${t} on selection ${e} is ${_s(t,e)}:1, needs ${En}:1`]:[]}];function Le(t,e){let n=Math.abs(t-e)%360;return Math.min(n,360-n)}var Mn=(t)=>t>8?t-8:t;function ni(t){let e=t.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(e.flatMap((n)=>Sn.includes(Mn(n))?[n,n>8?n-8:n+8]:[n]))}function Xi(t,e){let n=dt(rn(t,e));return n.c<to?void 0:n}function Xr(t){let e=ni(t);return gu.flatMap((n)=>{let r=Xi(t,n),i=on[Mn(n)];if(r===void 0||i===void 0||e.has(n))return[];let o=Le(r.h,i.center)-i.width;return o>0?[{slot:n,hue:r.h,over:o}]:[]})}function $r(t){let e=new Set(t.signatureSlots);return Sn.flatMap((n)=>{let r=Xi(t,n),i=Xi(t,n+8);if(r===void 0||i===void 0||e.has(`ansi${n}`)&&e.has(`ansi${n+8}`))return[];return[{normal:n,gap:Le(r.h,i.h)}]})}function kr(t){let e=ni(t);return[0,8].flatMap((n)=>Sn.flatMap((r)=>Sn.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[n+r,n+i],a=Xi(t,o),c=Xi(t,s);if(a===void 0||c===void 0||e.has(o)&&e.has(s))return[];return Le(a.h,c.h)<ti&&Math.abs(a.l-c.l)<ei?[[o,s]]:[]})))}var Nv=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(t)=>Math.max(0,...Xr(t).map((e)=>e.over)),check:(t)=>Xr(t).map(({slot:e,hue:n,over:r})=>{let i=on[Mn(e)];return`ANSI ${e} ${rn(t,e)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:we,measure:(t)=>Math.max(0,...$r(t).map((e)=>e.gap)),check:(t)=>$r(t).filter((e)=>e.gap>we).map(({normal:e,gap:n})=>`ANSI ${e+8} is ${n.toFixed(0)}° from ANSI ${e}, needs <= ${we}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(t)=>kr(t).length,check:(t)=>kr(t).map(([e,n])=>`ANSI ${e} ${rn(t,e)} and ANSI ${n} ${rn(t,n)} are within ${ti}° hue and ${ei} lightness`)}],Bs=[..._h,...Nv],pu=Bs.map((t)=>t.rule),Dt=Bs.map(({rule:t,label:e,unit:n,min:r,max:i})=>({rule:t,label:e,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Te(t){return Bs.map((e)=>Math.round(e.measure(t)*1000)/1000)}function Bh(t,e){return t.filter((n)=>!e.waive.includes(n.rule)).flatMap((n)=>n.check(e).map((r)=>({theme:e.name,rule:n.rule,detail:r})))}function yr(t){return Bh(Bs,t)}function zh(t){return Bh(_h,t)}function Kh(t){return t.flatMap(yr)}import{chmodSync as Rv,copyFileSync as Pv,existsSync as ri,mkdirSync as Hv,readFileSync as bu,realpathSync as Fv,renameSync as xv,rmSync as qh,statSync as Lv,writeFileSync as Tv}from"node:fs";import{dirname as Av}from"node:path";function Jh(t){return`${t}.ttheme.bak`}var Cv=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function wu(t){let e=Jh(t);if(ri(t)&&!ri(e)&&!Cv.test(bu(t,"utf8")))Pv(t,e)}function x(t,e){let n=ri(t)?Fv(t):t;Hv(Av(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(Tv(r,e),ri(n))Rv(r,Lv(n).mode&4095);xv(r,n)}function Ae(t,e){if((ri(t)?bu(t,"utf8"):void 0)===e)return!1;return wu(t),x(t,e),!0}function Yh(t,e){let n=Jh(t),r=ri(n)?bu(n,"utf8"):void 0;if(e===""&&r===void 0)return qh(t,{force:!0}),"removed";if(x(t,e),r===void 0||r===e)return qh(n,{force:!0}),"restored";return"kept backup"}import{createHash as op}from"node:crypto";import{copyFileSync as FM,existsSync as il,mkdirSync as xM,readdirSync as LM,readFileSync as bi,renameSync as sp,rmSync as pi,statSync as TM}from"node:fs";import{basename as ap,isAbsolute as AM,join as U}from"node:path";import{createHash as iM}from"node:crypto";import{existsSync as oM,readdirSync as sM,readFileSync as aM,rmSync as cM,statSync as uM,utimesSync as lM}from"node:fs";import{join as hi}from"node:path";import{readdirSync as fS,rmSync as dS,statSync as hS}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as mS}from"node:net";import{homedir as gS}from"node:os";import{join as co}from"node:path";import{setTimeout as pS}from"node:timers/promises";var zm=Yc(Um(),1);import{constants as nS,deflateSync as rS,inflateSync as iS}from"node:zlib";import{inflateRawSync as tS}from"node:zlib";var XE=(()=>{var t=import.meta.url;return function(e={}){var n=e,r,i,o=new Promise((h,p)=>{r=h,i=p});let a=globalThis.ServiceWorkerGlobalScope!==void 0&&typeof self<"u"&&globalThis.caches&&globalThis.caches.default!==void 0,c=typeof process==="object"&&process.release&&process.release.name==="node";if(a||c){if(!globalThis.ImageData)globalThis.ImageData=class{constructor(p,k,y){this.data=p,this.width=k,this.height=y}};if(import.meta.url===void 0)import.meta.url="https://localhost";if(typeof self<"u"&&self.location===void 0)self.location={href:""}}var u=Object.assign({},n),l=[],f="./this.program",d=(h,p)=>{throw p},m=typeof window=="object",g=typeof importScripts=="function",$=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",w="";function b(h){if(n.locateFile)return n.locateFile(h,w);return w+h}var v,R,S;if(m||g){if(g)w=self.location.href;else if(typeof document<"u"&&document.currentScript)w=document.currentScript.src;if(t)w=t;if(w.startsWith("blob:"))w="";else w=w.substr(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1);{if(v=(h)=>{var p=new XMLHttpRequest;return p.open("GET",h,!1),p.send(null),p.responseText},g)S=(h)=>{var p=new XMLHttpRequest;return p.open("GET",h,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)};R=(h,p,k)=>{var y=new XMLHttpRequest;y.open("GET",h,!0),y.responseType="arraybuffer",y.onload=()=>{if(y.status==200||y.status==0&&y.response){p(y.response);return}k()},y.onerror=k,y.send(null)}}}var I=n.print||console.log.bind(console),P=n.printErr||console.error.bind(console);if(Object.assign(n,u),u=null,n.arguments)l=n.arguments;if(n.thisProgram)f=n.thisProgram;if(n.quit)d=n.quit;var O;if(n.wasmBinary)O=n.wasmBinary;var F,j=!1,W,D,_,ge,z,ht,V,$n,qr;function Fe(){var h=F.buffer;n.HEAP8=D=new Int8Array(h),n.HEAP16=ge=new Int16Array(h),n.HEAPU8=_=new Uint8Array(h),n.HEAPU16=z=new Uint16Array(h),n.HEAP32=ht=new Int32Array(h),n.HEAPU32=V=new Uint32Array(h),n.HEAPF32=$n=new Float32Array(h),n.HEAPF64=qr=new Float64Array(h)}var dr=[],Ms=[],Is=[],Rk=!1;function Pk(){if(n.preRun){if(typeof n.preRun=="function")n.preRun=[n.preRun];while(n.preRun.length)xk(n.preRun.shift())}jc(dr)}function Hk(){Rk=!0,jc(Ms)}function Fk(){if(n.postRun){if(typeof n.postRun=="function")n.postRun=[n.postRun];while(n.postRun.length)Tk(n.postRun.shift())}jc(Is)}function xk(h){dr.unshift(h)}function Lk(h){Ms.unshift(h)}function Tk(h){Is.unshift(h)}var hr=0,Cc=null,Di=null;function Ak(h){hr++,n.monitorRunDependencies?.(hr)}function Ck(h){if(hr--,n.monitorRunDependencies?.(hr),hr==0){if(Cc!==null)clearInterval(Cc),Cc=null;if(Di){var p=Di;Di=null,p()}}}function Ad(h){n.onAbort?.(h),h="Aborted("+h+")",P(h),j=!0,W=1,h+=". Build with -sASSERTIONS for more info.";var p=new WebAssembly.RuntimeError(h);throw i(p),p}var jk="data:application/octet-stream;base64,",Cd=(h)=>h.startsWith(jk),mr;if(n.locateFile){if(mr="mozjpeg_dec.wasm",!Cd(mr))mr=b(mr)}else mr=new URL("mozjpeg_dec.wasm",import.meta.url).href;function jd(h){if(h==mr&&O)return new Uint8Array(O);if(S)return S(h);throw"both async and sync fetching of the wasm failed"}function Gk(h){if(!O&&(m||g)){if(typeof fetch=="function")return fetch(h,{credentials:"same-origin"}).then((p)=>{if(!p.ok)throw`failed to load wasm binary file at '${h}'`;return p.arrayBuffer()}).catch(()=>jd(h))}return Promise.resolve().then(()=>jd(h))}function Gd(h,p,k){return Gk(h).then((y)=>WebAssembly.instantiate(y,p)).then(k,(y)=>{P(`failed to asynchronously prepare wasm: ${y}`),Ad(y)})}function Uk(h,p,k,y){if(!h&&typeof WebAssembly.instantiateStreaming=="function"&&!Cd(p)&&typeof fetch=="function")return fetch(p,{credentials:"same-origin"}).then((M)=>{var N=WebAssembly.instantiateStreaming(M,k);return N.then(y,function(L){return P(`wasm streaming compile failed: ${L}`),P("falling back to ArrayBuffer instantiation"),Gd(p,k,y)})});return Gd(p,k,y)}function Wk(){var h={a:f1};function p(y,M){return Ct=y.exports,F=Ct.A,Fe(),Jd=Ct.F,Lk(Ct.B),Ck("wasm-instantiate"),Ct}Ak("wasm-instantiate");function k(y){p(y.instance)}if(n.instantiateWasm)try{return n.instantiateWasm(h,p)}catch(y){P(`Module.instantiateWasm callback failed with error: ${y}`),i(y)}return Uk(O,mr,h,k).catch(i),{}}function _k(h){this.name="ExitStatus",this.message=`Program terminated with exit(${h})`,this.status=h}var jc=(h)=>{while(h.length>0)h.shift()(n)},Bk=n.noExitRuntime||!0;class Ud{constructor(h){this.excPtr=h,this.ptr=h-24}set_type(h){V[this.ptr+4>>2]=h}get_type(){return V[this.ptr+4>>2]}set_destructor(h){V[this.ptr+8>>2]=h}get_destructor(){return V[this.ptr+8>>2]}set_caught(h){h=h?1:0,D[this.ptr+12]=h}get_caught(){return D[this.ptr+12]!=0}set_rethrown(h){h=h?1:0,D[this.ptr+13]=h}get_rethrown(){return D[this.ptr+13]!=0}init(h,p){this.set_adjusted_ptr(0),this.set_type(h),this.set_destructor(p)}set_adjusted_ptr(h){V[this.ptr+16>>2]=h}get_adjusted_ptr(){return V[this.ptr+16>>2]}get_exception_ptr(){var h=th(this.get_type());if(h)return V[this.excPtr>>2];var p=this.get_adjusted_ptr();if(p!==0)return p;return this.excPtr}}var Wd=0,zk=0,Kk=(h,p,k)=>{var y=new Ud(h);throw y.init(p,k),Wd=h,zk++,Wd},qk=(h,p,k,y,M)=>{},Jk=()=>{var h=Array(256);for(var p=0;p<256;++p)h[p]=String.fromCharCode(p);_d=h},_d,pe=(h)=>{var p="",k=h;while(_[k])p+=_d[_[k++]];return p},Jr={},gr={},Os={},Bd,qt=(h)=>{throw new Bd(h)},zd,Kd=(h)=>{throw new zd(h)},Yk=(h,p,k)=>{h.forEach(function(H){Os[H]=p});function y(H){var A=k(H);if(A.length!==h.length)Kd("Mismatched type converter count");for(var K=0;K<h.length;++K)Ze(h[K],A[K])}var M=Array(p.length),N=[],L=0;if(p.forEach((H,A)=>{if(gr.hasOwnProperty(H))M[A]=gr[H];else{if(N.push(H),!Jr.hasOwnProperty(H))Jr[H]=[];Jr[H].push(()=>{if(M[A]=gr[H],++L,L===N.length)y(M)})}}),N.length===0)y(M)};function Dk(h,p,k={}){var y=p.name;if(!h)qt(`type "${y}" must have a positive integer typeid pointer`);if(gr.hasOwnProperty(h))if(k.ignoreDuplicateRegistrations)return;else qt(`Cannot register type '${y}' twice`);if(gr[h]=p,delete Os[h],Jr.hasOwnProperty(h)){var M=Jr[h];delete Jr[h],M.forEach((N)=>N())}}function Ze(h,p,k={}){if(!("argPackAdvance"in p))throw TypeError("registerType registeredInstance requires argPackAdvance");return Dk(h,p,k)}var pr=8,Vk=(h,p,k,y)=>{p=pe(p),Ze(h,{name:p,fromWireType:function(M){return!!M},toWireType:function(M,N){return N?k:y},argPackAdvance:pr,readValueFromPointer:function(M){return this.fromWireType(_[M])},destructorFunction:null})},Gc=[],Qe=[],Uc=(h)=>{if(h>9&&--Qe[h+1]===0)Qe[h]=void 0,Gc.push(h)},Zk=()=>Qe.length/2-5-Gc.length,Qk=()=>{Qe.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=Zk},br={toValue:(h)=>{if(!h)qt("Cannot use deleted val. handle = "+h);return Qe[h]},toHandle:(h)=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let p=Gc.pop()||Qe.length;return Qe[p]=h,Qe[p+1]=1,p}}}};function Wc(h){return this.fromWireType(V[h>>2])}var Xk={name:"emscripten::val",fromWireType:(h)=>{var p=br.toValue(h);return Uc(h),p},toWireType:(h,p)=>br.toHandle(p),argPackAdvance:pr,readValueFromPointer:Wc,destructorFunction:null},ty=(h)=>Ze(h,Xk),ey=(h,p)=>{switch(p){case 4:return function(k){return this.fromWireType($n[k>>2])};case 8:return function(k){return this.fromWireType(qr[k>>3])};default:throw TypeError(`invalid float width (${p}): ${h}`)}},ny=(h,p,k)=>{p=pe(p),Ze(h,{name:p,fromWireType:(y)=>y,toWireType:(y,M)=>M,argPackAdvance:pr,readValueFromPointer:ey(p,k),destructorFunction:null})},_c=(h,p)=>Object.defineProperty(p,"name",{value:h}),qd=(h)=>{while(h.length){var p=h.pop(),k=h.pop();k(p)}};function ry(h){for(var p=1;p<h.length;++p)if(h[p]!==null&&h[p].destructorFunction===void 0)return!0;return!1}function iy(h,p,k,y,M,N){var L=p.length;if(L<2)qt("argTypes array size mismatch! Must at least get return value and 'this' types!");var H=p[1]!==null&&k!==null,A=ry(p),K=p[0].name!=="void",at=L-2,$t=Array(at),jt=[],ae=[],Yr=function(...qc){if(qc.length!==at)qt(`function ${h} called with ${qc.length} arguments, expected ${at}`);ae.length=0;var Jc;if(jt.length=H?2:1,jt[0]=M,H)Jc=p[1].toWireType(ae,this),jt[1]=Jc;for(var Dr=0;Dr<at;++Dr)$t[Dr]=p[Dr+2].toWireType(ae,qc[Dr]),jt.push($t[Dr]);var w1=y(...jt);function $1(k1){if(A)qd(ae);else for(var Vr=H?1:2;Vr<p.length;Vr++){var y1=Vr===1?Jc:$t[Vr-2];if(p[Vr].destructorFunction!==null)p[Vr].destructorFunction(y1)}if(K)return p[0].fromWireType(k1)}return $1(w1)};return _c(h,Yr)}var oy=(h,p,k)=>{if(h[p].overloadTable===void 0){var y=h[p];h[p]=function(...M){if(!h[p].overloadTable.hasOwnProperty(M.length))qt(`Function '${k}' called with an invalid number of arguments (${M.length}) - expects one of (${h[p].overloadTable})!`);return h[p].overloadTable[M.length].apply(this,M)},h[p].overloadTable=[],h[p].overloadTable[y.argCount]=y}},sy=(h,p,k)=>{if(n.hasOwnProperty(h)){if(k===void 0||n[h].overloadTable!==void 0&&n[h].overloadTable[k]!==void 0)qt(`Cannot register public name '${h}' twice`);if(oy(n,h,h),n.hasOwnProperty(k))qt(`Cannot register multiple overloads of a function with the same number of arguments (${k})!`);n[h].overloadTable[k]=p}else if(n[h]=p,k!==void 0)n[h].numArguments=k},ay=(h,p)=>{var k=[];for(var y=0;y<h;y++)k.push(V[p+y*4>>2]);return k},cy=(h,p,k)=>{if(!n.hasOwnProperty(h))Kd("Replacing nonexistent public symbol");if(n[h].overloadTable!==void 0&&k!==void 0)n[h].overloadTable[k]=p;else n[h]=p,n[h].argCount=k},uy=(h,p,k)=>{h=h.replace(/p/g,"i");var y=n["dynCall_"+h];return y(p,...k)},Ns=[],Jd,Yd=(h)=>{var p=Ns[h];if(!p){if(h>=Ns.length)Ns.length=h+1;Ns[h]=p=Jd.get(h)}return p},ly=(h,p,k=[])=>{if(h.includes("j"))return uy(h,p,k);var y=Yd(p)(...k);return y},fy=(h,p)=>(...k)=>ly(h,p,k),dy=(h,p)=>{h=pe(h);function k(){if(h.includes("j"))return fy(h,p);return Yd(p)}var y=k();if(typeof y!="function")qt(`unknown function pointer with signature ${h}: ${p}`);return y},hy=(h,p)=>{var k=_c(p,function(y){this.name=p,this.message=y;var M=Error(y).stack;if(M!==void 0)this.stack=this.toString()+`
83
+ `+M.replace(/^Error(:[^\n]*)?\n/,"")});return k.prototype=Object.create(h.prototype),k.prototype.constructor=k,k.prototype.toString=function(){if(this.message===void 0)return this.name;else return`${this.name}: ${this.message}`},k},Dd,Vd=(h)=>{var p=Xd(h),k=pe(p);return Xe(p),k},my=(h,p)=>{var k=[],y={};function M(N){if(y[N])return;if(gr[N])return;if(Os[N]){Os[N].forEach(M);return}k.push(N),y[N]=!0}throw p.forEach(M),new Dd(`${h}: `+k.map(Vd).join([", "]))},gy=(h)=>{h=h.trim();let p=h.indexOf("(");if(p!==-1)return h.substr(0,p);else return h},py=(h,p,k,y,M,N,L)=>{var H=ay(p,k);h=pe(h),h=gy(h),M=dy(y,M),sy(h,function(){my(`Cannot call ${h} due to unbound types`,H)},p-1),Yk([],H,(A)=>{var K=[A[0],null].concat(A.slice(1));return cy(h,iy(h,K,null,M,N,L),p-1),[]})},by=(h,p,k)=>{switch(p){case 1:return k?(y)=>D[y]:(y)=>_[y];case 2:return k?(y)=>ge[y>>1]:(y)=>z[y>>1];case 4:return k?(y)=>ht[y>>2]:(y)=>V[y>>2];default:throw TypeError(`invalid integer width (${p}): ${h}`)}},wy=(h,p,k,y,M)=>{if(p=pe(p),M===-1)M=4294967295;var N=(at)=>at;if(y===0){var L=32-8*k;N=(at)=>at<<L>>>L}var H=p.includes("unsigned"),A=(at,$t)=>{},K;if(H)K=function(at,$t){return A($t,this.name),$t>>>0};else K=function(at,$t){return A($t,this.name),$t};Ze(h,{name:p,fromWireType:N,toWireType:K,argPackAdvance:pr,readValueFromPointer:by(p,k,y!==0),destructorFunction:null})},$y=(h,p,k)=>{var y=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],M=y[p];function N(L){var H=V[L>>2],A=V[L+4>>2];return new M(D.buffer,A,H)}k=pe(k),Ze(h,{name:k,fromWireType:N,argPackAdvance:pr,readValueFromPointer:N},{ignoreDuplicateRegistrations:!0})},ky=(h,p,k,y)=>{if(!(y>0))return 0;var M=k,N=k+y-1;for(var L=0;L<h.length;++L){var H=h.charCodeAt(L);if(H>=55296&&H<=57343){var A=h.charCodeAt(++L);H=65536+((H&1023)<<10)|A&1023}if(H<=127){if(k>=N)break;p[k++]=H}else if(H<=2047){if(k+1>=N)break;p[k++]=192|H>>6,p[k++]=128|H&63}else if(H<=65535){if(k+2>=N)break;p[k++]=224|H>>12,p[k++]=128|H>>6&63,p[k++]=128|H&63}else{if(k+3>=N)break;p[k++]=240|H>>18,p[k++]=128|H>>12&63,p[k++]=128|H>>6&63,p[k++]=128|H&63}}return p[k]=0,k-M},yy=(h,p,k)=>ky(h,_,p,k),vy=(h)=>{var p=0;for(var k=0;k<h.length;++k){var y=h.charCodeAt(k);if(y<=127)p++;else if(y<=2047)p+=2;else if(y>=55296&&y<=57343)p+=4,++k;else p+=3}return p},Zd=(h,p,k)=>{var y=p+k,M="";while(!(p>=y)){var N=h[p++];if(!N)return M;if(!(N&128)){M+=String.fromCharCode(N);continue}var L=h[p++]&63;if((N&224)==192){M+=String.fromCharCode((N&31)<<6|L);continue}var H=h[p++]&63;if((N&240)==224)N=(N&15)<<12|L<<6|H;else N=(N&7)<<18|L<<12|H<<6|h[p++]&63;if(N<65536)M+=String.fromCharCode(N);else{var A=N-65536;M+=String.fromCharCode(55296|A>>10,56320|A&1023)}}return M},Ey=(h,p)=>h?Zd(_,h,p):"",Sy=(h,p)=>{p=pe(p);var k=p==="std::string";Ze(h,{name:p,fromWireType(y){var M=V[y>>2],N=y+4,L;if(k){var H=N;for(var A=0;A<=M;++A){var K=N+A;if(A==M||_[K]==0){var at=K-H,$t=Ey(H,at);if(L===void 0)L=$t;else L+=String.fromCharCode(0),L+=$t;H=K+1}}}else{var jt=Array(M);for(var A=0;A<M;++A)jt[A]=String.fromCharCode(_[N+A]);L=jt.join("")}return Xe(y),L},toWireType(y,M){if(M instanceof ArrayBuffer)M=new Uint8Array(M);var N,L=typeof M=="string";if(!(L||M instanceof Uint8Array||M instanceof Uint8ClampedArray||M instanceof Int8Array))qt("Cannot pass non-string to std::string");if(k&&L)N=vy(M);else N=M.length;var H=Kc(4+N+1),A=H+4;if(V[H>>2]=N,k&&L)yy(M,A,N+1);else if(L)for(var K=0;K<N;++K){var at=M.charCodeAt(K);if(at>255)Xe(A),qt("String has UTF-16 code units that do not fit in 8 bits");_[A+K]=at}else for(var K=0;K<N;++K)_[A+K]=M[K];if(y!==null)y.push(Xe,H);return H},argPackAdvance:pr,readValueFromPointer:Wc,destructorFunction(y){Xe(y)}})},My=(h,p)=>{var k="";for(var y=0;!(y>=p/2);++y){var M=ge[h+y*2>>1];if(M==0)break;k+=String.fromCharCode(M)}return k},Iy=(h,p,k)=>{if(k??=2147483647,k<2)return 0;k-=2;var y=p,M=k<h.length*2?k/2:h.length;for(var N=0;N<M;++N){var L=h.charCodeAt(N);ge[p>>1]=L,p+=2}return ge[p>>1]=0,p-y},Oy=(h)=>h.length*2,Ny=(h,p)=>{var k=0,y="";while(!(k>=p/4)){var M=ht[h+k*4>>2];if(M==0)break;if(++k,M>=65536){var N=M-65536;y+=String.fromCharCode(55296|N>>10,56320|N&1023)}else y+=String.fromCharCode(M)}return y},Ry=(h,p,k)=>{if(k??=2147483647,k<4)return 0;var y=p,M=y+k-4;for(var N=0;N<h.length;++N){var L=h.charCodeAt(N);if(L>=55296&&L<=57343){var H=h.charCodeAt(++N);L=65536+((L&1023)<<10)|H&1023}if(ht[p>>2]=L,p+=4,p+4>M)break}return ht[p>>2]=0,p-y},Py=(h)=>{var p=0;for(var k=0;k<h.length;++k){var y=h.charCodeAt(k);if(y>=55296&&y<=57343)++k;p+=4}return p},Hy=(h,p,k)=>{k=pe(k);var y,M,N,L;if(p===2)y=My,M=Iy,L=Oy,N=(H)=>z[H>>1];else if(p===4)y=Ny,M=Ry,L=Py,N=(H)=>V[H>>2];Ze(h,{name:k,fromWireType:(H)=>{var A=V[H>>2],K,at=H+4;for(var $t=0;$t<=A;++$t){var jt=H+4+$t*p;if($t==A||N(jt)==0){var ae=jt-at,Yr=y(at,ae);if(K===void 0)K=Yr;else K+=String.fromCharCode(0),K+=Yr;at=jt+p}}return Xe(H),K},toWireType:(H,A)=>{if(typeof A!="string")qt(`Cannot pass non-string to C++ string type ${k}`);var K=L(A),at=Kc(4+K+p);if(V[at>>2]=K/p,M(A,at+4,K+p),H!==null)H.push(Xe,at);return at},argPackAdvance:pr,readValueFromPointer:Wc,destructorFunction(H){Xe(H)}})},Fy=(h,p)=>{p=pe(p),Ze(h,{isVoid:!0,name:p,argPackAdvance:0,fromWireType:()=>{return},toWireType:(k,y)=>{return}})},xy=(h,p,k)=>_.copyWithin(h,p,p+k),Bc=[],Ly=(h,p,k,y)=>{return h=Bc[h],p=br.toValue(p),h(null,p,k,y)},Ty={},Ay=(h)=>{var p=Ty[h];if(p===void 0)return pe(h);return p},Qd=()=>{if(typeof globalThis=="object")return globalThis;function h(p){p.$$$embind_global$$$=p;var k=typeof $$$embind_global$$$=="object"&&p.$$$embind_global$$$==p;if(!k)delete p.$$$embind_global$$$;return k}if(typeof $$$embind_global$$$=="object")return $$$embind_global$$$;if(typeof global=="object"&&h(global))$$$embind_global$$$=global;else if(typeof self=="object"&&h(self))$$$embind_global$$$=self;if(typeof $$$embind_global$$$=="object")return $$$embind_global$$$;throw Error("unable to get global object.")},Cy=(h)=>{if(h===0)return br.toHandle(Qd());else return h=Ay(h),br.toHandle(Qd()[h])},jy=(h)=>{var p=Bc.length;return Bc.push(h),p},Gy=(h,p)=>{var k=gr[h];if(k===void 0)qt(`${p} has unknown type ${Vd(h)}`);return k},Uy=(h,p)=>{var k=Array(h);for(var y=0;y<h;++y)k[y]=Gy(V[p+y*4>>2],"parameter "+y);return k},Wy=Reflect.construct,_y=(h,p,k)=>{var y=[],M=h.toWireType(y,k);if(y.length)V[p>>2]=br.toHandle(y);return M},By=(h,p,k)=>{var y=Uy(h,p),M=y.shift();h--;var N=Array(h),L=(A,K,at,$t)=>{var jt=0;for(var ae=0;ae<h;++ae)N[ae]=y[ae].readValueFromPointer($t+jt),jt+=y[ae].argPackAdvance;var Yr=k===1?Wy(K,N):K.apply(A,N);return _y(M,at,Yr)},H=`methodCaller<(${y.map((A)=>A.name).join(", ")}) => ${M.name}>`;return jy(_c(H,L))},zy=(h)=>{if(h>9)Qe[h+1]+=1},Ky=(h)=>{var p=br.toValue(h);qd(p),Uc(h)},qy=()=>{Ad("")},Jy=()=>2147483648,Yy=(h)=>{var p=F.buffer,k=(h-p.byteLength+65535)/65536;try{return F.grow(k),Fe(),1}catch(y){}},Dy=(h)=>{var p=_.length;h>>>=0;var k=Jy();if(h>k)return!1;var y=(A,K)=>A+(K-A%K)%K;for(var M=1;M<=4;M*=2){var N=p*(1+0.2/M);N=Math.min(N,h+100663296);var L=Math.min(k,y(Math.max(h,N),65536)),H=Yy(L);if(H)return!0}return!1},zc={},Vy=()=>f||"./this.program",Vi=()=>{if(!Vi.strings){var h=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:h,_:Vy()};for(var k in zc)if(zc[k]===void 0)delete p[k];else p[k]=zc[k];var y=[];for(var k in p)y.push(`${k}=${p[k]}`);Vi.strings=y}return Vi.strings},Zy=(h,p)=>{for(var k=0;k<h.length;++k)D[p++]=h.charCodeAt(k);D[p]=0},Qy=(h,p)=>{var k=0;return Vi().forEach((y,M)=>{var N=p+k;V[h+M*4>>2]=N,Zy(y,N),k+=y.length+1}),0},Xy=(h,p)=>{var k=Vi();V[h>>2]=k.length;var y=0;return k.forEach((M)=>y+=M.length+1),V[p>>2]=y,0},t1=0,e1=()=>Bk||t1>0,n1=(h)=>{if(W=h,!e1())n.onExit?.(h),j=!0;d(h,new _k(h))},r1=(h,p)=>{W=h,n1(h)},i1=r1,o1=(h)=>52,s1=(h,p)=>p+2097152>>>0<4194305-!!h?(h>>>0)+p*4294967296:NaN;function a1(h,p,k,y,M){var N=s1(p,k);return 70}var c1=[null,[],[]],u1=(h,p)=>{var k=c1[h];if(p===0||p===10)(h===1?I:P)(Zd(k,0)),k.length=0;else k.push(p)},l1=(h,p,k,y)=>{var M=0;for(var N=0;N<k;N++){var L=V[p>>2],H=V[p+4>>2];p+=8;for(var A=0;A<H;A++)u1(h,_[L+A]);M+=H}return V[y>>2]=M,0};Jk(),Bd=n.BindingError=class extends Error{constructor(p){super(p);this.name="BindingError"}},zd=n.InternalError=class extends Error{constructor(p){super(p);this.name="InternalError"}},Qk(),Dd=n.UnboundTypeError=hy(Error,"UnboundTypeError");var f1={o:Kk,q:qk,m:Vk,l:ty,j:ny,f:py,b:wy,a:$y,e:Sy,c:Hy,n:Fy,v:xy,i:Ly,d:Uc,k:Cy,h:By,y:zy,g:Ky,r:qy,s:Dy,t:Qy,u:Xy,z:i1,w:o1,p:a1,x:l1},Ct=Wk(),d1=()=>(d1=Ct.B)(),Xd=(h)=>(Xd=Ct.C)(h),Kc=(h)=>(Kc=Ct.D)(h),Xe=(h)=>(Xe=Ct.E)(h),h1=(h)=>(h1=Ct._emscripten_stack_restore)(h),m1=(h)=>(m1=Ct._emscripten_stack_alloc)(h),g1=()=>(g1=Ct.emscripten_stack_get_current)(),p1=(h)=>(p1=Ct.__cxa_increment_exception_refcount)(h),th=(h)=>(th=Ct.G)(h),b1=n.dynCall_jiji=(h,p,k,y,M)=>(b1=n.dynCall_jiji=Ct.H)(h,p,k,y,M),Rs;Di=function h(){if(!Rs)eh();if(!Rs)Di=h};function eh(){if(hr>0)return;if(Pk(),hr>0)return;function h(){if(Rs)return;if(Rs=!0,n.calledRun=!0,j)return;if(Hk(),r(n),n.onRuntimeInitialized)n.onRuntimeInitialized();Fk()}if(n.setStatus)n.setStatus("Running..."),setTimeout(function(){setTimeout(function(){n.setStatus("")},1),h()},1);else h()}if(n.preInit){if(typeof n.preInit=="function")n.preInit=[n.preInit];while(n.preInit.length>0)n.preInit.pop()()}return eh(),o}})(),Wm=XE;function xu(t){if(t[0]!==255||t[1]!==216)return null;let e=2;while(e+9<t.length){if(t[e]!==255){e++;continue}let n=t[e+1];if(n===255){e++;continue}let r=t[e+2]<<8|t[e+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:t[e+5]<<8|t[e+6],width:t[e+7]<<8|t[e+8]};e+=2+r}return null}var Fu;function eS(){if(Fu)return Fu;let t=new WebAssembly.Module(tS(Buffer.from("7L0NnFzHVSd6q+5H3+7bPdMjjeyRZmTf7ohFITZWgpFN4mBdEX3Y8leI15jfy+6a3UC8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/NUIrxMfVWkkWEa+T/R2blz56rElx5TZp39peuXeB6eviakhOdMIpdMM1WkiQGa6H/is/8ImFkqcTeeZxAZZlqsIrMYZhb/7+hcvEQm08Rqmo1waIRifVQlbntcmWGHB0s8i8/bo5gwxjFhjGNSGA8K6z0OQj8eFpZ7HBPJONp2HE0xjuYbJ9Yf1R9HtcdRxXHUaxxNNo4Cjs+UZcE4Cj6OThlHb4yjguOYSMYxYYxjQhjHJDAOIj+O8t6Hyeso8j+K/I8i/6PI/yjyP4r8jyL/o8j/KPI/ivyPIv+jyP8p5H8U+R9Fz3wdR9AQP4b4McSP/biazzypX4Wj0R5yqiPe0DijaSYzKPPmv+PU06zmltNPLvy/+Yf6BGqMkB446onyn6uLP/v3Z14+sr3++PHzzyDGIA13DI0ex0x76GqfWrW6Xl1+80Glnns9OFtPvHvh9iC5x946fvyTDx4/jgG8a1dqbCzZn93XCbnIrtJgdngXqZnsggpVgei8WolZ/BpwBO2LeMC74JfjPYc9Om8Egj8C+HvOnAR+hERoE+GPTQp/DuALvEPojkHws8GNxM6StrgOz4/heTXcx2ntBvcJVZXWYsx3A9hESPL2Za46vfRZkv8+xNuG94Nw/fr9LriUfr8XblC/PwCX1O+PwJX0+9NwZf3+LFxWv78EN6Tf34TL6fcAiOSwfo/jfUy/z8f7Af3ehvcB/b60Xfqa3le1V9cT76XsZN3C9dxEEy7q2Vc+p7LHrH/3I+wjeF4L98eKYDo7c4Xd4A9k+5zi3wWY9y8S+GMa/roK/GLZgNURdJ5Pt0va9KO8qa/+xNVX18P9KdwNcDdyOuc4BVea0Ziv8yy3S/xPVsX/FNxNcJ/W8Jfr/KisN+N5CxxGgroV7jNwf6YS1/xYmZHxJbIACoKO4tt3uUrcj2f0CvhdCXfXEhx7owAsIp/5sYfQHnoG3lf9Bw==","base64"))),e={noInitialRun:!0,print:()=>{return},printErr:()=>{return},instantiateWasm:(n,r)=>{let i=new WebAssembly.Instance(t,n);return r(i),i.exports}};if(Wm(e),typeof e.decode!=="function")throw Error("the JPEG decoder did not start");return Fu=e,e}function _m(t,e){let n=xu(t);if(n&&n.width*n.height>e)throw Error(`${n.width}×${n.height} is over ${e/1e6} megapixels`);let r=null;try{r=eS().decode(t,!0)}catch{r=null}if(!r)throw Error("not a JPEG image this decoder can read");return{width:r.width,height:r.height,data:new Uint8Array(r.data.buffer,r.data.byteOffset,r.data.length)}}var ai=[137,80,78,71,13,10,26,10],Km=13,qm=3;function Er(t){return t.length>=ai.length&&ai.every((e,n)=>t[n]===e)}var Jm={0:1,2:3,4:2,6:4};function oS(t){if(t.length<33||!Er(t))return;let e=Buffer.from(t.buffer,t.byteOffset,t.byteLength),n=e.readUInt32BE(16),r=e.readUInt32BE(20),i=e[25];if(e[24]!==8||e[28]!==0||Jm[i]===void 0)return;let o=[];for(let s=8;s+12<=e.length;){let a=e.readUInt32BE(s),c=e.toString("latin1",s+4,s+8);if(c==="IDAT")o.push(e.subarray(s+8,s+8+a));else if(c==="tRNS"||c==="IEND"){if(c==="tRNS"&&i!==4&&i!==6)return;break}s+=12+a}return o.length>0?{width:n,height:r,type:i,idat:o}:void 0}function sS(t,e,n,r){let i=new Uint8Array(e);for(let o=0;o<n;o++){let s=o*(e+1),a=t[s],c=s+1,u=o>0?t:i,l=o>0?c-e-1:0;if(a===1)for(let f=r;f<e;f++)t[c+f]=t[c+f]+t[c+f-r];else if(a===2)for(let f=0;f<e;f++)t[c+f]=t[c+f]+u[l+f];else if(a===3){for(let f=0;f<r;f++)t[c+f]=t[c+f]+(u[l+f]>>1);for(let f=r;f<e;f++)t[c+f]=t[c+f]+(t[c+f-r]+u[l+f]>>1)}else if(a===4){for(let f=0;f<r;f++)t[c+f]=t[c+f]+u[l+f];for(let f=r;f<e;f++){let d=t[c+f-r],m=u[l+f],g=u[l+f-r],$=Math.abs(m-g),w=Math.abs(d-g),b=Math.abs(d+m-2*g);t[c+f]=t[c+f]+($<=w&&$<=b?d:w<=b?m:g)}}else if(a!==0)throw Error(`bad PNG filter ${a}`)}}function aS(t){let{width:e,height:n,type:r}=t,i=Jm[r],o=e*i,s=iS(Buffer.concat(t.idat),{chunkSize:Math.min(268435456,Math.max(65536,n*(o+1)))});if(s.length<n*(o+1))throw Error("truncated PNG");sS(s,o,n,i);let a=new Uint8Array(e*n*4);for(let c=0;c<n;c++){let u=c*(o+1)+1,l=c*e*4;if(r===6)a.set(s.subarray(u,u+o),l);else if(r===2)for(let f=0,d=u,m=l;f<e;f++,d+=3,m+=4)a[m]=s[d],a[m+1]=s[d+1],a[m+2]=s[d+2],a[m+3]=255;else if(r===0)for(let f=0,d=l;f<e;f++,d+=4){let m=s[u+f];a[d]=m,a[d+1]=m,a[d+2]=m,a[d+3]=255}else for(let f=0,d=u,m=l;f<e;f++,d+=2,m+=4){let g=s[d];a[m]=g,a[m+1]=g,a[m+2]=g,a[m+3]=s[d+1]}}return{width:e,height:n,data:a}}function le(t){let e=oS(t);if(e)return aS(e);let n=zm.PNG.sync.read(Buffer.from(t));return{width:n.width,height:n.height,data:new Uint8Array(n.data)}}function Rn(t,e){if(Er(t)){let n=Pn(t);if(n&&n.width*n.height>e)throw Error(`${n.width}×${n.height} is over ${e/1e6} megapixels`);return le(t)}if(t[0]===255&&t[1]===216)return _m(t,e);throw Error("not a PNG or JPEG image")}function Ym(t,e){let{width:n,height:r,at:i}=e,o=Math.max(0,i.x),s=Math.max(0,i.y),a=Math.min(n,i.x+i.w),c=Math.min(r,i.y+i.h);if(a<=o||c<=s)return;let u={x:o,y:s,w:a-o,h:c-s};if(i.w===t.width&&i.h===t.height)return{part:t,box:u,dx:o-i.x,dy:s-i.y};let l={x:(o-i.x)*t.width/i.w,y:(s-i.y)*t.height/i.h,w:u.w*t.width/i.w,h:u.h*t.height/i.h};return{part:no(t,l,u.w,u.h),box:u,dx:0,dy:0}}function Dm(t,e){let n=new Uint8Array(e.width*e.height*4),r=Ym(t,e);if(r){let{part:i,box:o,dx:s,dy:a}=r;for(let c=0;c<o.h;c++){let u=((c+a)*i.width+s)*4;n.set(i.data.subarray(u,u+o.w*4),((o.y+c)*e.width+o.x)*4)}}return{width:e.width,height:e.height,data:n}}function zs(t,e,n,r={width:t.width,height:t.height,at:{x:0,y:0,w:t.width,h:t.height}}){let i=nt(e),{width:o,height:s}=r,a=new Uint8Array(o*s*3);for(let m=0;m<o*3;m+=3)a.set(i,m);for(let m=1;m<s;m++)a.copyWithin(m*o*3,0,o*3);let c=Ym(t,r);if(!c)return{width:o,height:s,data:a};let{part:u,box:l,dx:f,dy:d}=c;for(let m=0;m<l.h;m++)for(let g=0;g<l.w;g++){let $=((m+d)*u.width+g+f)*4,w=((l.y+m)*o+l.x+g)*3,b=u.data[$+3]/255*n;for(let v=0;v<3;v++)a[w+v]=Math.round(i[v]*(1-b)+u.data[$+v]*b)}return{width:o,height:s,data:a}}function Bm(t,e){for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let i=0;i<e.length&&r;i++)r=t[n+i]===e.charCodeAt(i);if(r)return n}return-1}function Pn(t){if(t.length<33||!Er(t))return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint32(16),r=e.getUint32(20);if(t[25]===4||t[25]===6)return{width:n,height:r,alpha:!0};let i=Bm(t,"IDAT");return{width:n,height:r,alpha:Bm(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function Vm(t,e=Km){let{width:n,height:r,data:i}=t,o=(l)=>{for(let f=l*n*4+3,d=f+n*4;f<d;f+=4)if(i[f]>=e)return!0;return!1},s=0;while(s<r&&!o(s))s++;if(s===r)return null;let a=r-1;while(!o(a))a--;let c=n,u=-1;for(let l=s;l<=a;l++){let f=l*n*4+3;for(let d=0;d<c;d++)if(i[f+d*4]>=e){c=d;break}for(let d=n-1;d>u;d--)if(i[f+d*4]>=e){u=d;break}}return{x:c,y:s,w:u-c+1,h:a-s+1}}function sn(t,e={x:0,y:0,w:t.width,h:t.height}){let n=0;for(let r=e.y;r<e.y+e.h;r++)for(let i=e.x;i<e.x+e.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<Km)n++;return Math.round(n*100/(e.w*e.h))}function Zm(t,e,n){let r=Math.min(e/t.width,n/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=no(t,{x:0,y:0,w:t.width,h:t.height},i,o),a=new Uint8Array(e*n*4),c=Math.floor((e-i)/2),u=Math.floor((n-o)/2);for(let l=0;l<o;l++)a.set(s.data.subarray(l*i*4,(l+1)*i*4),((u+l)*e+c)*4);return{width:e,height:n,data:a}}function cS(t){let e=Math.abs(t);if(e<1)return(7*e*e*e-12*e*e+5.333333333333333)/6;if(e<2)return(-2.3333333333333335*e*e*e+12*e*e-20*e+10.666666666666666)/6;return 0}function Lu(t,e,n,r){if(n===r&&Number.isInteger(e)&&e>=0&&e+r<=t)return{first:Int32Array.from({length:r},(l,f)=>e+f),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,o=Math.max(1,i),s=2*o,a=Math.min(t,Math.ceil(2*s)+2),c=new Int32Array(r),u=new Float32Array(r*a);for(let l=0;l<r;l++){let f=e+(l+0.5)*i,d=Math.floor(f-s-0.5),m=Math.max(0,Math.min(t-a,d));c[l]=m;let g=0;for(let $=d;$<=Math.ceil(f+s-0.5);$++){let w=cS(($+0.5-f)/o),b=l*a+Math.min(t-1,Math.max(0,$))-m;u[b]=(u[b]??0)+w,g+=w}for(let $=l*a;$<(l+1)*a;$++)u[$]=(u[$]??0)/g}return{first:c,size:a,weights:u}}function Qm(t,e,n,r,i,o,s){let a=Lu(t,e.y,e.h,r),c=n*i,u=a.size+1,l=Array.from({length:u},()=>new Float32Array(c)),f=new Int32Array(u).fill(-1),d=new Float32Array(c),m=[],g=[];for(let $=0;$<r;$++){m.length=0,g.length=0;let w=a.first[$];for(let v=0;v<a.size;v++){let R=a.weights[$*a.size+v];if(R===0)continue;let S=w+v,I=S%u,P=l[I];if(f[I]!==S)o(S,P),f[I]=S;m.push(P),g.push(R)}let b=0;while(b<m.length){let v=m[b],R=g[b];if(m.length-b>=4){let S=m[b+1],I=m[b+2],P=m[b+3],O=g[b+1],F=g[b+2],j=g[b+3];if(b===0)for(let W=0;W<c;W++)d[W]=v[W]*R+S[W]*O+I[W]*F+P[W]*j;else for(let W=0;W<c;W++)d[W]=d[W]+(v[W]*R+S[W]*O+I[W]*F+P[W]*j);b+=4}else{if(b===0)for(let S=0;S<c;S++)d[S]=v[S]*R;else for(let S=0;S<c;S++)d[S]=d[S]+v[S]*R;b+=1}}if(m.length===0)d.fill(0);s($,d)}}function Xm(t,e,n,r,i){let o=0,s=n;while(o<s){let c=o+s>>1;if(t[c]+e-1<r)o=c+1;else s=c}let a=o;s=n;while(o<s){let c=o+s>>1;if(t[c]<=i)o=c+1;else s=c}return[a,o]}function no(t,e,n,r){let i=Lu(t.width,e.x,e.w,n),o=t.data,s=t.width,a=new Float32Array(s*4),c=new Uint8Array(n*r*4);return Qm(t.height,e,n,r,4,(u,l)=>{let f=u*s*4,d=s,m=-1;for(let w=0,b=0;w<s*4;w+=4,b++){let v=o[f+w+3];if(v===0){a[w]=0,a[w+1]=0,a[w+2]=0,a[w+3]=0;continue}if(b<d)d=b;m=b,a[w]=o[f+w]*v,a[w+1]=o[f+w+1]*v,a[w+2]=o[f+w+2]*v,a[w+3]=v}if(l.fill(0),m<0)return;let[g,$]=Xm(i.first,i.size,n,d,m);for(let w=g;w<$;w++){let b=i.first[w]*4,v=w*i.size,R=0,S=0,I=0,P=0;for(let O=0;O<i.size;O++){let F=i.weights[v+O],j=b+O*4;R+=a[j]*F,S+=a[j+1]*F,I+=a[j+2]*F,P+=a[j+3]*F}l[w*4]=R,l[w*4+1]=S,l[w*4+2]=I,l[w*4+3]=P}},(u,l)=>{let f=u*n*4;for(let d=0;d<n;d++){let m=d*4,g=l[m+3];if(g<=0)continue;let $=l[m]/g;c[f+m]=($<0?0:$>255?255:$)+0.5,$=l[m+1]/g,c[f+m+1]=($<0?0:$>255?255:$)+0.5,$=l[m+2]/g,c[f+m+2]=($<0?0:$>255?255:$)+0.5,c[f+m+3]=(g>255?255:g)+0.5}}),{width:n,height:r,data:c}}function tg(t,e,n,r){let i=Lu(t.width,e.x,e.w,n),o=t.data,s=t.width,a=new Float32Array(n*r);return Qm(t.height,e,n,r,1,(c,u)=>{let l=c*s,f=s,d=-1;for(let $=0;$<s;$++)if(o[l+$]!==0){if($<f)f=$;d=$}if(u.fill(0),d<0)return;let[m,g]=Xm(i.first,i.size,n,f,d);for(let $=m;$<g;$++){let w=l+i.first[$],b=$*i.size,v=0;for(let R=0;R<i.size;R++)v+=o[w+R]*i.weights[b+R];u[$]=v}},(c,u)=>{a.set(u,c*n)}),{width:n,height:r,data:a}}function ro(t,e){if(e<=0)return t;let n=Math.max(1,Math.ceil(e*3)),r=Array.from({length:2*n+1},(l,f)=>Math.exp(-((f-n)**2)/(2*e*e))),i=r.reduce((l,f)=>l+f,0),{width:o,height:s,data:a}=t,c=new Float32Array(o*s);for(let l=0;l<s;l++){let f=l*o;for(let d=0;d<o;d++){let m=0;for(let g=-n;g<=n;g++)m+=(a[f+Math.min(o-1,Math.max(0,d+g))]??0)*(r[g+n]??0);c[f+d]=m/i}}let u=new Float32Array(o*s);for(let l=0;l<s;l++){let f=l*o;for(let d=-n;d<=n;d++){let m=(r[d+n]??0)/i,g=Math.min(s-1,Math.max(0,l+d))*o;for(let $=0;$<o;$++)u[f+$]=(u[f+$]??0)+(c[g+$]??0)*m}}return{width:o,height:s,data:u}}function io(t){let e=new Uint8Array(t.data.length);for(let n=0;n<e.length;n++){let r=t.data[n];e[n]=(r<0?0:r>255?255:r)+0.5}return{width:t.width,height:t.height,data:e}}function oo(t){let e=new Uint8Array(t.width*t.height);for(let n=0;n<e.length;n++)e[n]=t.data[n*4+3]??0;return{width:t.width,height:t.height,data:e}}var uS=Array.from({length:256},(t,e)=>{let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function lS(t){let e=4294967295;for(let n of t)e=(uS[(e^n)&255]??0)^e>>>8;return(e^4294967295)>>>0}function Nn(t,e){let n=Buffer.alloc(12+e.length);return n.writeUInt32BE(e.length,0),n.write(t,4,"latin1"),n.set(e,8),n.writeUInt32BE(lS(n.subarray(4,8+e.length)),8+e.length),n}function eg(t,e,n){let r=new Uint8Array(n*(e+1));r.set(t.subarray(0,e),1);for(let i=1;i<n;i++){let o=i*(e+1),s=i*e,a=s-e;r[o]=2;for(let c=0;c<e;c++)r[o+1+c]=t[s+c]-t[a+c]}return r}function ng(t){return rS(t,{level:1,strategy:nS.Z_RLE})}function rg(t,e,n){let r=Buffer.alloc(13);return r.writeUInt32BE(t.width,0),r.writeUInt32BE(t.height,4),r[8]=8,r[9]=e,Buffer.concat([Buffer.from(ai),Nn("IHDR",r),...n,Nn("IDAT",ng(eg(t.data,t.width,t.height))),Nn("IEND",new Uint8Array)])}function ig(t){let[e,n,r]=nt(t),i=new Uint8Array(768);for(let o=0;o<256;o++)i.set([e,n,r],o*3);return Nn("PLTE",i)}function og(t,e,n,r,i){let o=Buffer.alloc(13);return o.writeUInt32BE(t,0),o.writeUInt32BE(e,4),o[8]=8,o[9]=n,Buffer.concat([Buffer.from(ai),Nn("IHDR",o),Nn("IDAT",ng(eg(i,t*r,e))),Nn("IEND",new Uint8Array)])}function Ks(t){return og(t.width,t.height,2,3,t.data)}function je(t){return og(t.width,t.height,6,4,t.data)}function so(t,e){return rg(t,qm,[ig(e),Nn("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function Tu(t){return rg(t,0,[])}function sg(t,e){if(!Er(t)||t[25]!==qm)return;let n=Buffer.from(t.buffer,t.byteOffset,t.byteLength),r=[Buffer.from(ai)],i=ai.length;while(i+8<=n.length){let o=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?ig(e):n.subarray(i,o)),i=o}return Buffer.concat(r)}var Hn=100,Vt=25000000,bS=536870912,ci=["safe","questionable","explicit"],Sr=["nudity","underwear"],Gu=["comic","monochrome","sketch","chibi"],gg=["off","5","10","25","50","100"],pg=["off","720","1080","1440","1800","2560"],bg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},wS={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},$S=/^(?:rating|score|width|height|filetype|dimension):/,ao={safe:"s",questionable:"q",explicit:"e"},wg=8191,kS=20000,yS=5000,ag=3000,cg=8,vS=8,ES=8000,SS=3000,$g=60000,ug=3,MS=3,IS="https://static.zerochan.net",kg="https://s1.zerochan.net",Uu=`ttheme/${Ot.version} (+${Ot.homepage})`,OS=["orig","tile","thumb","cut"],yg=new Map,NS=KS(process.env.TTHEME_FIND_HOSTS),RS=zS(process.env.TTHEME_FIND_CUTOUTS);mS(SS);var PS=["artist","character","copyright"];function lg(t){try{return fS(t)}catch{return[]}}function ui(t){return t.startsWith("//")?`https:${t}`:t}function xn(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function uo(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function HS(t){let e=t.trim(),r=(e?JSON.parse(e):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function Cu(t,e,n){let r=ui(String(t??""));return{file:r,width:Number(e)||0,height:Number(n)||0,ext:xn(r)}}function an(t){return String(t??"").split(/\s+/).filter(Boolean)}function ju(t){let e=typeof t==="number"?new Date(t*1000):typeof t==="string"?new Date(t):void 0;return e&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):void 0}function vg(t,e){let n=ui(String(e.preview??""));if(!e.file||!n||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:e.file,preview:n,ext:e.ext,owner:String(e.owner??""),score:Number(t.score)||0,rating:String(t.rating??""),md5:String(e.md5??""),source:String(t.source??""),tags:an(e.tags),named:e.named,...ju(t.created_at)?{posted:ju(t.created_at)}:{},solo:e.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:e.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function FS(t){let e=HS(t);return uo(t).flatMap((n)=>{let r=ui(String(n.file_url??"")),i=String(n.tags??""),o=(s)=>an(i).filter((a)=>e.get(a)===s);return vg(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||xn(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:o("artist"),character:o("character"),copyright:o("copyright")},solo:void 0,versions:[Cu(n.jpeg_url,n.jpeg_width,n.jpeg_height),Cu(n.sample_url,n.sample_width,n.sample_height)]})})}function xS(t){return uo(t).flatMap((e)=>{let n=ui(String(e.file_url??"")),r=String(e.tag_string??""),i=e.media_asset??{};return vg(e,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??e.preview_file_url,file:n,ext:String(e.file_ext||xn(n)).toLowerCase(),owner:"",md5:e.md5,tags:r,named:{artist:an(e.tag_string_artist),character:an(e.tag_string_character),copyright:an(e.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>Cu(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function Eg(t){return t.toLowerCase().replace(/\s+/g,"_")}function LS(t){return(Array.isArray(t)?t:[]).map((e)=>Eg(String(e)))}function TS(t){return String(t??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function AS(t){let e=t.trim(),n=e?JSON.parse(e):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let o=Number(i.id);if(!o)return[];let s=LS(i.tags),a=ui(String(i.full??""));return[{id:o,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:xn(a),preview:`${kg}/${TS(i.tag??i.primary)}.600.${o}.jpg`,owner:"",score:0,rating:s.some((c)=>bg.nudity.has(c))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:s,named:{artist:[],character:[],copyright:[]},solo:s.includes("solo"),family:0,smaller:[]}]})}var CS={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function fg(t){return t.replace(/&(?:#(\d+)|amp|quot|apos|lt|gt);/g,(e,n)=>n?String.fromCharCode(Number(n)):{"&amp;":"&","&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">"}[e]??e)}function jS(t){let e={artist:[],character:[],copyright:[]};for(let[,r,i]of t.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let o=CS[r],s=Eg(fg(i));if(o&&!e[o].includes(s))e[o].push(s)}let n=ju(/"datePublished":\s*"([^"]+)"/.exec(t)?.[1]);return{named:e,source:"",owner:fg(/\buploader = \{\s*name: '([^']*)'/.exec(t)?.[1]??""),...n?{posted:n}:{}}}function GS(t){return Number(/Zerochan has ([\d,]+) /.exec(t)?.[1]?.replace(/,/g,"")??0)}function US(t){return uo(t).flatMap((e)=>{let n=String(e.value??"");return n?[{value:n,count:Number(e.post_count)||0}]:[]})}function WS(t){return uo(t).flatMap((e)=>{let n=String(e.name??"");return n?[{value:n,count:Number(e.count)||0}]:[]})}function _S(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function BS(t){let n=(t.trim()?JSON.parse(t):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function zS(t){let e=new Map;for(let n of(t??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)e.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return e}function KS(t){let e=new Map;for(let n of(t??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let o=new URL(n.slice(r+1));if(i&&o.protocol==="https:")e.set(i,o.origin)}catch{}}return e}function qs(t,e,n,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=e.filter((s)=>i.includes(s));return o.length>0?o:[...n]}function Mr(t){return qs(t,ci,["safe"])}function li(t){return qs(t,Sr,Sr,"none")}function Js(t){return qs(t,Gu,[],"none")}function lo(t){let e=q.map((n)=>n.name);return qs(t,e,e)}function Wu(t,e,n){return{score:Number(t)||0,size:Number(e)||0,png:n==="on"}}function fo(t){return[...new Set((t??"").toLowerCase().split(/[\s,]+/).map((e)=>e.replace(/^-+/,"")).filter(Boolean))]}function _u(t,e,n){return{safe:new Set(t),questionable:new Set(e),explicit:new Set(n)}}function Bu(t){let e=NS.get(t.key),n=RS.get(t.key);return{...t,origin:e??t.origin,moved:e!==void 0&&e!==t.origin,cutouts:n??t.cutouts,vouched:t.vouched&&n===void 0}}function Sg(t){return t.length<2?t.join(""):t.map((e)=>`~${e}`).join(" ")}function Mg(t){return t>0?[`width:>=${t}`,`height:>=${t}`]:[]}function dg(t){let e=Bu(t),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...e,scored:!0,narrow:({score:r,size:i})=>[...r>0?[`score:>=${r}`]:[],...Mg(i)],cutouts:Sg(e.cutouts),ratings:_u([ao.safe],[ao.questionable],[ao.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ao[i]}`;let o=ci.filter((a)=>!r.includes(a)),[s]=o;return o.length===1&&s?`-rating:${ao[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,ors:!0,postsUrl:(r,i)=>`${e.origin}/post.json?${n({limit:String(Hn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${e.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/post/show/${r}`,parse:FS,count:_S,uploadedBy:(r)=>`user:${r}`}}function qS(t){let e=Bu(t),n=_u(["g"],["s","q"],["e"]);return{...e,scored:!0,narrow:({score:r,size:i,png:o})=>[...r>0?[`score:>=${r}`]:[],...Mg(i),...o?["filetype:png"]:[]],cutouts:Sg(e.cutouts),ratings:n,rate:(r)=>r.length===ci.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,ors:!0,postsUrl:(r,i)=>`${e.origin}/posts.json?${new URLSearchParams({limit:String(Hn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${e.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/posts/${r}`,parse:xS,count:BS,uploadedBy:(r)=>`user:${r}`}}function Au(t){return t.split(/\s+/).filter((e)=>e&&!/^(?:order|dimension):/.test(e)).map((e)=>e.split("_").map(encodeURIComponent).join("+")).join(",")}function hg(t){let e=t.split(/\s+/),n=e.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:e.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function JS(t){let e=Bu(t);return{...e,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:e.cutouts[0]??"",ratings:_u(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,ors:!1,missing:404,postsUrl:(n,r)=>`${e.origin}/${Au(n)}?${new URLSearchParams({json:"",l:String(Hn),p:String(r+1),...hg(n)})}`,countUrl:(n)=>`${e.origin}/${Au(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${e.origin}/${n}?json=`,pageUrl:(n)=>`${e.origin}/${n}`,parse:AS,count:GS,credits:jS,counts:(n)=>Au(n).split(",").length===1&&!("d"in hg(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(kg,IS).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function YS(t){let e=mg(`https://${t}`);return q.find((n)=>mg(n.origin)===e)}function zu(t){return t.split(/\s+/).filter((e)=>e&&!$S.test(e)).length}function Ys(t,e){let n=t.trim();if(/^\d+$/.test(n))return{site:e,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=q.find((c)=>c.key===r[1]||c.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let o=YS(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var q=[qS({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),dg({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),dg({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),JS({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ut=q.find((t)=>t.key==="danbooru"),Ln=134217728;function Zt(t,e){let n=q.indexOf(t);return(n===-1?q.length:n)*Ln+e}function mg(t){let e;try{e=new URL(t).hostname}catch{return""}return e.split(".").slice(-2).join(".")}function Ir(t,e,n=e){return e.mirror&&n===e?{site:Ut,url:e.mirror.file}:{site:t,url:n.file}}function Ds(t,e){return e.mirror?{site:Ut,url:e.mirror.preview}:{site:t,url:e.preview}}function Vs(t,e=Sr){return t.tags.filter((n)=>e.some((r)=>bg[r].has(n)))}function Ig(t,e){return t.tags.filter((n)=>e.some((r)=>wS[r].has(n)))}function Zs(t,e,n=["safe"]){return n.some((r)=>t.ratings[r].has(e.rating))}function Og(t,e){return t.rate(["safe"])===""?void 0:ci.find((n)=>t.ratings[n].has(e.rating))}function Ge(t){return[t,...t.smaller].find((e)=>e.width*e.height<=Vt)}function Ng(t){let e=new Map;for(let[n,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;e.set(r,[...e.get(r)??[],n])}return e}function Tn(){return co(process.env.XDG_CACHE_HOME??co(gS(),".cache"),"ttheme")}function ke(t){return co(Tn(),t.key)}function Rg(t=bS,e=Tn()){let n=[],r=0;for(let i of lg(e))for(let o of OS){let s=co(e,i,o);for(let a of lg(s)){let c=co(s,a);try{let{size:u,mtimeMs:l}=hS(c);n.push({path:c,size:u,at:l}),r+=u}catch{}}}n.sort((i,o)=>i.at-o.at);for(let i of n){if(r<=t)return;try{dS(i.path,{force:!0}),r-=i.size}catch{}}}function DS(t,e){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let n=t===null?Number.NaN:Date.parse(t);return Number.isNaN(n)?$g:Math.max(0,n-e)}function cn(t){return yg.get(t.key)??0}function VS(t){for(let e=t;e instanceof Error;e=e.cause)if(e.code==="ECONNRESET")return!0;return!1}function ZS(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}function QS(t,e){let n=new URL(e,t);if(!n.search)n.search=new URL(t).search;return n.href}async function Fn(t,e,n,r={},i=kS){let o=e;for(let s=1,a=0;;s++){let c=cn(t)-Date.now();if(c>0)await pS(c,void 0,{signal:n});let u;try{u=await fetch(o,{headers:{"User-Agent":Uu,Referer:`${t.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(s<ug&&!n.aborted&&VS(f))continue;throw f}let l=u.headers.get("location");if(l&&u.status>=300&&u.status<400&&a<MS){await u.body?.cancel(),o=QS(o,l),a++,s--;continue}if(u.status===429&&s<ug){await u.body?.cancel();let f=DS(u.headers.get("retry-after"),Date.now());if(f>$g)throw Error(`${t.name} asks to wait ${Math.ceil(f/1000)}s`);yg.set(t.key,Math.max(cn(t),Date.now()+f));continue}if(!u.ok)throw await u.body?.cancel(),Object.assign(Error(ZS(u)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${u.status}`),{status:u.status});return u}}async function Qs(t,e,n){try{return await(await Fn(t,e,n)).text()}catch(r){if(t.missing!==void 0&&r.status===t.missing)return"";throw r}}async function Pg(t,e,n,r){return t.parse(await Qs(t,t.postsUrl(e,n),r))}async function Ku(t,e,n){return t.count(await Qs(t,t.countUrl(e),n))}async function fi(t,e,n){let[r]=t.parse(await Qs(t,t.postUrl(e),n));return r}async function Xs(t,e,n){return t.credits?.(await Qs(t,t.pageUrl(e),n))}var XS=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,tM=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function ho(t){let e=XS.exec(t)?.[1]??tM.exec(t)?.[1];return e?`https://www.pixiv.net/artworks/${e}`:t}function ta(t,e){return t.credits!==void 0&&e.named.artist.length===0}function mo(t,e){for(let n of PS){let r=e.named?.[n]??[];if(t.named[n].length===0&&r.length>0)t.named[n]=r}if(t.source||=e.source??"",t.owner||=e.owner??"",!t.posted&&e.posted)t.posted=e.posted}function eM(t){let e=new URLSearchParams({limit:String(2*Hn),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${t.join(",")}`});return`${Ut.origin}/posts.json?${e}`}function nM(t){return new Map(uo(t).flatMap((e)=>{let n=String(e.md5??"");return n?[[n,{tags:an(e.tag_string),named:{artist:an(e.tag_string_artist),character:an(e.tag_string_character),copyright:an(e.tag_string_copyright)},source:String(e.source??""),file:ui(String(e.file_url??""))}]]:[]}))}function ea(t,e){for(let n of t){let r=e.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],mo(n,r),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=xn(r.file)}}}async function na(t,e){let n=new Map;if(cn(Ut)>Date.now())return n;for(let r=0;r<t.length;r+=Hn){let i=await(await Fn(Ut,eM(t.slice(r,r+Hn)),e,{},yS)).text();for(let[o,s]of nM(i))n.set(o,s)}return n}async function go(t,e,n){if(e.file||!t.guesses)return;for(let r of t.guesses(e))try{let i=await Fn(t,r,n,{Range:`bytes=0-${wg}`}),o=Pn(new Uint8Array(await i.arrayBuffer()));return e.file=r,e.ext=xn(r),o}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${t.name} keeps no png or jpg of ${e.id}`)}async function Hg(t,e){if(cn(Ut)<=Date.now())try{let i=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(cg)}),o=`${Ut.origin}/autocomplete.json?${i}`;return US(await(await Fn(Ut,o,e,{},ag)).text())}catch(i){if(e.aborted)throw i}let n=q.find((i)=>i.key==="yande"),r=new URLSearchParams({name:t,order:"count",limit:String(cg)});return WS(await(await Fn(n,`${n.origin}/tag.json?${r}`,e,{},ag)).text())}function rM(t){try{return(JSON.parse(t).related_tags??[]).flatMap(({tag:n})=>n?.name?[{value:n.name,count:Number(n.post_count)||0}]:[])}catch{return[]}}async function Fg(t,e){if(cn(Ut)>Date.now())return[];let n=new URLSearchParams({"search[query]":t,"search[category]":"character",limit:String(vS)});return rM(await(await Fn(Ut,`${Ut.origin}/related_tag.json?${n}`,e,{},ES)).text())}function xg(t,e){return e.slice(0,t.ors?t.tagBudget:1)}async function Lg(t,e,n){let r=await Fn(t,e,n,{Range:`bytes=0-${wg}`});return Pn(new Uint8Array(await r.arrayBuffer()))}async function ra(t,e,n,r){let i=await Fn(t,e,n,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let a=[],c=0;for(;;){let{done:f,value:d}=await s.read();if(f)break;a.push(d),c+=d.length,r?.(c,o)}let u=new Uint8Array(c),l=0;for(let f of a)u.set(f,l),l+=f.length;return u}var fM=12,dM=/^[0-9a-f]{40}$/;function di(){return hi(Tn(),"drawn")}function Tg(t){return iM("sha1").update(JSON.stringify(t)).digest("hex")}function Ag(t){return oM(hi(di(),t))}function Cg(t){let e=hi(di(),t);try{let n=aM(e),r=n.readUInt32BE(0),i=JSON.parse(n.toString("utf8",4,4+r)),o=n.subarray(4+r,4+r+i.figure),s=n.subarray(4+r+i.figure,4+r+i.figure+i.picture);if(o.length!==i.figure||s.length!==i.picture)return;let a=new Date;return lM(e,a,a),{stem:i.stem,fill:i.fill,...i.peak?{peak:i.peak}:{},figure:o,picture:s}}catch{return}}function qu(t,e){let n=Buffer.from(JSON.stringify({stem:e.stem,fill:e.fill,...e.peak?{peak:e.peak}:{},figure:e.figure.length,picture:e.picture.length})),r=Buffer.alloc(4);r.writeUInt32BE(n.length),x(hi(di(),t),Buffer.concat([r,n,e.figure,e.picture])),hM()}function hM(){let t=sM(di()).filter((e)=>dM.test(e)).flatMap((e)=>{try{return[{name:e,at:uM(hi(di(),e)).mtimeMs}]}catch{return[]}}).sort((e,n)=>n.at-e.at);for(let{name:e}of t.slice(fM))cM(hi(di(),e),{force:!0})}import{readdirSync as kM,readFileSync as qg}from"node:fs";import{basename as yM,join as Jg}from"node:path";/*!
72
84
  * Copyright (c) Squirrel Chat et al., All rights reserved.
73
85
  * SPDX-License-Identifier: BSD-3-Clause
74
86
  *
@@ -94,11 +106,11 @@ ${a}
94
106
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
95
107
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
96
108
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97
- */function y1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function E1(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
- `,o===t)i+=" ".repeat(s+n+2),i+=`^
99
- `}return i}class B extends Error{line;column;codeblock;constructor(e,t){let[n,r]=y1(t.toml,t.ptr),i=E1(t.toml,n,r);super(`Invalid TOML document: ${e}
109
+ */function mM(t,e){let n=t.slice(0,e).split(/\r?\n/);return[n.length,n.pop().length+1]}function gM(t,e,n){let r=t.split(/\r?\n/),i="",o=(Math.log10(e+1)|0)+1;for(let s=e-1;s<=e+1;s++){let a=r[s-1];if(!a)continue;if(i+=s.toString().padEnd(o," "),i+=": ",i+=a,i+=`
110
+ `,s===e)i+=" ".repeat(o+n+2),i+=`^
111
+ `}return i}class G extends Error{line;column;codeblock;constructor(t,e){let[n,r]=mM(e.toml,e.ptr),i=gM(e.toml,n,r);super(`Invalid TOML document: ${t}
100
112
 
101
- ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(e,{toml:t.s,ptr:n??t.p})}}/*!
113
+ ${i}`,e);this.line=n,this.column=r,this.codeblock=i}static x(t,e,n){throw new G(t,{toml:e.s,ptr:n??e.p})}}/*!
102
114
  * Copyright (c) Squirrel Chat et al., All rights reserved.
103
115
  * SPDX-License-Identifier: BSD-3-Clause
104
116
  *
@@ -124,8 +136,8 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
124
136
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
125
137
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
126
138
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
127
- */function Yo(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)B.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,f=n===120?2:n===117?4:8;for(let d=0;d<f;d++,e.p++){let h=e.s.charCodeAt(e.p),g=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;if(g<0)B.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)B.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
- `;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 B.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)B.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}B.x("unfinished string",e,t)}/*!
139
+ */function ia(t){let e=t.p,n=t.s.charCodeAt(t.p++),r=n,i=n===39,o=n===t.s.charCodeAt(t.p)&&n===t.s.charCodeAt(t.p+1);if(o){if((n=t.s.charCodeAt(t.p+=2))===10)t.p++;else if(n===13&&t.s.charCodeAt(t.p+1)===10)t.p+=2}let s="",a=t.p,c=0;for(;t.p<t.s.length;t.p++)if(n=t.s.charCodeAt(t.p),o&&(n===10||n===13&&t.s.charCodeAt(t.p+1)===10))c=c&&3;else if(n<32&&n!==9||n===127)G.x("control characters are not allowed in strings",t);else if((!c||c===3)&&n===r&&(!o||t.s.charCodeAt(t.p+1)===r&&t.s.charCodeAt(t.p+2)===r)){if(o){if(t.s.charCodeAt(t.p+3)===r)t.p++;if(t.s.charCodeAt(t.p+3)===r)t.p++}if(!c){let u=t.s.slice(a,t.p);s=s?s+u:u}return t.p+=o?3:1,s}else if(!c){if(!i&&n===92)s+=t.s.slice(a,a=t.p),c=1}else if(c===1)if(n===120||n===117||n===85){let u=t.p++-1,l=0,f=n===120?2:n===117?4:8;for(let d=0;d<f;d++,t.p++){let m=t.s.charCodeAt(t.p),g=m>=48&&m<=57?m-48:m>=65&&m<=70?m-65+10:m>=97&&m<=102?m-97+10:-1;if(g<0)G.x("invalid non-hex character in unicode escape",t);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)G.x("invalid unicode escape",t,u);s+=String.fromCodePoint(l),a=t.p--,c=0}else if(o&&(n===32||n===9))c=2;else{if(n===98)s+="\b";else if(n===116)s+="\t";else if(n===110)s+=`
140
+ `;else if(n===102)s+="\f";else if(n===114)s+="\r";else if(n===101)s+="\x1B";else if(n===34)s+='"';else if(n===92)s+="\\";else G.x("unrecognised escape sequence",t);a=t.p+1,c=0}else if(n!==32&&n!==9){if(c===2)G.x("invalid escape: only line-ending whitespace may be escaped",t,a);c=!i&&n===92?1:0,a=t.p}G.x("unfinished string",t,e)}/*!
129
141
  * Copyright (c) Squirrel Chat et al., All rights reserved.
130
142
  * SPDX-License-Identifier: BSD-3-Clause
131
143
  *
@@ -151,7 +163,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
151
163
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
152
164
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
153
165
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
154
- */var v1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class qn 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(v1);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 qn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new qn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new qn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new qn(e);return t.#t=!1,t.#e=null,t}}/*!
166
+ */var pM=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class An extends Date{#e=!1;#n=!1;#t=null;constructor(t,e,n){let r=!0,i=!0,o="Z",s;if(typeof t==="string")if(e)t:{if(e<3){if(+t.slice(11,13)>23){t="";break t}if(e===2)o=null,t+="Z";else if((s=t.charCodeAt(t.length-1))!==90&&s!==122)o=t.slice(t.length-6);if(n)t=t.slice(0,10)+"T"+t.slice(11)}else if(e===4)t=+t.slice(0,2)>23?"":`0000-01-01T${t}Z`;r=e!==4,i=e!==3}else{let a=t.match(pM);if(a){if(!a[1])r=!1,t=`0000-01-01T${t}`;if(i=!!a[2],i&&t[10]===" "&&(t=t.replace(" ","T")),a[2]&&+a[2]>23)t="";else if(o=a[3]||null,!o&&i)t+="Z"}else t=""}super(t);if(!isNaN(this.getTime()))this.#e=r,this.#n=i,this.#t=o}isDateTime(){return this.#e&&this.#n}isLocal(){return!this.#e||!this.#n||!this.#t}isDate(){return this.#e&&!this.#n}isTime(){return this.#n&&!this.#e}isValid(){return this.#e||this.#n}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#t===null)return t.slice(0,-1);if(this.#t==="Z"||this.#t==="z")return t;let e=+this.#t.slice(1,3)*60+ +this.#t.slice(4,6);return e=this.#t[0]==="-"?e:-e,new Date(this.getTime()-e*60000).toISOString().slice(0,-1)+this.#t}static wrapAsOffsetDateTime(t,e="Z"){let n=new An(t);return n.#t=e,n}static wrapAsLocalDateTime(t){let e=new An(t);return e.#t=null,e}static wrapAsLocalDate(t){let e=new An(t);return e.#n=!1,e.#t=null,e}static wrapAsLocalTime(t){let e=new An(t);return e.#e=!1,e.#t=null,e}}/*!
155
167
  * Copyright (c) Squirrel Chat et al., All rights reserved.
156
168
  * SPDX-License-Identifier: BSD-3-Clause
157
169
  *
@@ -177,7 +189,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
177
189
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
178
190
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
179
191
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
180
- */function wt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Oc(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function ms(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||B.x("document contains excessively nested structures. aborting.",e);let i=r===91?Ug(e):Wg(e);return e.d++,i}if(r===34||r===39)return Yo(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)B.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)B.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Qo(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 M1(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return S1(e,r,t);return Qo(e,e.p,r,0,t)}function Qo(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)B.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)B.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||Oc(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return Rc(e,t,16,i);else if(s===98)return Rc(e,t,2,i);else if(s===111)return Rc(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else B.x("illegal leading zero",e,t)}else if(!wt(s))B.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!Oc(s,i))){if(!o)o=1;if(s===95){if(!(o&1))B.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(!wt(s))B.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))B.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):Gg(e,u,10,t)}function Rc(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Oc(i,r)))if(i===95){if(s&1)B.x("illegal underscore",e);s=3}else if(!wt(i,n))B.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)B.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return Gg(e,o,n,t)}function Gg(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;B.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 M1(e,t,n){let r=e.p++,i;if(!wt(t)||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++)))return Qo(e,e.p=r,t,0,n);if(e.p+=5,!wt(e.s.charCodeAt(e.p++)))B.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,!wt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return gs(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)B.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(wt(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 gs(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return gs(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return gs(e,s,2,i,r)}function S1(e,t,n){let r=e.p;if(!wt(t)||!wt(e.s.charCodeAt(++e.p)))return Qo(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(wt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return gs(e,i,4,!1,r)}function gs(e,t,n,r,i,s){if(e.ld){let o=new qn(t,n,r);if(!o.isValid())B.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){B.x(o instanceof Error?o.message:""+o,e,i)}}/*!
192
+ */function Qt(t,e=10){return e===16?t>47&&t<58||t>64&&t<71||t>96&&t<103:t>47&&t<48+e}function Yu(t,e){return t===32||t===9||t===10||t===13||e&&(t===e||t===44)||t===35}function bo(t,e){let n=t.p,r=t.s.charCodeAt(t.p);if(r===91||r===123){t.d--||G.x("document contains excessively nested structures. aborting.",t);let i=r===91?Ug(t):Gg(t);return t.d++,i}if(r===34||r===39)return ia(t);if(r===116){if(t.s.charCodeAt(++t.p)!==114||t.s.charCodeAt(++t.p)!==117||t.s.charCodeAt(++t.p)!==101)G.x("invalid value",t,n);return t.p++,!0}if(r===102){if(t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==108||t.s.charCodeAt(++t.p)!==115||t.s.charCodeAt(++t.p)!==101)G.x("invalid value",t,n);return t.p++,!1}if(r===43||r===45)return oa(t,t.p,t.s.charCodeAt(++t.p),44-r,e);if(t.s.charCodeAt(t.p+4)===45&&t.s.charCodeAt(t.p+7)===45)return bM(t,r,e);if(t.s.charCodeAt(t.p+2)===58)return wM(t,r,e);return oa(t,t.p,r,0,e)}function oa(t,e,n,r,i){let o=n,s=0,a=!1;if(o===105){if(t.s.charCodeAt(++t.p)!==110||t.s.charCodeAt(++t.p)!==102)G.x("invalid value",t,e);return t.p++,(r||1)/0}if(o===110){if(t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==110)G.x("invalid value",t,e);return t.p++,NaN}if(o===48){if(++t.p>=t.s.length||Yu(o=t.s.charCodeAt(t.p),i))return t.bi===!0?0n:0;if(!r){if(o===120)return Ju(t,e,16,i);else if(o===98)return Ju(t,e,2,i);else if(o===111)return Ju(t,e,8,i)}if(o===46)s=2;else if(o===101||o===69)s=4;else G.x("illegal leading zero",t,e)}else if(!Qt(o))G.x("invalid value",t,e);while(++t.p<t.s.length&&(o=t.s.charCodeAt(t.p),!Yu(o,i))){if(!s)s=1;if(o===95){if(!(s&1))G.x("illegal underscore",t);s+=11,a=!0}else if(s===1&&o===46)s=2;else if((s===1||s===3)&&(o===101||o===69))s=4;else if(s===4&&(o===43||o===45));else if(!Qt(o))G.x("illegal character in numeric literal",t);else if(s>9)s-=11;else if(!(s&1))s++}if(!s){let u=(n-48)*(r||1);return t.bi===!0?BigInt(u):u}if(!(s&1))G.x("unfinished numeric value",t,e);let c=t.s.slice(e,t.p);if(a)c=c.replaceAll("_","");return s>1?parseFloat(c):jg(t,c,10,e)}function Ju(t,e,n,r){let i,o=1;while(++t.p<t.s.length&&(i=t.s.charCodeAt(t.p),!Yu(i,r)))if(i===95){if(o&1)G.x("illegal underscore",t);o=3}else if(!Qt(i,n))G.x("illegal character in numeric literal",t);else if(o&1)o--;if(o&1)G.x("unfinished numeric value",t);let s=t.s.slice(e+2,t.p);if(o)s=s.replaceAll("_","");return jg(t,s,n,e)}function jg(t,e,n,r){if(t.bi!==!0)t:{let i=parseInt(e,n);if(!Number.isSafeInteger(i)){if(t.bi)break t;G.x("integer value cannot be represented losslessly",t,r)}return i}return n===10?BigInt(e):BigInt((n===2?"0b":n===8?"0o":"0x")+e)}function bM(t,e,n){let r=t.p++,i;if(!Qt(e)||!Qt(t.s.charCodeAt(t.p++))||!Qt(t.s.charCodeAt(t.p++))||!Qt(t.s.charCodeAt(t.p++)))return oa(t,t.p=r,e,0,n);if(t.p+=5,!Qt(t.s.charCodeAt(t.p++)))G.x("invalid date-time: date part is malformed",t,r);if(t.p>=t.s.length||((e=t.s.charCodeAt(t.p))!==32||(i=!0,!Qt(t.s.charCodeAt(t.p+1))))&&e!==84&&e!==116){let s=t.s.slice(r,t.p);return po(t,s,3,!1,r)}if(t.s.charCodeAt(t.p+=3)!==58)G.x("invalid date-time: time part is malformed",t,r);if(t.s.charCodeAt(t.p+=3)===58)t.p+=3;if(t.s.charCodeAt(t.p)===46)while(Qt(t.s.charCodeAt(++t.p)));if(e=t.s.charCodeAt(t.p)){if(e===90||e===122){let s=t.s.slice(r,++t.p);return po(t,s,1,i,r,"[+00:00]")}if(e===43||e===45){let s=t.s.slice(r,t.p+=6);return po(t,s,1,i,r,!t.ld&&"["+t.s.slice(t.p-6,t.p)+"]")}}let o=t.s.slice(r,t.p);return po(t,o,2,i,r)}function wM(t,e,n){let r=t.p;if(!Qt(e)||!Qt(t.s.charCodeAt(++t.p)))return oa(t,--t.p,e,0,n);if(t.s.charCodeAt(t.p+=4)===58)t.p+=3;if(t.s.charCodeAt(t.p)===46)while(Qt(t.s.charCodeAt(++t.p)));let i=t.s.slice(r,t.p);return po(t,i,4,!1,r)}function po(t,e,n,r,i,o){if(t.ld){let s=new An(e,n,r);if(!s.isValid())G.x("invalid date",t,i);return s}try{if(o)e+=o;switch(n){case 1:return Temporal.ZonedDateTime.from(e);case 2:return Temporal.PlainDateTime.from(e);case 3:return Temporal.PlainDate.from(e);case 4:return Temporal.PlainTime.from(e)}}catch(s){G.x(s instanceof Error?s.message:""+s,t,i)}}/*!
181
193
  * Copyright (c) Squirrel Chat et al., All rights reserved.
182
194
  * SPDX-License-Identifier: BSD-3-Clause
183
195
  *
@@ -203,7 +215,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
203
215
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
204
216
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
205
217
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
206
- */function I1(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)B.x("control characters are not allowed in comments",e)}}function Bt(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;I1(e)}}/*!
218
+ */function $M(t){for(;t.p<t.s.length;t.p++){let e=t.s.charCodeAt(t.p);if(e===10)break;if(e===13&&t.s.charCodeAt(t.p+1)===10){t.p++;break}if(e<32&&e!==9||e===127)G.x("control characters are not allowed in comments",t)}}function ye(t,e,n){let r;while(t.p<t.s.length){while(t.p<t.s.length&&((r=t.s.charCodeAt(t.p))===32||r===9||!e&&(r===10||r===13&&t.s.charCodeAt(t.p+1)===10)))t.p++;if(n||r!==35)break;$M(t)}}/*!
207
219
  * Copyright (c) Squirrel Chat et al., All rights reserved.
208
220
  * SPDX-License-Identifier: BSD-3-Clause
209
221
  *
@@ -229,7 +241,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
229
241
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
230
242
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
231
243
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
232
- */function Zo(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)B.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)B.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))B.x("illegal quoted key: multiline strings are not allowed",e);i.push(Yo(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)B.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));B.x("incomplete key-value: cannot find end of key",e,n)}function Wg(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Bt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Zo(e);for(let f=0;f<c.length;f++){if(f)o=a?o[s]:o[s]=Object.create(null);if(s=c[f],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))B.x("trying to redefine an already defined value",e,u);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&B.x("document contains an unsafe property",e,u);break}if(!a&&d)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)B.x("trying to redefine an already defined value",e,u);Bt(e,!0,!0);let l=ms(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Bt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished table",e,t)}function Ug(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Bt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(ms(e,93)),Bt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished array",e,t)}/*!
244
+ */function sa(t,e=61){let n,r=0,i=[],o,s=t.s.charCodeAt(n=t.p);do if(s===e){if(!r)G.x("unexpected end of key",t);if(r===1)i.push(t.s.slice(o,t.p));return t.p++,i}else if(s===46){if(!r)G.x("illegal empty bare key",t);if(r===1)i.push(t.s.slice(o,t.p));r=0}else if(!r&&(s===34||s===39)){if(s===t.s.charCodeAt(t.p+1)&&s===t.s.charCodeAt(t.p+2))G.x("illegal quoted key: multiline strings are not allowed",t);i.push(ia(t)),r=2,t.p--}else if(s===32||s===9){if(r===1)i.push(t.s.slice(o,t.p)),r=2}else if(r===2||s<48&&s!==45||s>57&&s<65||s>90&&s<97&&s!==95||s>122)G.x("illegal character in key",t);else if(!r)r=1,o=t.p;while(s=t.s.charCodeAt(++t.p));G.x("incomplete key-value: cannot find end of key",t,n)}function Gg(t){let e=t.p++,n=Object.create(null),r=new Set,i;while(t.p<t.s.length){if(ye(t),(i=t.s.charCodeAt(t.p))===125)return t.p++,n;let o,s=n,a=!1,c=t.p,u=sa(t);for(let f=0;f<u.length;f++){if(f)s=a?s[o]:s[o]=Object.create(null);if(o=u[f],(a=Object.hasOwn(s,o))&&(typeof s[o]!=="object"||r.has(s[o])))G.x("trying to redefine an already defined value",t,c);let d=o==="__proto__";if(t.uk&&(d||o==="constructor")){s=t.uk!==1&&G.x("document contains an unsafe property",t,c);break}if(!a&&d)Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0})}if(a)G.x("trying to redefine an already defined value",t,c);ye(t,!0,!0);let l=bo(t,125);if(s&&typeof(s[o]=l)==="object")r.add(l);if(ye(t),(i=t.s.charCodeAt(t.p++))===125)return n;if(i!==44)G.x("expected comma or end of structure",t,t.p-1)}G.x("unfinished table",t,e)}function Ug(t){let e=t.p++,n=[],r;while(t.p<t.s.length){if(ye(t),(r=t.s.charCodeAt(t.p))===93)return t.p++,n;if(n.push(bo(t,93)),ye(t),(r=t.s.charCodeAt(t.p++))===93)return n;if(r!==44)G.x("expected comma or end of structure",t,t.p-1)}G.x("unfinished array",t,e)}/*!
233
245
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
246
  * SPDX-License-Identifier: BSD-3-Clause
235
247
  *
@@ -255,7 +267,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
255
267
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
256
268
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
269
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
- */function jg(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 f=s.length-1;s=s[f],o=o[f].c}}if(a=t[l],(u=Object.hasOwn(s,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!u){let f=a==="__proto__";if(e.uk&&(f||a==="constructor"))return!1;if(f)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 Kg(e,t,n){if(t===null||e.uk===2)B.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Fc(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++;Bt(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=Zo(n,93);if(c){if(e.charCodeAt(n.p)!==93)B.x("expected end of table array declaration",n);n.p++}let f=jg(n,l,r,i,c?2:1);if(!f)Kg(n,f,s),o=!0;else u=f[2],a=f[1]}else{s=n.p;let c=Zo(n),l=jg(n,c,a,u,0);if(!l&&!o)Kg(n,l,s);Bt(n,!0,!0);let f=ms(n,void 0);if(l&&!o)l[1][l[0]]=f}if(Bt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))B.x("each key-value declaration must be followed by an end-of-line",n);Bt(n)}return r}/*!
270
+ */function Wg(t,e,n,r,i){let o=n,s=r,a,c=!1,u;for(let l=0;l<e.length;l++){if(l){if(o=c?o[a]:o[a]=Object.create(null),s=(u=s[a]).c,i===0&&(u.t===1||u.t===2))return null;if(u.t===2){let f=o.length-1;o=o[f],s=s[f].c}}if(a=e[l],(c=Object.hasOwn(o,a))&&s[a]?.t===0&&s[a]?.d)return null;if(!c){let f=a==="__proto__";if(t.uk&&(f||a==="constructor"))return!1;if(f)Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(s,a,{enumerable:!0,configurable:!0,writable:!0});s[a]={t:l<e.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(u=s[a],u.t!==i&&!(i===1&&u.t===3))return null;if(i===2){if(!u.d)u.d=!0,o[a]=[];o[a].push(o=Object.create(null)),u.c[u.i++]=u={t:1,d:!1,i:0,c:Object.create(null)}}if(u.d)return null;if(u.d=!0,i===1)o=c?o[a]:o[a]=Object.create(null);else if(i===0&&c)return null;return[a,o,u.c]}function _g(t,e,n){if(e===null||t.uk===2)G.x(e===null?"trying to redefine an already defined table or value":"document contains an unsafe property",t,n)}function Du(t,e={}){let n={s:t,p:0,d:e.maxDepth??1000,bi:e.integersAsBigInt??!1,ld:e.useLegacyDate??!0,uk:e.unsafeKeyBehaviour==="throw"?2:e.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),o,s=!1,a=r,c=i;if(t.charCodeAt(0)===65279)n.p++;ye(n);while(n.p<t.length){if(t.charCodeAt(n.p)===91){let u=t.charCodeAt(++n.p)===91;o=n.p+=+u,s=!1;let l=sa(n,93);if(u){if(t.charCodeAt(n.p)!==93)G.x("expected end of table array declaration",n);n.p++}let f=Wg(n,l,r,i,u?2:1);if(!f)_g(n,f,o),s=!0;else c=f[2],a=f[1]}else{o=n.p;let u=sa(n),l=Wg(n,u,a,c,0);if(!l&&!s)_g(n,l,o);ye(n,!0,!0);let f=bo(n,void 0);if(l&&!s)l[1][l[0]]=f}if(ye(n,!0),n.p<t.length&&(o=t.charCodeAt(n.p))!==10&&(o!==13||t.charCodeAt(n.p+1)!==10))G.x("each key-value declaration must be followed by an end-of-line",n);ye(n)}return r}/*!
259
271
  * Copyright (c) Squirrel Chat et al., All rights reserved.
260
272
  * SPDX-License-Identifier: BSD-3-Clause
261
273
  *
@@ -281,7 +293,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
281
293
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
282
294
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
295
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
- */var WO=!!"".isWellFormed;/*!
296
+ */var $x=!!"".isWellFormed;/*!
285
297
  * Copyright (c) Squirrel Chat et al., All rights reserved.
286
298
  * SPDX-License-Identifier: BSD-3-Clause
287
299
  *
@@ -307,92 +319,93 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
307
319
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
308
320
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
309
321
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
310
- */import{readdirSync as N1,rmSync as P1,statSync as R1}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as O1}from"node:net";import{homedir as F1}from"node:os";import{join as bs}from"node:path";import{setTimeout as T1}from"node:timers/promises";var Vn=100,$t=25000000,H1=536870912,di=["safe","questionable","explicit"],Pr=["nudity","underwear"],Ac=["comic","monochrome","sketch","chibi"],Xg=["off","5","10","25","50","100"],Dg=["off","720","1080","1440","1800","2560"],em={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},x1={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},A1=/^(?:rating|score|width|height|filetype|dimension):/,ps={safe:"s",questionable:"q",explicit:"e"},tm=8191,L1=20000,C1=5000,Bg=3000,Jg=8,_1=3000,nm=60000,qg=3,G1=3,W1="https://static.zerochan.net",rm="https://s1.zerochan.net",Lc=`ttheme/${et.version} (+${et.homepage})`,U1=["orig","tile","thumb","cut"],im=new Map,j1=sE(process.env.TTHEME_FIND_HOSTS),K1=iE(process.env.TTHEME_FIND_CUTOUTS);O1(_1);var B1=["artist","character","copyright"];function Vg(e){try{return N1(e)}catch{return[]}}function hi(e){return e.startsWith("//")?`https:${e}`:e}function Yn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function ws(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 J1(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function Hc(e,t,n){let r=hi(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Yn(r)}}function En(e){return String(e??"").split(/\s+/).filter(Boolean)}function xc(e){let t=typeof e==="number"?new Date(e*1000):typeof e==="string"?new Date(e):void 0;return t&&!Number.isNaN(t.getTime())?t.toISOString().slice(0,10):void 0}function sm(e,t){let n=hi(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??""),score:Number(e.score)||0,rating:String(e.rating??""),md5:String(t.md5??""),source:String(e.source??""),tags:En(t.tags),named:t.named,...xc(e.created_at)?{posted:xc(e.created_at)}:{},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 q1(e){let t=J1(e);return ws(e).flatMap((n)=>{let r=hi(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>En(i).filter((a)=>t.get(a)===o);return sm(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Yn(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:s("artist"),character:s("character"),copyright:s("copyright")},solo:void 0,versions:[Hc(n.jpeg_url,n.jpeg_width,n.jpeg_height),Hc(n.sample_url,n.sample_width,n.sample_height)]})})}function V1(e){return ws(e).flatMap((t)=>{let n=hi(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return sm(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Yn(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:En(t.tag_string_artist),character:En(t.tag_string_character),copyright:En(t.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>Hc(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 om(e){return e.toLowerCase().replace(/\s+/g,"_")}function z1(e){return(Array.isArray(e)?e:[]).map((t)=>om(String(t)))}function Y1(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function Q1(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=z1(i.tags),a=hi(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Yn(a),preview:`${rm}/${Y1(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>em.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,named:{artist:[],character:[],copyright:[]},solo:o.includes("solo"),family:0,smaller:[]}]})}var Z1={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function zg(e){return e.replace(/&(?:#(\d+)|amp|quot|apos|lt|gt);/g,(t,n)=>n?String.fromCharCode(Number(n)):{"&amp;":"&","&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">"}[t]??t)}function X1(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=Z1[r],o=om(zg(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=xc(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:zg(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function D1(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function eE(e){return ws(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function tE(e){return ws(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function nE(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function rE(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function iE(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 sE(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 Xo(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 Or(e){return Xo(e,di,["safe"])}function gi(e){return Xo(e,Pr,Pr,"none")}function Do(e){return Xo(e,Ac,[],"none")}function $s(e){let t=X.map((n)=>n.name);return Xo(e,t,t)}function Cc(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function ks(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function _c(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function Gc(e){let t=j1.get(e.key),n=K1.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 am(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function um(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function Yg(e){let t=Gc(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}`]:[],...um(i)],cutouts:am(t.cutouts),ratings:_c([ps.safe],[ps.questionable],[ps.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ps[i]}`;let s=di.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${ps[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:q1,count:nE,uploadedBy:(r)=>`user:${r}`}}function oE(e){let t=Gc(e),n=_c(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...um(i),...s?["filetype:png"]:[]],cutouts:am(t.cutouts),ratings:n,rate:(r)=>r.length===di.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:V1,count:rE,uploadedBy:(r)=>`user:${r}`}}function Tc(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function Qg(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 aE(e){let t=Gc(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:_c(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${Tc(n)}?${new URLSearchParams({json:"",l:String(Vn),p:String(r+1),...Qg(n)})}`,countUrl:(n)=>`${t.origin}/${Tc(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:Q1,count:D1,credits:X1,counts:(n)=>Tc(n).split(",").length===1&&!("d"in Qg(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(rm,W1).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function uE(e){let t=Zg(`https://${e}`);return X.find((n)=>Zg(n.origin)===t)}function Wc(e){return e.split(/\s+/).filter((t)=>t&&!A1.test(t)).length}function ea(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=X.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=uE(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 X=[oE({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),Yg({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Yg({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),aE({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Lt=X.find((e)=>e.key==="danbooru"),Qn=134217728;function Ct(e,t){let n=X.indexOf(e);return(n===-1?X.length:n)*Qn+t}function Zg(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function mi(e,t,n=t){return t.mirror&&n===t?{site:Lt,url:t.mirror.file}:{site:e,url:n.file}}function ta(e,t){return t.mirror?{site:Lt,url:t.mirror.preview}:{site:e,url:t.preview}}function na(e,t=Pr){return e.tags.filter((n)=>t.some((r)=>em[r].has(n)))}function cm(e,t){return e.tags.filter((n)=>t.some((r)=>x1[r].has(n)))}function ra(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function lm(e,t){return e.rate(["safe"])===""?void 0:di.find((n)=>e.ratings[n].has(t.rating))}function nn(e){return[e,...e.smaller].find((t)=>t.width*t.height<=$t)}function fm(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 pi(){return bs(process.env.XDG_CACHE_HOME??bs(F1(),".cache"),"ttheme")}function rn(e){return bs(pi(),e.key)}function dm(e=H1,t=pi()){let n=[],r=0;for(let i of Vg(t))for(let s of U1){let o=bs(t,i,s);for(let a of Vg(o)){let u=bs(o,a);try{let{size:c,mtimeMs:l}=R1(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{P1(i.path,{force:!0}),r-=i.size}catch{}}}function cE(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)?nm:Math.max(0,n-t)}function zn(e){return im.get(e.key)??0}function lE(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function fE(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function dE(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Rr(e,t,n,r={},i=L1){let s=t;for(let o=1,a=0;;o++){let u=zn(e)-Date.now();if(u>0)await T1(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":Lc,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(o<qg&&!n.aborted&&lE(f))continue;throw f}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<G1){await c.body?.cancel(),s=dE(s,l),a++,o--;continue}if(c.status===429&&o<qg){await c.body?.cancel();let f=cE(c.headers.get("retry-after"),Date.now());if(f>nm)throw Error(`${e.name} asks to wait ${Math.ceil(f/1000)}s`);im.set(e.key,Math.max(zn(e),Date.now()+f));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(fE(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function ia(e,t,n){try{return await(await Rr(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function hm(e,t,n,r){return e.parse(await ia(e,e.postsUrl(t,n),r))}async function Uc(e,t,n){return e.count(await ia(e,e.countUrl(t),n))}async function ys(e,t,n){let[r]=e.parse(await ia(e,e.postUrl(t),n));return r}async function sa(e,t,n){return e.credits?.(await ia(e,e.pageUrl(t),n))}var hE=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,gE=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function Es(e){let t=hE.exec(e)?.[1]??gE.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function oa(e,t){return e.credits!==void 0&&t.named.artist.length===0}function vs(e,t){for(let n of B1){let r=t.named?.[n]??[];if(e.named[n].length===0&&r.length>0)e.named[n]=r}if(e.source||=t.source??"",e.owner||=t.owner??"",!e.posted&&t.posted)e.posted=t.posted}function mE(e){let t=new URLSearchParams({limit:String(2*Vn),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${Lt.origin}/posts.json?${t}`}function pE(e){return new Map(ws(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:En(t.tag_string),named:{artist:En(t.tag_string_artist),character:En(t.tag_string_character),copyright:En(t.tag_string_copyright)},source:String(t.source??""),file:hi(String(t.file_url??""))}]]:[]}))}function aa(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])],vs(n,r),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=Yn(r.file)}}}async function ua(e,t){let n=new Map;if(zn(Lt)>Date.now())return n;for(let r=0;r<e.length;r+=Vn){let i=await(await Rr(Lt,mE(e.slice(r,r+Vn)),t,{},C1)).text();for(let[s,o]of pE(i))n.set(s,o)}return n}async function ca(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Rr(e,r,n,{Range:`bytes=0-${tm}`}),s=Jn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Yn(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 gm(e,t){if(zn(Lt)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(Jg)}),s=`${Lt.origin}/autocomplete.json?${i}`;return eE(await(await Rr(Lt,s,t,{},Bg)).text())}catch(i){if(t.aborted)throw i}let n=X.find((i)=>i.key==="yande"),r=new URLSearchParams({name:e,order:"count",limit:String(Jg)});return tE(await(await Rr(n,`${n.origin}/tag.json?${r}`,t,{},Bg)).text())}async function mm(e,t,n){let r=await Rr(e,t,n,{Range:`bytes=0-${tm}`});return Jn(new Uint8Array(await r.arrayBuffer()))}async function la(e,t,n,r){let i=await Rr(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:f,value:d}=await o.read();if(f)break;a.push(d),u+=d.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let f of a)c.set(f,l),l+=f.length;return c}var kt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Ms="Original",$E=1e6,sn="_groups.toml",pm=3,bm=8,jc="[a-z0-9]+(?:-[a-z0-9]+)*",kE=new RegExp(`^(?:(${jc})@(${jc})/)?(${jc})$`),ym=["background","foreground","cursor","selection"];function ge(e,t){throw Error(`${e}: ${t}`)}function Fr(e,t,n){if(typeof n!=="string"||!Ht(n))ge(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Is(e,t,n){if(typeof n!=="string"||n.length===0)ge(e,`${t} must be a non-empty string`);return n}function vn(e){return e.replace("@","--").replace("/","--")}function _(e){return`ttheme-${vn(e)}`}function Me(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function wi(e){return e.slice(e.indexOf("/")+1)}function on(e){let t=kE.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 Ns(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 Ss(e,t,n){let r=Is(e,t,n),i=Ns(r);if(i)ge(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function wm(e,t,n){let r=Is(e,t,n),i=on(r);if(i)ge(e,`${t} "${r}" ${i}`);return r}function bi(e){return e&&typeof e==="object"?e:{}}function yE(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)ge(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Fr(e,`ghostty.icon_screen[${s}]`,i))}function EE(e,t,n){let r=bi(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Fr(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:yE(e,r.icon_screen,n)}}function vE(e){return new Map([...ym.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function ME(e,t,n){if(!Array.isArray(t)||t.length!==pm)ge(e,`meta.signature must name exactly ${pm} palette slots`);let r=vE(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Is(e,u,a),l=r.get(c);if(l===void 0)ge(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${ym.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)ge(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function SE(e,t,n){if(t===void 0)return;if(!n)ge(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))ge(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=X.find((u)=>u.key===i);if(!o)ge(e,`meta.booru_sites.${i} is not a find site — use ${X.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)))ge(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))ge(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function IE(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>bm)ge(e,`[[picture]] holds 1 to ${bm} pictures`);return t.map((n,r)=>{let i=bi(n),s=`picture[${r}]`,o=X.find((l)=>l.key===i.site);if(!o)ge(e,`${s}.site must be one of ${X.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ge(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))ge(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!kt.includes(u))ge(e,`${s}.position must be one of ${kt.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))ge(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 Em(e,t){try{return Fc(t)}catch(n){ge(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
- `)[0]}`)}}function NE(e){let n=Em(sn,$m(km(e,sn),"utf8")).group;if(!Array.isArray(n)||n.length===0)ge(sn,"needs at least one [[group]] table");return n.map((r)=>{let i=bi(r);return{name:Ss(sn,"group.name",i.name),native:i.native===void 0?void 0:Ss(sn,"group.native",i.native),lead:Is(sn,"group.lead",i.lead)}})}function PE(e,t){if(!Array.isArray(t)||t.length===0)ge(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=Ss(e,`meta.native_names[${r}]`,n);if(i.includes("|"))ge(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function Kc(e,t,n){let r=Em(e,t),i=bi(r.meta),s=bi(r.colors),o=bi(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)ge(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=wm(e,"meta.name",i.name);if(u!==n.name)ge(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)ge(e,`meta.${F} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")ge(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:wm(e,"meta.base",i.base);if(f!==void 0&&!c)ge(e,"meta.base is for market palettes");let d=f===void 0?void 0:n.bases?.get(f),h=c&&i.group===void 0?d?.group??Ms:Ss(e,"meta.group",i.group),g=n.groups.get(h);if(!g&&!(c&&(h===Ms||n.open)))ge(e,`meta.group "${h}" has no [[group]] table in ${sn}`);let b=Fr(e,"colors.background",s.background),p=Fr(e,"colors.foreground",s.foreground),m=Fr(e,"colors.cursor",s.cursor),k=Fr(e,"colors.selection_background",s.selection_background),v=a.map((F,x)=>Fr(e,`colors.ansi[${x}]`,F)),M=ME(e,i.signature,{background:b,foreground:p,cursor:m,selection:k,ansi:v}),w=i.booru===void 0?void 0:Is(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))ge(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let I=SE(e,i.booru_sites,w),$=i.native_names===void 0?void 0:PE(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")ge(e,"contrast.waive needs a contrast.reason explaining why");let R=IE(e,r.picture);return{name:u,...f?{base:f}:{},group:h,native:g?.native,...$?{nativeNames:$}:{},lead:!c&&g?.lead===u,order:c?d?.order??$E:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?f??"original":Ss(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...I?{booruSites:I}:{},background:b,foreground:p,cursor:m,selectionBackground:k,ansi:v,signature:M.colors,signatureSlots:M.names,ghostty:EE(e,r.ghostty,{background:b,cursor:m,selectionBackground:k}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...R?{pictures:R}:{}}}function vm(e){let t=NE(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)ge(sn,"group.name must be unique");let r=bE(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Kc(s,$m(km(e,s),"utf8"),{name:wE(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)ge(sn,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))ge(sn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function Mm(e){return e.filter((t)=>t.role===void 0)}function Tr(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())||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 fa={width:2560,height:1550},HE=2560,xE=0.1,Am=0.99,AE=2,Mn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},LE=ze(it("#19161e","#9b86c8",0.2)),CE="shelf",ga="originals",_E="images.json",Jc=1;function GE(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 Sm(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 Lm(e,t){let r=Sm((s)=>$h({name:e.name,background:it(e.background,t,s),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),i=Sm((s)=>ze(it(e.background,t,s))<=LE);return{cap:r,matched:i,opacity:Math.floor(Math.min(r,i)*100)/100}}function Im(e,t){let n=GE(e,t),{cap:r,matched:i,opacity:s}=Lm(e,n),o=ve(e.background),a=Math.hypot(...ve(n).map((u,c)=>(u-(o[c]??0))*s));return{slot:t,color:n,cap:r,matched:i,opacity:s,reach:a}}function ma(e,t){return Lm(e,t).opacity}function ki(e,t){let n=Im(e,"cursor");if(n.opacity>=xE)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Im(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function WE(e){return Og(e)??{x:0,y:0,w:e.width,h:e.height}}function Zc(e,t){if(e<=0||t<=0)return fa;let n=Math.min(1,fa.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function Cm(e,t,n,r){if(r<Mn.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(Mn.tall*n,Mn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>Mn.widest*t)s=Mn.widest*t,i=s*e.h/e.w;let o=Mn.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-Mn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function _m(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function UE(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(_m(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*Am)return Math.min(AE,Math.max(1,255/Math.max(1,o)));return 1}var Bc=Float64Array.from({length:256},(e,t)=>{let n=t/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4});function jE(e,t,n){return`#${[e,t,n].map((r)=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function KE(e,t){let n=new Uint32Array(256),r=new Float64Array(768),i=Math.max(1,Math.floor(t.w*t.h/400000)),s=0;for(let a=0;a<t.w*t.h;a+=i){let u=((t.y+Math.floor(a/t.w))*e.width+t.x+a%t.w)*4;if((e.data[u+3]??0)>=128){let c=e.data[u]??0,l=e.data[u+1]??0,f=e.data[u+2]??0,d=Math.round(255*Math.sqrt(0.2126*(Bc[c]??0)+0.7152*(Bc[l]??0)+0.0722*(Bc[f]??0)));n[d]=(n[d]??0)+1,r[d*3]=(r[d*3]??0)+c,r[d*3+1]=(r[d*3+1]??0)+l,r[d*3+2]=(r[d*3+2]??0)+f,s++}}let o=0;for(let a=0;a<256&&s>0;a++)if(o+=n[a]??0,o>=s*Am){let u=Math.max(1,n[a]??1);return jE((r[a*3]??0)/u,(r[a*3+1]??0)/u,(r[a*3+2]??0)/u)}return"#ffffff"}function BE(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,_m(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function Gm(e,t,n){let r=Math.max(0,Math.round(e.at.x)),i=Math.max(0,Math.round(e.at.y)),s=Math.min(t,Math.round(e.at.x+e.at.w)),o=Math.min(n,Math.round(e.at.y+e.at.h));if(s<=r||o<=i)return;let a=e.crop.w/e.at.w,u=e.crop.h/e.at.h;return{x0:r,y0:i,x1:s,y1:o,box:{x:e.crop.x+(r-e.at.x)*a,y:e.crop.y+(i-e.at.y)*u,w:(s-r)*a,h:(o-i)*u}}}function da(e,t,n,r){let i=new Float32Array(n*r),s=Gm(t,n,r);if(s){let o=Hg(e,s.box,s.x1-s.x0,s.y1-s.y0);for(let a=s.y0;a<s.y1;a++)i.set(o.data.subarray((a-s.y0)*(s.x1-s.x0),(a-s.y0+1)*(s.x1-s.x0)),a*n+s.x0)}return{width:n,height:r,data:i}}function Xc(e,t,n,r){let i=new Uint8Array(n*r*4),s=Gm(t,n,r);if(s){let o=s.x1-s.x0,a=cs(e,s.box,o,s.y1-s.y0);for(let u=s.y0;u<s.y1;u++)i.set(a.data.subarray((u-s.y0)*o*4,(u-s.y0+1)*o*4),(u*n+s.x0)*4)}return{width:n,height:r,data:i}}function qc(e,t){if(t<=0)return e;let{width:n,height:r}=e,i=[0,1,2,3].map(()=>({width:n,height:r,data:new Float32Array(n*r)}));for(let a=0;a<n*r;a++){let u=e.data[a*4+3]??0;for(let c=0;c<3;c++)i[c].data[a]=(e.data[a*4+c]??0)*u/255;i[3].data[a]=u}let s=i.map((a)=>ls(a,t).data),o=new Uint8Array(n*r*4);for(let a=0;a<n*r;a++){let u=s[3]?.[a]??0;if(u<=0)continue;for(let c=0;c<3;c++)o[a*4+c]=Math.min(255,Math.max(0,Math.round((s[c]?.[a]??0)*255/u)));o[a*4+3]=Math.min(255,Math.round(u))}return{width:n,height:r,data:o}}function Dc(e){let t=WE(e);return{box:t,clear:yn(e,t),ink:BE(e,UE(e,t)),image:e,peak:KE(e,t)}}function Wm(e,t,n,r,i){let s=Dc(e),{box:o,clear:a,ink:u}=s,c=Cm(o,t,n,a),l=Math.min(1,HE/Math.max(o.w,o.h)),f={x:0,y:0,w:Math.round(o.w*l),h:Math.round(o.h*l)},d=r*f.w*c.crop.w/(o.w*c.at.w);if(i==="original")return{coloring:i,figure:qc(cs(e,o,f.w,f.h),d),fill:qc(Xc(e,c,t,n),r),focus:c.focus,peak:s.peak};let h=da(u,{crop:o,at:f,focus:c.focus},f.w,f.h),g=da(u,c,t,n);return{coloring:i,figure:fs(ls(h,d)),fill:fs(ls(g,r)),focus:c.focus}}function JE(e,t,n,r){let i=ve(t),s=ve(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 qE(e,t,n){let r=ve(t),i=new Uint8Array(e.width*e.height*4);for(let s=0;s<e.width*e.height;s++){let o=(e.data[s*4+3]??0)/255*n;for(let a=0;a<3;a++)i[s*4+a]=Math.round((r[a]??0)+((e.data[s*4+a]??0)-(r[a]??0))*o);i[s*4+3]=255}return{width:e.width,height:e.height,data:i}}function Um(e,t,n,r,i,s,o,a="tone"){let{box:u,clear:c,ink:l}=e,f=Cm(u,r,i,c),d=Math.round(100*f.at.w/f.crop.w/Math.min(r/u.w,i/u.h)),h=o?.size??"fill",g=h==="fill"?f:{crop:u,at:zm(u.w,u.h,r,i,h,o?.at??5,!1,h>100?Math.round(f.focus*100):-1),focus:f.focus},b=a==="original"?ma(t,e.peak):n.opacity,p=o?.opacity??b;return{image:a==="original"?qE(qc(Xc(e.image,g,r,i),s),t.background,p):JE(fs(ls(da(l,g,r,i),s)),t.background,n.color,p),fill:d,opacity:b}}function Se(e){return D(e,"ttheme","backgrounds")}function Vc(e){return D(e,_E)}function Xn(e){try{return ha(e,"utf8")}catch{return}}function Zn(e){try{return FE(e)}catch{return[]}}function ct(e){let t=Xn(Vc(e));if(t===void 0)return VE(e);let n=JSON.parse(t);if(n.version!==Jc)throw Error(`${Vc(e)} is version ${n.version} — this ttheme reads version ${Jc}`);return n}function Dn(e){return e.coloring??"tone"}function el(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,...e.selection?{selection:e.selection}:{},ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}function Ps(e){return{hue:{color:e.backdrop.color,opacity:e.backdrop.opacity},colors:el(e)}}function Rs(e){return e.tone===void 0&&Dn(e)==="tone"}function Nm(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function jm(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${Nm(r)}`]:[],...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${t.pictures.length}`,...t.pictures.map((i)=>[`# picture ${i.key} ${i.stem} ${i.fill} ${i.opacity} ${i.artist?.length?Nm(i):"-"}`,...i.from?[i.from]:[]].join(" ")),...t.pictures.filter((i)=>Dn(i)==="original").map((i)=>`# colors ${i.key} original`),`background-image = ${D(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 Km(e){let t=Se(e);for(let[n,r]of Object.entries(ct(t).palettes)){let i=D(t,`${vn(n)}.conf`),s=jm(t,r);if(Xn(i)!==s)K(i,s)}}function yi(e,t,n){K(Vc(e),`${JSON.stringify(t,null,2)}
313
- `);for(let r of n){let i=t.palettes[r],s=D(e,`${vn(r)}.conf`);if(i)K(s,jm(e,i));else $i(s,{force:!0})}}function Bm(e,t){return Zn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function tl(e,t){for(let n of Bm(e,t))$i(D(e,n),{force:!0})}function Jm(e,t){tl(e,t.stem);for(let n of[t.original,t.cut])if(n)$i(D(e,n),{force:!0})}function Pm(e,t,n,r){let i=xm(/^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:D(ga,c)}:{}}}function Rm(e,t){if(Qc(e))Hm(e,t)}function VE(e){let t={version:Jc,palettes:{}};if(!Qc(e))return t;let n=Zn(D(e,ga)),r=Zn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=D(e,CE);for(let s of new Set([...r,...Zn(i)])){let o=[],a=Pm(s,Xn(D(e,`${s}.conf`)),n);if(a)Rm(D(e,`${s}.tune.conf`),D(e,`${a.stem}.tune.conf`)),Rm(D(e,`${s}.off.conf`),D(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Zn(D(i,s))){let c=D(i,s,u),l=Pm(s,Xn(D(c,".conf")),n,u);if(!l)continue;for(let f of Zn(c)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${s}${f}`;if(f!==".conf")Hm(D(c,f),D(e,d))}$i(c,{recursive:!0}),o.push(l)}if(Zn(D(i,s)).length===0)$i(D(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(Zn(i).length===0)$i(i,{recursive:!0,force:!0});return yi(e,t,Object.keys(t.palettes)),t}function Om(e,t,n){return t.startsWith("~/")?D(n,t.slice(2)):TE(t)?t:D(e,t)}function Os(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 f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(f?.[1]==="config-file"&&u<4)i(Om(e,f[2].replace(/^\?/,""),n),u+1);else if(f&&/^background-image(?:-fit|-opacity)?$/.test(f[1]))r.set(f[1],f[2])}return!0};if(!i(D(e,`${vn(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:Om(e,s,n),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function ft(e){return`${e.site}_${e.id}`}function pa(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t];if(!s)throw Error(`${t} has no image`);let o=s.pictures.findIndex((c)=>c.key===(n??s.active));if(o===-1)throw Error(`${t} has no picture ${n}`);let[a]=s.pictures.splice(o,1);Jm(r,a);let u=s.pictures[o%Math.max(s.pictures.length,1)];if(!u)delete i.palettes[t];else if(a.key===s.active)s.active=u.key;return yi(r,i,[t]),{key:a.key,left:s.pictures.length}}function qm(e,t,n,r){let i=n.coloring==="original"?Bn(n.figure):hs(n.figure,r),s=n.coloring==="original"?Bn(n.fill):hs(n.fill,r),o=`${vn(e)}.${Tm("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 Vm(e,t,n){return n.coloring==="original"?{coloring:"original",opacity:ma(e,n.peak),peak:n.peak}:{coloring:"tone",opacity:t.opacity,tone:t.color}}function zc(e,t){return D(ga,`${vn(e)}-${t}`)}function nl(e,t){return t.map(([n,r])=>{let i=D(e,n);return K(i,r),i})}function ba(e,t,n,r,i,s,o,a="tone"){let u=Se(e),c=t.name,l=ft(i),f=ct(u),d=f.palettes[c]??{active:l,pictures:[]},h=Zc(s.width,s.height),g=Wm(r,h.width,h.height,o,a),b=qm(c,l,g,n.color),p=zc(c,l),m={key:l,stem:b.stem,fill:b.fill,...Vm(t,n,g),blur:o,window:h,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${p}.${i.ext}`,...i.cut?{cut:`${p}.cut.png`}:{}},k=d.pictures.find((M)=>M.key===l);if(k)Jm(u,k);OE(D(u,ga),{recursive:!0});let v=nl(u,[...b.files,[m.original,i.bytes],...m.cut?[[m.cut,Pc(ds(r))]]:[]]);return d.pictures=k?d.pictures.map((M)=>M===k?m:M):[...d.pictures,m],d.active=l,f.palettes[c]=d,yi(u,f,[c]),[...v,D(u,`${vn(c)}.conf`)]}function Ei(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t],o=s?s.pictures.findIndex((a)=>a.key===n):-1;if(!s||o===-1)throw Error(`${t} has no picture ${n}`);if(s.active!==n)s.active=n,yi(r,i,[t]);return{at:o+1,of:s.pictures.length}}function _t(e,t){let n=ct(Se(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var Yc="top-right";function zm(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),f=n*t>=r*e!==!o,d=f?u(i*n/100):u(i*r*e/(100*t)),h=f?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-d)/2),b=u(l*(r-h)/2);if(a>=0){if(d>n)g=u((n-d)/2);if(h>r)b=Math.max(r-h,Math.min(0,u(r/2)-u(a*h/100)))}return{x:g,y:b,w:d,h}}function rl(e,t){let n=Xn(D(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=xm(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!==Yc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Fs(e,t,n,r,i){let s=n.size??"fill",o=n.position??Yc,a=n.opacity??t.opacity;if(s==="fill"&&o===Yc&&a===t.opacity)return;let u=kt.indexOf(o)+1,c=D(e,`${t.stem}.png`),l=D(e,t.fill),f=!0,d=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!d)l=c,f=!1;else if(typeof s==="number"){if(Rs(t))throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=At(new Uint8Array(ha(c))),{width:b,height:p}=d?fa:g,m=d?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,k=zm(g.width,g.height,b,p,s,u,!1,m);l=D(e,`${t.stem}@${s}-${o}${d?`-${b}x${p}`:""}.png`);let M={crop:{x:0,y:0,w:g.width,h:g.height},at:k,focus:m};K(l,t.tone?hs(fs(da(ds(g),M,b,p)),t.tone):Bn(Xc(g,M,b,p))),f=d}let h=D(e,`${t.stem}.tune.conf`);return K(h,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
- `)),h}function Ym(e){let t=new Map;for(let[n,r]of Object.entries(ct(Se(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 zE(e){try{let t=Jn(new Uint8Array(ha(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function wa(e,t,n,r,i,s,o,a,u,c=Dn(n)){let l=Se(e),f=n.window??zE(D(l,n.fill))??fa,d=Wm(r,f.width,f.height,s,c),h=qm(t,n.key,d,i.hue.color),g={...n,stem:h.stem,fill:h.fill,...Vm(i.colors,i.hue,d),blur:s,window:f,...u?{cut:`${zc(t,n.key)}.cut.png`}:{}};if(d.coloring==="original")delete g.tone;else delete g.peak;if(u)K(D(l,`${zc(t,n.key)}.cut.png`),Pc(ds(r)));if(h.stem===n.stem)return g;nl(l,h.files);let b=rl(l,n);Fs(l,g,Dn(n)===c?b:{...b,opacity:void 0},o,a);let p=D(l,`${n.stem}.off.conf`);if(Qc(p))RE(p,D(l,`${g.stem}.off.conf`));return g}function il(e,t){let n=Se(e),r=ct(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((f)=>f.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;yi(n,r,[...i]);for(let o of s)tl(n,o)}function Qm(e,t,n){return e.replace(/^background-image-opacity = (\S+)$/m,(r,i)=>Number(i)===t?`background-image-opacity = ${n}`:r)}function Zm(e,t,n){let r=D(e,`${t.stem}.tune.conf`),i=Xn(r);if(i!==void 0)K(r,Qm(i,t.opacity,n));return{...t,opacity:n}}function YE(e,t,n,r){if(n.tone===r.color)return Zm(e,n,r.opacity);let i=Bm(e,n.stem).filter((a)=>a.endsWith(".png")).map((a)=>{let u=new Uint8Array(ha(D(e,a)));return[a,_g(u,r.color)??hs(ds(At(u)),r.color)]}),s=(a)=>i.find(([u])=>u===a)?.[1]??new Uint8Array,o=`${vn(t)}.${Tm("sha1").update(n.key).update(s(`${n.stem}.png`)).update(s(n.fill)).digest("hex").slice(0,8)}`;nl(e,i.map(([a,u])=>[o+a.slice(n.stem.length),u]));for(let a of["tune","off"]){let u=Xn(D(e,`${n.stem}.${a}.conf`));if(u!==void 0)K(D(e,`${o}.${a}.conf`),Qm(u.split(n.stem).join(o),n.opacity,r.opacity))}return{...n,stem:o,fill:o+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function Fm(e,t){if(Dn(e)==="original")return e.peak!==void 0&&ma(t.colors,e.peak)!==e.opacity;return e.tone!==void 0&&(e.tone!==t.hue.color||e.opacity!==t.hue.opacity)}function Xm(e,t){let n=Se(e),r=ct(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o);if(!u||!a.pictures.some((c)=>Fm(c,u)))continue;a.pictures=a.pictures.map((c)=>{if(!Fm(c,u))return c;let l=Dn(c)==="original"?Zm(n,c,ma(u.colors,c.peak)):YE(n,o,c,u.hue);if(l.stem!==c.stem)s.push(c.stem);return l}),i.push(o)}if(i.length>0){yi(n,r,i);for(let o of s)tl(n,o)}return i}function Jt(e){let{slot:t,color:n,opacity:r}=ki({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.nativeNames?{nativeNames:e.nativeNames}:{},...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:Gn(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function Sn(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},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 QE=6,ZE=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function $a(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,...ZE]){let o=t(s);if(i.length===QE||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function Xe(e){return e.filter((t)=>t.default!==!0)}function Ts(){return{version:et.version,gate:bt,placement:Mn,palettes:[]}}function XE(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Ts(),palettes:e.map(Jt)}}var sl={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(XE(e),null,2)}
316
- `}]}};import{existsSync as sv,readdirSync as ip,readFileSync as ov}from"node:fs";import{basename as sp,join as Hs}from"node:path";import{existsSync as DE,readFileSync as Dm}from"node:fs";import{homedir as ep}from"node:os";import{isAbsolute as tp,join as Hr,resolve as ev}from"node:path";var ee="official",an="ttheme-market.json",vi="ttheme-market",tv=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,nv=/^[\w.-]{1,100}$/,rv=/^\w[\w.+/-]{0,199}$/;function tr(e){return Hr(e,"ttheme","installed.json")}function st(e){return e??[ee]}function Mi(e){try{let{markets:t}=JSON.parse(Dm(tr(e),"utf8"));return st(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[ee]}}function xe(e){return tp(e)}function yt(e){return e!==ee&&!xe(e)}function er(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(0,t):e}function ol(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(t+1):void 0}function Si(e,t){return er(e)===er(t)}function nr(e,t){return!xe(e)&&(t?.[e]??e===ee)}function iv(e){return!rv.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function rr(e,t=process.cwd()){if(e===ee)return ee;if(e==="~"||e.startsWith("~/"))return Hr(ep(),e.slice(1));if(e.startsWith(".")||tp(e))return ev(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!tv.test(s)||!o||!nv.test(o)||a.length>0||i.length>0||r!==void 0&&iv(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 np(e){let t=ol(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${er(e)}/${t}/${an}`}function rp(e){return e.slice(0,e.indexOf("/"))}function al(e){return Hr(e,"ttheme","markets")}function qt(e,t){return Hr(al(e),`${er(t).replace("/","--")}.json`)}function ka(e){return Hr(e,"ttheme","market")}function ul(e,t){return Hr(ka(e),t)}function cl(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return on(`${e}@${t}/x`)}function Et({owner:e,name:t}){return`${e}@${t}`}function un(e){let t=Hr(e,an);if(!DE(t))throw Error(`${e} has no ${an} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Dm(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=cl(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function ye(e){if(e===ee)return"the ttheme catalog";if(!xe(e))return`github.com/${e}`;let t=ep();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var In="tt1:",op=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function xr(e,t=!0){return Mi(e).filter(xe).flatMap((n)=>{try{let r=un(n);return[{dir:n,...r,id:Et(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
- `);return[]}})}function ya(e){return Hs(e,"palettes")}function ir(e){let t=ya(e);if(!sv(t))return[];let n=[],r=[];for(let i of ip(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of ip(Hs(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:Hs(t,i.name,s),slug:sp(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Hs(t,i.name),slug:sp(i.name,".toml")})}return[...n,...r]}function xs(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:Ns(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function ll(e,t){let n=Me(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=xr(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=wi(t);return ir(r.dir).find((s)=>s.slug===i)?.path??Hs(ya(r.dir),`${i}.toml`)}function av(e,t){let n=new Map;for(let i of t)if(i.group!==Ms&&!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 vt(e,t,n){let r=wi(e),{native:i,...s}=Kc(`${r}.toml`,t,av(r,n)),o=Me(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function sr(e,t,n,r=!0){let i=new Map;return ir(e).flatMap((s)=>{try{let o=xs(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Jt(vt(`${t}/${s.slug}`,ov(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 Ea(e,t,n=!0){return xr(e,n).flatMap(({dir:r,id:i})=>sr(r,i,t,n))}function fl(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==Ms?{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 Ve=(e)=>JSON.stringify(e);function ap(e){return["[[picture]]",`site = ${Ve(e.site)}`,`id = ${e.id}`,...e.size===void 0?[]:[`size = ${typeof e.size==="number"?e.size:Ve(e.size)}`],...e.position===void 0?[]:[`position = ${Ve(e.position)}`],...e.opacity===void 0?[]:[`opacity = ${e.opacity}`]]}function up(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
319
- `)}${t.map((n)=>`
320
- ${ap(n).join(`
322
+ */var Xt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],wo="Original",vM=1e6,Ue="_groups.toml",Bg=3,zg=8,Vu="[a-z0-9]+(?:-[a-z0-9]+)*",EM=new RegExp(`^(?:(${Vu})@(${Vu})/)?(${Vu})$`),Yg=["background","foreground","cursor","selection"];function Q(t,e){throw Error(`${t}: ${e}`)}function Or(t,e,n){if(typeof n!=="string"||!Bt(n))Q(t,`${e} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function ko(t,e,n){if(typeof n!=="string"||n.length===0)Q(t,`${e} must be a non-empty string`);return n}function We(t){return t.replace("@","--").replace("/","--")}function T(t){return`ttheme-${We(t)}`}function rt(t){let e=t.indexOf("/");return e<0?void 0:t.slice(0,e)}function gi(t){return t.slice(t.indexOf("/")+1)}function ve(t){let e=EM.exec(t);if(!e)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((e[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(e[2]?.length??0)>40||(e[3]?.length??0)>40?"is longer than 40 characters":void 0}function yo(t){if(/[\p{Cc}"$`\\]/u.test(t))return"holds a control character, a quote, $, ` or \\";return t.length>80?"is longer than 80 characters":void 0}function $o(t,e,n){let r=ko(t,e,n),i=yo(r);if(i)Q(t,`${e} ${JSON.stringify(r)} ${i}`);return r}function Kg(t,e,n){let r=ko(t,e,n),i=ve(r);if(i)Q(t,`${e} "${r}" ${i}`);return r}function mi(t){return t&&typeof t==="object"?t:{}}function SM(t,e,n){if(e===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(e)?e:[e];if(r.length===0)Q(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Or(t,`ghostty.icon_screen[${o}]`,i))}function MM(t,e,n){let r=mi(e);return{iconGhost:r.icon_ghost===void 0?n.cursor:Or(t,"ghostty.icon_ghost",r.icon_ghost),iconScreen:SM(t,r.icon_screen,n)}}function IM(t){return new Map([...Yg.map((e)=>[e,t[e]]),...t.ansi.map((e,n)=>[`ansi${n}`,e])])}function OM(t,e,n){if(!Array.isArray(e)||e.length!==Bg)Q(t,`meta.signature must name exactly ${Bg} palette slots`);let r=IM(n),i=[],o=[];for(let[s,a]of e.entries()){let c=`meta.signature[${s}]`,u=ko(t,c,a),l=r.get(u);if(l===void 0)Q(t,`${c} ${JSON.stringify(a)} is not a palette slot — use ${Yg.join(", ")} or ansi0-ansi15`);i.push(u),o.push(l)}if(new Set(o).size!==o.length)Q(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function NM(t,e,n){if(e===void 0)return;if(!n)Q(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!e||typeof e!=="object"||Array.isArray(e))Q(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(e)){let s=q.find((c)=>c.key===i);if(!s)Q(t,`meta.booru_sites.${i} is not a find site — use ${q.map((c)=>c.key).join(", ")}`);let a=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!a||a.some((c)=>typeof c!=="string"||c===""||/\s/.test(c)))Q(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(a.length>1&&!s.ors)Q(t,`meta.booru_sites.${i} takes one tag — ${s.name} does not OR tags`);if(a.length>s.tagBudget)Q(t,`meta.booru_sites.${i} takes ${s.tagBudget} tags at most — ${s.name} searches that many at a time`);r[i]=a}return r}function RM(t,e){if(e===void 0)return;if(!Array.isArray(e)||e.length===0||e.length>zg)Q(t,`[[picture]] holds 1 to ${zg} pictures`);return e.map((n,r)=>{let i=mi(n),o=`picture[${r}]`,s=q.find((l)=>l.key===i.site);if(!s)Q(t,`${o}.site must be one of ${q.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)Q(t,`${o}.id must be the post's number on ${s.name}`);let{size:a,position:c,opacity:u}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))Q(t,`${o}.size must be "fill" or a percentage from 20 to 999`);if(c!==void 0&&!Xt.includes(c))Q(t,`${o}.position must be one of ${Xt.join(", ")}`);if(u!==void 0&&!(typeof u==="number"&&u>=0&&u<=1))Q(t,`${o}.opacity must be a number from 0 to 1`);return{site:s.key,id:i.id,...a!==void 0?{size:a}:{},...c!==void 0?{position:c}:{},...u!==void 0?{opacity:u}:{}}})}function Dg(t,e){try{return Du(e)}catch(n){Q(t,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
323
+ `)[0]}`)}}function PM(t){let n=Dg(Ue,qg(Jg(t,Ue),"utf8")).group;if(!Array.isArray(n)||n.length===0)Q(Ue,"needs at least one [[group]] table");return n.map((r)=>{let i=mi(r);return{name:$o(Ue,"group.name",i.name),native:i.native===void 0?void 0:$o(Ue,"group.native",i.native),lead:ko(Ue,"group.lead",i.lead)}})}function HM(t,e){if(!Array.isArray(e)||e.length===0)Q(t,'meta.native_names must be a list of names, like ["後藤ひとり"]');return e.map((n,r)=>{let i=$o(t,`meta.native_names[${r}]`,n);if(i.includes("|"))Q(t,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function Zu(t,e,n){let r=Dg(t,e),i=mi(r.meta),o=mi(r.colors),s=mi(r.contrast),a=o.ansi;if(!Array.isArray(a)||a.length!==16)Q(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let c=Kg(t,"meta.name",i.name);if(c!==n.name)Q(t,`meta.name "${c}" does not match its file — it lives at ${n.name}`);let u=n.open===!0;for(let W of["order","role"])if(u&&i[W]!==void 0)Q(t,`meta.${W} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")Q(t,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:Kg(t,"meta.base",i.base);if(f!==void 0&&!u)Q(t,"meta.base is for market palettes");let d=f===void 0?void 0:n.bases?.get(f),m=u&&i.group===void 0?d?.group??wo:$o(t,"meta.group",i.group),g=n.groups.get(m);if(!g&&!(u&&(m===wo||n.open)))Q(t,`meta.group "${m}" has no [[group]] table in ${Ue}`);let $=Or(t,"colors.background",o.background),w=Or(t,"colors.foreground",o.foreground),b=Or(t,"colors.cursor",o.cursor),v=Or(t,"colors.selection_background",o.selection_background),R=a.map((W,D)=>Or(t,`colors.ansi[${D}]`,W)),S=OM(t,i.signature,{background:$,foreground:w,cursor:b,selection:v,ansi:R}),I=i.booru===void 0?void 0:ko(t,"meta.booru",i.booru);if(I!==void 0&&/[\s\p{Cc}]/u.test(I))Q(t,`meta.booru must be a single booru tag, got ${JSON.stringify(I)}`);let P=NM(t,i.booru_sites,I),O=i.native_names===void 0?void 0:HM(t,i.native_names),F=Array.isArray(s.waive)?s.waive.map(String):[];if(F.length>0&&typeof s.reason!=="string")Q(t,"contrast.waive needs a contrast.reason explaining why");let j=RM(t,r.picture);return{name:c,...f?{base:f}:{},group:m,native:g?.native,...O?{nativeNames:O}:{},lead:!u&&g?.lead===c,order:u?d?.order??vM:Number(i.order),role:l,ansiSource:u&&i.ansi_source===void 0?f??"original":$o(t,"meta.ansi_source",i.ansi_source),...I?{booru:I}:{},...P?{booruSites:P}:{},background:$,foreground:w,cursor:b,selectionBackground:v,ansi:R,signature:S.colors,signatureSlots:S.names,ghostty:MM(t,r.ghostty,{background:$,cursor:b,selectionBackground:v}),waive:F,waiveReason:typeof s.reason==="string"?s.reason:void 0,...j?{pictures:j}:{}}}function Vg(t){let e=PM(t),n=new Map(e.map((o)=>[o.name,o]));if(n.size!==e.length)Q(Ue,"group.name must be unique");let r=kM(t).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>Zu(o,qg(Jg(t,o),"utf8"),{name:yM(o,".toml"),groups:n})).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of e){let s=r.filter((a)=>a.group===o.name);if(s.length===0)Q(Ue,`group "${o.name}" has no themes`);if(!s.some((a)=>a.name===o.lead))Q(Ue,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function Zg(t){return t.filter((e)=>e.role===void 0)}function Nr(t){let e=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>rt(r.name)?r.name:r.base??r.name;return[...t].sort((r,i)=>Number(rt(r.name)!==void 0)-Number(rt(i.name)!==void 0)||e(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||e((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||e(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||e(r.name,i.name))}var vo={width:2560,height:1550},CM=1,jM=2560,GM=0.1,cp=0.99,UM=2,un={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},WM=yt(Ht("#19161e","#9b86c8",0.2)),_M="shelf",ca="originals",BM="images.json",Xu=1;function zM(t,e){if(e==="background"||e==="foreground"||e==="cursor")return t[e];if(e==="selection"&&t.selection)return t.selection;let n=/^ansi(\d|1[0-5])$/.exec(e),r=n?t.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${e}`);return r}function Qg(t){if(t(1))return 1;let e=0,n=1;for(let r=0;r<40;r++){let i=(e+n)/2;if(t(i))e=i;else n=i}return e}function up(t,e){let r=Qg((o)=>zh({name:t.name,background:Ht(t.background,e,o),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),i=Qg((o)=>yt(Ht(t.background,e,o))<=WM);return{cap:r,matched:i,opacity:Math.floor(Math.min(r,i)*100)/100}}function Xg(t,e){let n=zM(t,e),{cap:r,matched:i,opacity:o}=up(t,n),s=nt(t.background),a=Math.hypot(...nt(n).map((c,u)=>(c-(s[u]??0))*o));return{slot:e,color:n,cap:r,matched:i,opacity:o,reach:a}}function ua(t,e){return up(t,e).opacity}function Gn(t,e){let n=Xg(t,"cursor");if(n.opacity>=GM)return n;return e.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Xg(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function KM(t){return Vm(t)??{x:0,y:0,w:t.width,h:t.height}}function ol(t,e){if(t<=0||e<=0)return vo;let n=Math.min(1,vo.width/Math.max(t,e));return{width:Math.round(t*n),height:Math.round(e*n)}}function lp(t,e,n,r){if(r<un.stands){let c=t.w*n>t.h*e?{x:t.x+(t.w-t.h*e/n)/2,y:t.y,w:t.h*e/n,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*n/e};return{crop:c,at:{x:0,y:0,w:e,h:n},focus:(c.y-t.y+c.h/2)/t.h}}let i=Math.max(un.tall*n,un.reach*e*t.h/t.w),o=i*t.w/t.h;if(o>un.widest*e)o=un.widest*e,i=o*t.h/t.w;let s=un.headroom*n,a=Math.min(1,(n-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*a},at:{x:e*(1-un.margin)-o,y:s,w:o,h:i*a},focus:Math.min(1,(n/2-s)/i)}}function qM(t,e){return 0.299*(t[e]??0)+0.587*(t[e+1]??0)+0.114*(t[e+2]??0)}function JM(t,e){let n=new Uint32Array(256),r=Math.max(1,Math.floor(e.w*e.h/400000)),i=0;for(let s=0;s<e.w*e.h;s+=r){let a=((e.y+Math.floor(s/e.w))*t.width+e.x+s%e.w)*4;if((t.data[a+3]??0)>=128){let c=Math.round(qM(t.data,a));n[c]=(n[c]??0)+1,i++}}let o=0;for(let s=0;s<256&&i>0;s++)if(o+=n[s]??0,o>=i*cp)return Math.min(UM,Math.max(1,255/Math.max(1,s)));return 1}var Qu=Float64Array.from({length:256},(t,e)=>{let n=e/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4});function YM(t,e,n){return`#${[t,e,n].map((r)=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function DM(t,e){let n=new Uint32Array(256),r=new Float64Array(768),i=Math.max(1,Math.floor(e.w*e.h/400000)),o=0;for(let a=0;a<e.w*e.h;a+=i){let c=((e.y+Math.floor(a/e.w))*t.width+e.x+a%e.w)*4;if((t.data[c+3]??0)>=128){let u=t.data[c]??0,l=t.data[c+1]??0,f=t.data[c+2]??0,d=Math.round(255*Math.sqrt(0.2126*(Qu[u]??0)+0.7152*(Qu[l]??0)+0.0722*(Qu[f]??0)));n[d]=(n[d]??0)+1,r[d*3]=(r[d*3]??0)+u,r[d*3+1]=(r[d*3+1]??0)+l,r[d*3+2]=(r[d*3+2]??0)+f,o++}}let s=0;for(let a=0;a<256&&o>0;a++)if(s+=n[a]??0,s>=o*cp){let c=Math.max(1,n[a]??1);return YM((r[a*3]??0)/c,(r[a*3+1]??0)/c,(r[a*3+2]??0)/c)}return"#ffffff"}function VM(t,e){let n=t.data,r=new Uint8Array(t.width*t.height);for(let i=0,o=0;i<r.length;i++,o+=4){let s=n[o+3];if(s===0)continue;let a=(0.299*n[o]+0.587*n[o+1]+0.114*n[o+2])*e;r[i]=(a>255?255:a)*s/255+0.5}return{width:t.width,height:t.height,data:r}}function fp(t,e,n){let r=Math.max(0,Math.round(t.at.x)),i=Math.max(0,Math.round(t.at.y)),o=Math.min(e,Math.round(t.at.x+t.at.w)),s=Math.min(n,Math.round(t.at.y+t.at.h));if(o<=r||s<=i)return;let a=t.crop.w/t.at.w,c=t.crop.h/t.at.h;return{x0:r,y0:i,x1:o,y1:s,box:{x:t.crop.x+(r-t.at.x)*a,y:t.crop.y+(i-t.at.y)*c,w:(o-r)*a,h:(s-i)*c}}}function aa(t,e,n,r){let i=new Float32Array(n*r),o=fp(e,n,r);if(o){let s=tg(t,o.box,o.x1-o.x0,o.y1-o.y0);for(let a=o.y0;a<o.y1;a++)i.set(s.data.subarray((a-o.y0)*(o.x1-o.x0),(a-o.y0+1)*(o.x1-o.x0)),a*n+o.x0)}return{width:n,height:r,data:i}}function sl(t,e,n,r){let i=new Uint8Array(n*r*4),o=fp(e,n,r);if(o){let s=o.x1-o.x0,a=no(t,o.box,s,o.y1-o.y0);for(let c=o.y0;c<o.y1;c++)i.set(a.data.subarray((c-o.y0)*s*4,(c-o.y0+1)*s*4),(c*n+o.x0)*4)}return{width:n,height:r,data:i}}function tl(t,e){if(e<=0)return t;let{width:n,height:r}=t,i=[0,1,2,3].map(()=>({width:n,height:r,data:new Float32Array(n*r)}));for(let a=0;a<n*r;a++){let c=t.data[a*4+3]??0;for(let u=0;u<3;u++)i[u].data[a]=(t.data[a*4+u]??0)*c/255;i[3].data[a]=c}let o=i.map((a)=>ro(a,e).data),s=new Uint8Array(n*r*4);for(let a=0;a<n*r;a++){let c=o[3]?.[a]??0;if(c<=0)continue;for(let u=0;u<3;u++)s[a*4+u]=Math.min(255,Math.max(0,Math.round((o[u]?.[a]??0)*255/c)));s[a*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:s}}function al(t){let e=KM(t),n,r;return{box:e,clear:sn(t,e),get ink(){return n??=VM(t,JM(t,e)),n},image:t,get peak(){return r??=DM(t,e),r}}}function dp(t,e,n,r,i){let o=al(t),{box:s,clear:a,ink:c}=o,u=lp(s,e,n,a),l=Math.min(1,jM/Math.max(s.w,s.h)),f={x:0,y:0,w:Math.round(s.w*l),h:Math.round(s.h*l)},d=r*f.w*u.crop.w/(s.w*u.at.w);if(i==="original")return{coloring:i,figure:tl(no(t,s,f.w,f.h),d),fill:tl(sl(t,u,e,n),r),focus:u.focus,peak:o.peak};let m=aa(c,{crop:s,at:f,focus:u.focus},f.w,f.h),g=aa(c,u,e,n);return{coloring:i,figure:io(ro(m,d)),fill:io(ro(g,r)),focus:u.focus}}function ZM(t,e,n,r){let i=nt(e),o=nt(n),s=new Uint8Array(t.width*t.height*4);for(let a=0;a<t.data.length;a++){let c=(t.data[a]??0)/255*r;for(let u=0;u<3;u++)s[a*4+u]=Math.round((i[u]??0)+((o[u]??0)-(i[u]??0))*c);s[a*4+3]=255}return{width:t.width,height:t.height,data:s}}function QM(t,e,n){let r=nt(e),i=new Uint8Array(t.width*t.height*4);for(let o=0;o<t.width*t.height;o++){let s=(t.data[o*4+3]??0)/255*n;for(let a=0;a<3;a++)i[o*4+a]=Math.round((r[a]??0)+((t.data[o*4+a]??0)-(r[a]??0))*s);i[o*4+3]=255}return{width:t.width,height:t.height,data:i}}function hp(t,e,n,r,i,o,s,a="tone"){let{box:c,clear:u,ink:l}=t,f=lp(c,r,i,u),d=Math.round(100*f.at.w/f.crop.w/Math.min(r/c.w,i/c.h)),m=s?.size??"fill",g=m==="fill"?f:{crop:c,at:kp(c.w,c.h,r,i,m,s?.at??5,!1,m>100?Math.round(f.focus*100):-1),focus:f.focus},$=a==="original"?ua(e,t.peak):n.opacity,w=s?.opacity??$;return{image:a==="original"?QM(tl(sl(t.image,g,r,i),o),e.background,w):ZM(io(ro(aa(l,g,r,i),o)),e.background,n.color,w),fill:d,opacity:$}}function X(t){return U(t,"ttheme","backgrounds")}function el(t){return U(t,BM)}function jn(t){try{return bi(t,"utf8")}catch{return}}function Cn(t){try{return LM(t)}catch{return[]}}function Rt(t){let e=jn(el(t));if(e===void 0)return XM(t);let n=JSON.parse(e);if(n.version!==Xu)throw Error(`${el(t)} is version ${n.version} — this ttheme reads version ${Xu}`);return n}function Ee(t){return t.coloring??"tone"}function cl(t){return{name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,...t.selection?{selection:t.selection}:{},ansi:t.ansi,...t.waived?{waived:t.waived}:{}}}function wi(t){return{hue:{color:t.backdrop.color,opacity:t.backdrop.opacity},colors:cl(t)}}function $i(t){return t.tone===void 0&&Ee(t)==="tone"}function tp(t){return(t.artist??[]).map((e)=>e.replace(/[\s,]+/g,"_")).join(",")}function mp(t,e){let n=e.pictures.findIndex((i)=>i.key===e.active),r=e.pictures[n];return[...r.artist?.length?[`# by ${tp(r)}`]:[],...r.from?[`# from ${r.from}`]:[],`# image ${r.key} ${n+1}/${e.pictures.length}`,...e.pictures.map((i)=>[`# picture ${i.key} ${i.stem} ${i.fill} ${i.opacity} ${i.artist?.length?tp(i):"-"}`,...i.from?[i.from]:[]].join(" ")),...e.pictures.filter((i)=>Ee(i)==="original").map((i)=>`# colors ${i.key} original`),`background-image = ${U(t,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
324
+ `)}function gp(t){let e=X(t);for(let[n,r]of Object.entries(Rt(e).palettes)){let i=U(e,`${We(n)}.conf`),o=mp(e,r);if(jn(i)!==o)x(i,o)}}function ki(t,e,n){x(el(t),`${JSON.stringify(e,null,2)}
325
+ `);for(let r of n){let i=e.palettes[r],o=U(t,`${We(r)}.conf`);if(i)x(o,mp(t,i));else pi(o,{force:!0})}}function pp(t,e){return Cn(t).filter((n)=>n.startsWith(`${e}.`)||n.startsWith(`${e}@`))}function ul(t,e){for(let n of pp(t,e))pi(U(t,n),{force:!0})}function bp(t,e){ul(t,e.stem);for(let n of[e.original,e.cut])if(n)pi(U(t,n),{force:!0})}function ep(t,e,n,r){let i=ap(/^background-image\s*=\s*(.*?)\s*$/m.exec(e??"")?.[1]??"");if(!i.startsWith(`${t}.`)||!/^\.[0-9a-f]{8}@fill-\d+\.png$/.test(i.slice(t.length)))return;let o=i.slice(0,i.indexOf("@")),s=r??/^# image (\S+)$/m.exec(e??"")?.[1]??`picture_${o.slice(t.length+1)}`,a=/^# from (.+)$/m.exec(e??"")?.[1],c=Number(/^background-image-opacity\s*=\s*(\S+)/m.exec(e??"")?.[1]??1),u=n.find((l)=>l.startsWith(`${t}-${s}.`));return{key:s,stem:o,fill:i,opacity:Number.isFinite(c)?c:1,...a?{from:a}:{},...u?{original:U(ca,u)}:{}}}function np(t,e){if(il(t))sp(t,e)}function XM(t){let e={version:Xu,palettes:{}};if(!il(t))return e;let n=Cn(U(t,ca)),r=Cn(t).filter((o)=>o.endsWith(".conf")&&o!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(o)).map((o)=>o.slice(0,-5)),i=U(t,_M);for(let o of new Set([...r,...Cn(i)])){let s=[],a=ep(o,jn(U(t,`${o}.conf`)),n);if(a)np(U(t,`${o}.tune.conf`),U(t,`${a.stem}.tune.conf`)),np(U(t,`${o}.off.conf`),U(t,`${a.stem}.off.conf`)),s.push(a);for(let c of Cn(U(i,o))){let u=U(i,o,c),l=ep(o,jn(U(u,".conf")),n,c);if(!l)continue;for(let f of Cn(u)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${o}${f}`;if(f!==".conf")sp(U(u,f),U(t,d))}pi(u,{recursive:!0}),s.push(l)}if(Cn(U(i,o)).length===0)pi(U(i,o),{recursive:!0,force:!0});if(s.length>0)s.sort((c,u)=>c.key<u.key?-1:c.key>u.key?1:0),e.palettes[o]={active:(a??s[0]).key,pictures:s}}if(Cn(i).length===0)pi(i,{recursive:!0,force:!0});return ki(t,e,Object.keys(e.palettes)),e}function rp(t,e,n){return e.startsWith("~/")?U(n,e.slice(2)):AM(e)?e:U(t,e)}function Eo(t,e,n){let r=new Map,i=(a,c)=>{let u=jn(a);if(u===void 0)return!1;for(let l of u.split(`
326
+ `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(f?.[1]==="config-file"&&c<4)i(rp(t,f[2].replace(/^\?/,""),n),c+1);else if(f&&/^background-image(?:-fit|-opacity)?$/.test(f[1]))r.set(f[1],f[2])}return!0};if(!i(U(t,`${We(e)}.conf`),0))return;let o=r.get("background-image")??"";if(o==="")return;let s=Number(r.get("background-image-opacity")??1);return{image:rp(t,o,n),opacity:Number.isFinite(s)?s:1,cover:r.get("background-image-fit")==="cover"}}function Wt(t){return`${t.site}_${t.id}`}function la(t,e,n){let r=X(t),i=Rt(r),o=i.palettes[e];if(!o)throw Error(`${e} has no image`);let s=o.pictures.findIndex((u)=>u.key===(n??o.active));if(s===-1)throw Error(`${e} has no picture ${n}`);let[a]=o.pictures.splice(s,1);bp(r,a);let c=o.pictures[s%Math.max(o.pictures.length,1)];if(!c)delete i.palettes[e];else if(a.key===o.active)o.active=c.key;return ki(r,i,[e]),{key:a.key,left:o.pictures.length}}function wp(t,e,n,r){let i=n.coloring==="original"?je(n.figure):so(n.figure,r),o=n.coloring==="original"?je(n.fill):so(n.fill,r),s=`${We(t)}.${op("sha1").update(e).update(i).update(o).digest("hex").slice(0,8)}`,a=`${s}@fill-${Math.round(n.focus*100)}.png`;return{stem:s,fill:a,files:[[`${s}.png`,i],[a,o]]}}function $p(t,e,n,r){return n==="original"&&r?{coloring:"original",opacity:ua(t,r),peak:r}:{coloring:"tone",opacity:e.opacity,tone:e.color}}function nl(t,e){return U(ca,`${We(t)}-${e}`)}function ll(t,e){return e.map(([n,r])=>{let i=U(t,n);return x(i,r),i})}function fa(t,e,n,r,i,o,s,a="tone"){let c=X(t),u=e.name,l=Wt(i),f=Rt(c),d=f.palettes[u]??{active:l,pictures:[]},m=ol(o.width,o.height),g=dp(r,m.width,m.height,s,a),$=wp(u,l,g,n.color),w=nl(u,l),b={key:l,stem:$.stem,fill:$.fill,...$p(e,n,g.coloring,g.coloring==="original"?g.peak:void 0),blur:s,window:m,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${w}.${i.ext}`,...i.cut?{cut:`${w}.cut.png`}:{}},v=d.pictures.find((S)=>S.key===l);if(v)bp(c,v);xM(U(c,ca),{recursive:!0});let R=ll(c,[...$.files,[b.original,i.bytes],...b.cut?[[b.cut,Tu(oo(r))]]:[]]);return d.pictures=v?d.pictures.map((S)=>S===v?b:S):[...d.pictures,b],d.active=l,f.palettes[u]=d,ki(c,f,[u]),[...R,U(c,`${We(u)}.conf`)]}function yi(t,e,n){let r=X(t),i=Rt(r),o=i.palettes[e],s=o?o.pictures.findIndex((a)=>a.key===n):-1;if(!o||s===-1)throw Error(`${e} has no picture ${n}`);if(o.active!==n)o.active=n,ki(r,i,[e]);return{at:s+1,of:o.pictures.length}}function fe(t,e){let n=Rt(X(t)).palettes[e];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var rl="top-right";function kp(t,e,n,r,i,o,s,a=-1){let c=Math.trunc,u=(o-1)%3,l=c((o-1)/3),f=n*e>=r*t!==!s,d=f?c(i*n/100):c(i*r*t/(100*e)),m=f?c(i*n*e/(100*t)):c(i*r/100),g=c(u*(n-d)/2),$=c(l*(r-m)/2);if(a>=0){if(d>n)g=c((n-d)/2);if(m>r)$=Math.max(r-m,Math.min(0,c(r/2)-c(a*m/100)))}return{x:g,y:$,w:d,h:m}}function fl(t,e){let n=jn(U(t,`${e.stem}.tune.conf`));if(n===void 0)return{};let r=(u)=>new RegExp(`^${u}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=ap(r("background-image")),o=/@(\d+)-/.exec(i)?.[1],s=/@fill-\d+\.png$/.test(i)?"fill":o?Number(o):r("background-image-fit")==="cover"?"fill":100,a=r("background-image-position").replace("center-center","center")||"center",c=Number(r("background-image-opacity")||1);return{...s!=="fill"?{size:s}:{},...a!==rl?{position:a}:{},...Number.isFinite(c)&&c!==e.opacity?{opacity:c}:{}}}function So(t,e,n,r,i){let o=n.size??"fill",s=n.position??rl,a=n.opacity??e.opacity;if(o==="fill"&&s===rl&&a===e.opacity)return;let c=Xt.indexOf(s)+1,u=U(t,`${e.stem}.png`),l=U(t,e.fill),f=!0,d=typeof o==="number"&&(o>100||!r&&s!=="center");if(o===100&&!d)l=u,f=!1;else if(typeof o==="number"){if($i(e))throw Error(`${e.stem} was drawn before pictures kept their tone — init draws it again`);let g=le(new Uint8Array(bi(u))),{width:$,height:w}=d?vo:g,b=d?Number(/@fill-(\d+)\.png$/.exec(e.fill)?.[1]??50):-1,v=kp(g.width,g.height,$,w,o,c,!1,b);l=U(t,`${e.stem}@${o}-${s}${d?`-${$}x${w}`:""}.png`);let S={crop:{x:0,y:0,w:g.width,h:g.height},at:v,focus:b};x(l,e.tone?so(io(aa(oo(g),S,$,w)),e.tone):je(sl(g,S,$,w))),f=d}let m=U(t,`${e.stem}.tune.conf`);return x(m,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${s}`,`background-image-opacity = ${a}`,""].join(`
327
+ `)),m}function yp(t){let e=new Map;for(let[n,r]of Object.entries(Rt(X(t)).palettes)){let[,i,o]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&o)e.set(n,{site:i,id:Number(o)})}return e}function vp(t){try{let e=Pn(new Uint8Array(bi(t)));return e?{width:e.width,height:e.height}:void 0}catch{return}}function Ep(t,e,n,r,i,o,s){let a=[n.original,n.cut].map((c)=>{if(!c)return"";try{let{size:u,mtimeMs:l}=TM(U(t,c));return`${c}:${u}:${l}`}catch{return}});if(!n.original||a.includes(void 0))return;return Tg([CM,We(e),n.key,...a,r.width,r.height,i,o,o==="tone"?s:""])}function t2(t,e,n){if(!n.window||n.blur===void 0)return;let r=Ep(t,e,n,n.window,n.blur,Ee(n),n.tone??"");if(!r||Ag(r))return;try{qu(r,{stem:n.stem,fill:n.fill,...n.peak?{peak:n.peak}:{},figure:bi(U(t,`${n.stem}.png`)),picture:bi(U(t,n.fill))})}catch{}}function Sp(t,e,n,r,i,o,s,a,c){let u=c?void 0:Ep(t,e,n,r,s,a,o.hue.color),l=u?Cg(u):void 0;if(l)return{made:{stem:l.stem,fill:l.fill,files:[[`${l.stem}.png`,l.figure],[l.fill,l.picture]]},peak:l.peak,image:void 0};let f=i();if(!f)return null;let d=dp(f,r.width,r.height,s,a),m=wp(e,n.key,d,o.hue.color),g=d.coloring==="original"?d.peak:void 0;if(u)qu(u,{stem:m.stem,fill:m.fill,...g?{peak:g}:{},figure:m.files[0]?.[1],picture:m.files[1]?.[1]});return{made:m,peak:g,image:f}}function Mo(t,e,n,r,i,o,s,a,c,u=Ee(n)){let l=X(t),f=n.window??vp(U(l,n.fill))??vo,d=Sp(l,e,n,f,r,i,o,u,c);if(!d)return null;let{made:m,peak:g,image:$}=d,w={...n,stem:m.stem,fill:m.fill,...$p(i.colors,i.hue,u,g),blur:o,window:f,...c?{cut:`${nl(e,n.key)}.cut.png`}:{}};if(u==="original")delete w.tone;else delete w.peak;if(c&&$)x(U(l,`${nl(e,n.key)}.cut.png`),Tu(oo($)));if(m.stem===n.stem)return w;if(Ee(n)!==u)t2(l,e,n);ll(l,m.files);let b=fl(l,n);So(l,w,Ee(n)===u?b:{...b,opacity:void 0},s,a);let v=U(l,`${n.stem}.off.conf`);if(il(v))FM(v,U(l,`${w.stem}.off.conf`));return w}function Mp(t,e,n,r,i,o,s){let a=X(t),c=n.window??vp(U(a,n.fill))??vo;return Sp(a,e,n,c,r,i,o,s,!1)!==null}function dl(t,e){let n=X(t),r=Rt(n),i=new Set,o=[];for(let{name:s,picture:a}of e){let c=r.palettes[s],u=c?.pictures.findIndex((f)=>f.key===a.key)??-1,l=c?.pictures[u];if(!c||!l)continue;if(c.pictures[u]=a,i.add(s),l.stem!==a.stem)o.push(l.stem)}if(i.size===0)return;ki(n,r,[...i]);for(let s of o)ul(n,s)}function Ip(t,e,n){return t.replace(/^background-image-opacity = (\S+)$/m,(r,i)=>Number(i)===e?`background-image-opacity = ${n}`:r)}function Op(t,e,n){let r=U(t,`${e.stem}.tune.conf`),i=jn(r);if(i!==void 0)x(r,Ip(i,e.opacity,n));return{...e,opacity:n}}function e2(t,e,n,r){if(n.tone===r.color)return Op(t,n,r.opacity);let i=pp(t,n.stem).filter((a)=>a.endsWith(".png")).map((a)=>{let c=new Uint8Array(bi(U(t,a)));return[a,sg(c,r.color)??so(oo(le(c)),r.color)]}),o=(a)=>i.find(([c])=>c===a)?.[1]??new Uint8Array,s=`${We(e)}.${op("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;ll(t,i.map(([a,c])=>[s+a.slice(n.stem.length),c]));for(let a of["tune","off"]){let c=jn(U(t,`${n.stem}.${a}.conf`));if(c!==void 0)x(U(t,`${s}.${a}.conf`),Ip(c.split(n.stem).join(s),n.opacity,r.opacity))}return{...n,stem:s,fill:s+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function ip(t,e){if(Ee(t)==="original")return t.peak!==void 0&&ua(e.colors,t.peak)!==t.opacity;return t.tone!==void 0&&(t.tone!==e.hue.color||t.opacity!==e.hue.opacity)}function Np(t,e){let n=X(t),r=Rt(n),i=[],o=[];for(let[s,a]of Object.entries(r.palettes)){let c=e.get(s);if(!c||!a.pictures.some((u)=>ip(u,c)))continue;a.pictures=a.pictures.map((u)=>{if(!ip(u,c))return u;let l=Ee(u)==="original"?Op(n,u,ua(c.colors,u.peak)):e2(n,s,u,c.hue);if(l.stem!==u.stem)o.push(u.stem);return l}),i.push(s)}if(i.length>0){ki(n,r,i);for(let s of o)ul(n,s)}return i}function de(t){let{slot:e,color:n,opacity:r}=Gn({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,...t.base?{base:t.base}:{},group:t.group,...t.native?{native:t.native}:{},...t.nativeNames?{nativeNames:t.nativeNames}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Te(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:e,color:n,opacity:r},...t.pictures?{pictures:t.pictures}:{}}}function Se(t){return{name:t.name,...t.base?{base:t.base}:{},group:t.group,...t.native?{native:t.native}:{},...t.nativeNames?{nativeNames:t.nativeNames}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,ghostty:{iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[],...t.pictures?{pictures:t.pictures}:{}}}var n2=6,r2=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function da(t){let e=(o)=>o.startsWith("ansi")?t.ansi[Number(o.slice(4))]:o==="foreground"?t.foreground:o==="cursor"?t.cursor:o==="selection"?t.selection:void 0,n=(o)=>o.startsWith("ansi")?`ansi${Number(o.slice(4))%8}`:o,r=new Set,i=[];for(let o of["foreground",...t.signatureSlots,...r2]){let s=e(o);if(i.length===n2||!s||r.has(n(o))||i.includes(s))continue;r.add(n(o)),i.push(s)}return i}function Mt(t){return t.filter((e)=>e.default!==!0)}function vi(){return{version:Ot.version,gate:Dt,placement:un,palettes:[]}}import{existsSync as l2,readdirSync as Lp,readFileSync as f2}from"node:fs";import{basename as Tp,join as Io}from"node:path";import{existsSync as i2,readFileSync as Rp}from"node:fs";import{homedir as Pp}from"node:os";import{isAbsolute as Hp,join as Rr,resolve as o2}from"node:path";var J="official",_e="ttheme-market.json",Ei="ttheme-market",s2=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,a2=/^[\w.-]{1,100}$/,c2=/^\w[\w.+/-]{0,199}$/;function Wn(t){return Rr(t,"ttheme","installed.json")}function Ft(t){return t??[J]}function Si(t){try{let{markets:e}=JSON.parse(Rp(Wn(t),"utf8"));return Ft(Array.isArray(e)?e.filter((n)=>typeof n==="string"):void 0)}catch{return[J]}}function ut(t){return Hp(t)}function te(t){return t!==J&&!ut(t)}function Un(t){let e=t.indexOf("#");return te(t)&&e>=0?t.slice(0,e):t}function hl(t){let e=t.indexOf("#");return te(t)&&e>=0?t.slice(e+1):void 0}function Mi(t,e){return Un(t)===Un(e)}function _n(t,e){return!ut(t)&&(e?.[t]??t===J)}function u2(t){return!c2.test(t)||t.includes("..")||t.includes("//")||/(?:[./]|\.lock)$/.test(t)}function Bn(t,e=process.cwd()){if(t===J)return J;if(t==="~"||t.startsWith("~/"))return Rr(Pp(),t.slice(1));if(t.startsWith(".")||Hp(t))return o2(e,t);let[n="",r,...i]=t.split("#"),[o,s,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!o||!s2.test(o)||!s||!a2.test(s)||a.length>0||i.length>0||r!==void 0&&u2(r))throw Error(`${t} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${o.toLowerCase()}/${s}${r===void 0?"":`#${r}`}`}function Fp(t){let e=hl(t)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Un(t)}/${e}/${_e}`}function xp(t){return t.slice(0,t.indexOf("/"))}function ml(t){return Rr(t,"ttheme","markets")}function Me(t,e){return Rr(ml(t),`${Un(e).replace("/","--")}.json`)}function ha(t){return Rr(t,"ttheme","market")}function gl(t,e){return Rr(ha(t),e)}function pl(t,e){if(typeof t!=="string"||typeof e!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return ve(`${t}@${e}/x`)}function ee({owner:t,name:e}){return`${t}@${e}`}function Be(t){let e=Rr(t,_e);if(!i2(e))throw Error(`${t} has no ${_e} — \`ttheme market init ${t}\` makes one`);let n;try{n=JSON.parse(Rp(e,"utf8"))}catch{throw Error(`${e} is not valid JSON`)}let r=pl(n.owner,n.name);if(r)throw Error(`${e} ${r}`);return{owner:n.owner,name:n.name}}function et(t){if(t===J)return"the ttheme catalog";if(!ut(t))return`github.com/${t}`;let e=Pp();return t===e||t.startsWith(`${e}/`)?`~${t.slice(e.length)}`:t}var ln="tt1:",Ap=["background","foreground","cursor","selection",...Array.from({length:16},(t,e)=>`ansi${e}`)];function Pr(t,e=!0){return Si(t).filter(ut).flatMap((n)=>{try{let r=Be(n);return[{dir:n,...r,id:ee(r)}]}catch(r){if(e)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
328
+ `);return[]}})}function ma(t){return Io(t,"palettes")}function zn(t){let e=ma(t);if(!l2(e))return[];let n=[],r=[];for(let i of Lp(e,{withFileTypes:!0}).sort((o,s)=>o.name<s.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let o of Lp(Io(e,i.name)).sort())if(o.endsWith(".toml"))n.push({path:Io(e,i.name,o),slug:Tp(o,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Io(e,i.name),slug:Tp(i.name,".toml")})}return[...n,...r]}function Oo(t,e){let n=e.get(t.slug);if(n)return`${t.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=t.catalog===void 0?void 0:yo(t.catalog);return r?`the catalog folder ${JSON.stringify(t.catalog)} ${r}`:void 0}function bl(t,e){let n=rt(e);if(!n)throw Error(`${e} is an official palette — yours are named <you>@<market>/<palette>`);let r=Pr(t,!1).find((o)=>o.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=gi(e);return zn(r.dir).find((o)=>o.slug===i)?.path??Io(ma(r.dir),`${i}.toml`)}function d2(t,e){let n=new Map;for(let i of e)if(i.group!==wo&&!n.has(i.group)){let o=e.find((s)=>s.group===i.group&&s.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:o})}let r=new Map(e.filter((i)=>!i.default&&!rt(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:t,groups:n,bases:r,open:!0}}function ne(t,e,n){let r=gi(t),{native:i,...o}=Zu(`${r}.toml`,e,d2(r,n)),s=rt(t);return{...o,name:t,...s?{group:s,lead:!1}:{}}}function Kn(t,e,n,r=!0){let i=new Map;return zn(t).flatMap((o)=>{try{let s=Oo(o,i);if(s)throw Error(s);i.set(o.slug,o);let a=de(ne(`${e}/${o.slug}`,f2(o.path,"utf8"),n));return[o.catalog?{...a,catalog:o.catalog}:a]}catch(s){if(r)process.stderr.write(`ttheme: skipping ${o.path} — ${s.message}
329
+ `);return[]}})}function ga(t,e,n=!0){return Pr(t,n).flatMap(({dir:r,id:i})=>Kn(r,i,e,n))}function wl(t,e=t.name,n){return{name:e,...t.base?{base:t.base}:{},...t.group!==wo?{group:t.group}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},signature:t.signatureSlots,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selection,ansi:t.ansi,...t.waived&&t.waived.length>0?{waive:t.waived,reason:n??"kept from the palette"}:{},...t.pictures?{pictures:t.pictures}:{}}}var bt=(t)=>JSON.stringify(t);function Cp(t){return["[[picture]]",`site = ${bt(t.site)}`,`id = ${t.id}`,...t.size===void 0?[]:[`size = ${typeof t.size==="number"?t.size:bt(t.size)}`],...t.position===void 0?[]:[`position = ${bt(t.position)}`],...t.opacity===void 0?[]:[`opacity = ${t.opacity}`]]}function jp(t,e){return e.length===0?t:`${t.replace(/\n*$/,`
330
+ `)}${e.map((n)=>`
331
+ ${Cp(n).join(`
321
332
  `)}
322
- `).join("")}`}function dl(e){let t=["[meta]",`name = ${Ve(wi(e.name))}`,...e.base?[`base = ${Ve(e.base)}`]:[],...e.group?[`group = ${Ve(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${Ve(e.ansiSource)}`]:[],...e.booru?[`booru = ${Ve(e.booru)}`]:[],`signature = [${e.signature.map(Ve).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(Ve).join(", ")}]`)]:[],"","[colors]",`background = ${Ve(e.background)}`,`foreground = ${Ve(e.foreground)}`,`cursor = ${Ve(e.cursor)}`,`selection_background = ${Ve(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${Ve(n)},`),"",...e.ansi.slice(8).map((n)=>` ${Ve(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(Ve).join(", ")}]`,`reason = ${Ve(e.reason??"")}`);for(let n of e.pictures??[])t.push("",...ap(n));return`${t.join(`
333
+ `).join("")}`}function $l(t){let e=["[meta]",`name = ${bt(gi(t.name))}`,...t.base?[`base = ${bt(t.base)}`]:[],...t.group?[`group = ${bt(t.group)}`]:[],...t.ansiSource?[`ansi_source = ${bt(t.ansiSource)}`]:[],...t.booru?[`booru = ${bt(t.booru)}`]:[],`signature = [${t.signature.map(bt).join(", ")}]`,...t.booruSites?["","[meta.booru_sites]",...Object.entries(t.booruSites).map(([n,r])=>`${n} = [${r.map(bt).join(", ")}]`)]:[],"","[colors]",`background = ${bt(t.background)}`,`foreground = ${bt(t.foreground)}`,`cursor = ${bt(t.cursor)}`,`selection_background = ${bt(t.selection)}`,"ansi = [",...t.ansi.slice(0,8).map((n)=>` ${bt(n)},`),"",...t.ansi.slice(8).map((n)=>` ${bt(n)},`),"]"];if(t.waive&&t.waive.length>0)e.push("","[contrast]",`waive = [${t.waive.map(bt).join(", ")}]`,`reason = ${bt(t.reason??"")}`);for(let n of t.pictures??[])e.push("",...Cp(n));return`${e.join(`
323
334
  `)}
324
- `}class cp{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 lp{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 fp(e){let t=new cp;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(op.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<<cc.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(X.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:kt.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${In}${t.done()}`}function dp(e){if(!e.startsWith(In))throw Error(`a share code starts with ${In}`);let t=e.slice(In.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 lp(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((k)=>op[k]??`slot${k}`),l=n.str(),f=n.str(),d=n.str(),h=n.str(),g=n.u16(),b=n.str(),p=cc.filter((k,v)=>g&1<<v),m=Array.from({length:n.u8()},()=>{let k=X[n.u8()]?.key??"unknown",v=n.u32(),M=n.u16(),w=n.u8(),I=n.u16();return{site:k,id:v,...M===1?{size:"fill"}:M>1?{size:M}:{},...w>0?{position:kt[w-1]??"unknown"}:{},...I>0?{opacity:(I-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Ht))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...f?{group:f}:{},...d?{ansiSource:d}:{},...h?{booru:h}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...p.length>0?{waive:p,reason:b}:{},...m.length>0?{pictures:m}:{}}}function hl(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function gl(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,()=>Ve(t.ansi[i++]));return[["background",t.background],["foreground",t.foreground],["cursor",t.cursor],["selection_background",t.selection]].reduce((a,[u,c])=>a.replace(new RegExp(`^(${u}\\s*=\\s*)"#[0-9a-fA-F]{6}"`,"m"),(l,f)=>`${f}${Ve(c)}`),e.slice(0,n)+s+e.slice(r))}function hp(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(Ve).join(", ")}]`)}function As(e){let t=Gn(Sn(e)),n=new Set(e.waived??[]),r=Math.max(...bt.map((i)=>i.label.length));return bt.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 pp="https://kecan0406.github.io/ttheme/manifest.json",uv=20000;function Vt(e){return mp(e,"ttheme","catalog.json")}function va(e,t){K(Vt(e),`${JSON.stringify(t,null,2)}
325
- `)}function We(e,t=!0){let n=Mi(e),r=Vt(e),i=Ts();if(n.includes(ee)){if(!gp(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=cn(ml(r,"utf8"))}let s=n.filter(yt).flatMap((o)=>cv(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function or(e,t){return pl(ml(qt(e,t),"utf8"))}function Ii(e,t){return Et({owner:rp(e),name:t.name})}function cv(e,t,n){let r=qt(e,t);if(!gp(r))return[];try{let i=or(e,t);return Ma(i,Ii(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
- `);return[]}}function pl(e){let t=cn(e),n=cl(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 Ma(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function cn(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=bp(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function bp(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=on(e.name)??(e.base===void 0?void 0:on(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Ht(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"?Ns(n):"has a field that is not text";if(r)return r}return}function wp(e){return mp(e,"ttheme","kept.json")}function Sa(e,t){K(wp(e),`${JSON.stringify({palettes:t},null,2)}
327
- `)}function Nn(e){try{let{palettes:t}=JSON.parse(ml(wp(e),"utf8"));return Array.isArray(t)?t.filter((n)=>bp(n)===void 0):[]}catch{return[]}}function Ke(e,t,n=!0){let r=[...t.palettes,...Ea(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...Nn(e).filter((s)=>!i.has(s.name))]}}function ln(e){return Ke(e,We(e))}class Ia extends Error{}class Na extends Error{}async function Ls(e,t,n=uv,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 Ia(`nothing at ${e}`);if(i.status===403||i.status===429)throw new Na(`${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 Cs(e){let t=new Set(e.waived??[]),n=e.gate??Gn(Sn(e));return bt.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 Ar(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${bl(e,[t])}`);return n}function bl(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 $p(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 kp(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 yp(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as _M}from"node:child_process";import{existsSync as ff,mkdirSync as Yb,readdirSync as GM,readFileSync as hf,rmSync as Qb}from"node:fs";import{basename as WM,join as Ur,relative as UM}from"node:path";import{existsSync as tf,readFileSync as Ob,rmSync as nf}from"node:fs";import{homedir as dn}from"node:os";import{join as Qa}from"node:path";var lv=["black","red","green","yellow","blue","magenta","cyan","white"];function Ep(e,t){return[e,...lv.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
- `)}var wl={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...ar(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}'`,"",Ep("[colors.normal]",e.ansi.slice(0,8)),Ep("[colors.bright]",e.ansi.slice(8,16))].join(`
329
- `);return[{path:`alacritty/themes/${_(e.name)}.toml`,content:t}]}};var $l={id:"ghostty",emit(e){let t=[...ar(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}`),"","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
330
- `);return[{path:`ghostty/themes/${_(e.name)}`,content:t}]}};function ur(e){let[t,n,r]=ve(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function Mp(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,ur(t)])),"Background Color":ur(e.background),"Bold Color":ur(e.foreground),"Cursor Color":ur(e.cursor),"Cursor Text Color":ur(e.background),"Foreground Color":ur(e.foreground),"Selected Text Color":ur(e.foreground),"Selection Color":ur(e.selectionBackground)}}function vp(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Sp(e,t,n,r,i=!1){let s=(u,c)=>({Name:`ttheme · ${c}`,Guid:_(c),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,...vp(t.get(u.name)),...Mp(u)}),o={Name:"ttheme · default",Guid:_("default"),"Dynamic Profile Parent GUID":r,...vp(void 0)},a=[...n?[s(n,"default")]:i&&r?[o]:[],...e.map((u)=>s(u,u.name))];return`${JSON.stringify({Profiles:a},null,2)}
331
- `}function fv(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(`
332
- `)}var kl={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(Mp(e)).map(([n,r])=>fv(n,r)),"</dict>","</plist>",""].join(`
333
- `);return[{path:`iterm2/${_(e.name)}.itermcolors`,content:t}]}};var yl={id:"kitty",emit(e){let t=[...ar(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(`
334
- `);return[{path:`kitty/themes/${_(e.name)}.conf`,content:t}]}};function Ip(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(`
335
- `)}function Pn(e,t){return[`[${e}]`,`Color=${ve(t).join(",")}`,""]}function dv(e){let t=(n)=>it(n,e.background,0.5);return[...ar(e),"",...Pn("Background",e.background),...Pn("BackgroundFaint",e.background),...Pn("BackgroundIntense",e.background),...e.ansi.slice(0,8).flatMap((n,r)=>[...Pn(`Color${r}`,n),...Pn(`Color${r}Faint`,t(n)),...Pn(`Color${r}Intense`,e.ansi[r+8])]),...Pn("Foreground",e.foreground),...Pn("ForegroundFaint",t(e.foreground)),...Pn("ForegroundIntense",e.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${e.name}`,"Opacity=1","Wallpaper=",""].join(`
336
- `)}var El={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(e){return[{path:`konsole/${_(e.name)}.colorscheme`,content:dv(e)}]}};var Np=44,Gt=[{name:"Shell",lines:["«B4»~/code/demo«d» on «5»main«2» +2«3» ~1","«2»❯ «»git status -sb","«w»## «2»main«»...«1»origin/main«3» [ahead 1]","«1» M«» src/main.rs","«1»??«» notes.md","","«w»«2»❯ «»ls","«w»«B4»docs«» «B4»src«» «B4»tests«» Cargo.toml README.md","«w»","«2»❯ «»cargo test","«2» ✓«» parses config","«n»«1» ✗«» renders frame","«w»«1» ✗«» renders frame«d» expected «2»3«d», received «1»2","","«2»❯ «»echo «s»selected text«» «c» "]},{name:"Code",lines:["«d» 12 │ «5»import«» { readFile } «5»from «2»'node:fs/promises'","«d» 13 │","«d» 14 │ «8»// Read a palette and check its sixteen colors","«d» 15 │ «5»export async function «4»load«»(path: «6»string«») {","«d» 16 │ «5»const«» text = «5»await «4»readFile«»(path, «2»'utf8'«»)","«b» 17 «d»│ «5»const«» colors = «s»parse(text)«».colors ?? {}","«d» 18 │ «5»if«» (colors.ansi.length !== «3»16«») {","«d» 19 │ «5»throw new «6»Error«»(«2»'needs 16 colors'«»)","«d» 20 │ }","«d» 21 │ «5»return«» { ...colors, ratio: «c»4«3».5«» }","«d» 22 │ }"]},{name:"Diff",lines:["«2»❯ «»git diff --stat","«» src/theme.ts | 3 «2»++«1»-","«2»❯ «»git diff","«b»diff --git a/src/theme.ts b/src/theme.ts","«6»@@ -16,3 +16,4 @@«» export async function load(","«» const text = await readFile(path, 'utf8')","«1»- const colors = parse(text).colors","«2»+ const colors = parse(text).colors ?? {}","«2»+ const ratio = contrast(colors)","«2»❯ «»git log --oneline --graph -4","«3»* 3f2a1c9 («B6»HEAD -> «B2»main«3»)«» Check contrast on load","«3»* 9b04e7d«» Merge branch ansi","«1»|«5»\\","«1»| «5»* «3»51cd0aa«» Add sixteen ANSI colors","«1»|«5»/","«3»* 07be2f1 («B1»origin/main«3», «B3»tag: v1.0«3»)«» Read palette files"]},{name:"Logs",lines:["«2»❯ «»npm run dev","«B2» VITE v6.2.0«d» ready in «b»412«d» ms","«2» ➜ «b»Local«»: «6»http://localhost:5173/","«d»10:42:07 «2»INFO «» GET /api/palettes «2»200«d» 12 ms","«d»10:42:08 «2»INFO «» GET /api/themes/kita «2»200«d» 8 ms","«d»10:42:09 «3»WARN «» slow query: palettes «3»812 ms","«d»10:42:10 «4»DEBUG«» cache hit themes/kita","«d»10:42:11 «B1»ERROR«» POST /api/share «1»500«d» 41 ms","«1» Error«»: read ECONNRESET","«d» at «»TCP.onStreamRead «d»(«6»node:net:216:20«d»)","«d» at «»share «d»(«6»src/share.ts:48:11«d»)","«d»10:42:12 «2»INFO «» retry 1/3 in 200 ms"]},{name:"Monitor",lines:["«6» 1 «b»[«2»|||||||||||||«1»||«» 42.1%«b»]«6» Tasks: «b»128«», 412 thr; «B2»3«» running","«6» 2 «b»[«2»||||||«4»||«» 21.4%«b»]«6» Load average: «b»1.42 «»1.18 0.97","«6» 3 «b»[«2»||||||||||||||«1»|||||«» 71.0%«b»]«6» Uptime: «b»3 days, 04:12:55","«6» 4 «b»[«2»||«» 7.9%«b»]","«6» Mem«b»[«2»||||||||«4»||«3»||«» 6.21G/16.0G«b»]","«6» Swp«b»[«1»|«» 0.10G/2.00G«b»]","","«K2» PID USER CPU% MEM% TIME+ Command ","«s» 4127 kec 38.2 2.1 3:12.44 node dev.js ","«» 2210 kec 12.0 4.8 1:02.10 «b»ghostty","«» 3301 kec 4.4 1.2 0:05.61 «b»zsh","«» 812 «1»root«» 3.1 0.3 0:44.02 «d»kernel_task","«» 167 «1»root«» 0.9 0.1 0:12.80 «d»WindowServer"]}];function Pa(e){let t=Gt.length;return Gt[(e%t+t)%t]}function Pp(e,t){let n=e.split("«"),r=n[0]?[[n[0],""]]:[];for(let i of n.slice(1)){let s=i.indexOf("»"),o=i.slice(0,s),a=i.slice(s+1);if(o==="w"||o==="n"){if(o==="w"!==t>=44)return}if(a)r.push([a,o==="w"||o==="n"?"":o])}return r}import{openSync as hv,writeSync as gv}from"node:fs";import{ReadStream as mv}from"node:tty";var Ni=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function gt(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function vl(e,t){return`\x1B]${Ni[e]};${t}\x1B\\`}function Ml(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":vl(r,n)).join("")}function pv(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function bv(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 wv(e){return`#${e.slice(e.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function Rp(e,t=[...e.keys()],n=!1){return t.map((r)=>{let i=e.get(r);return i?`\x1B]${r};${n?wv(i):i}\x1B\\`:pv(r)}).join("")}function Op(e,t){return`\x1B]50;ColorScheme=${e};UseCustomCursorColor=true;customCursorColor=${t}\x07`}function $v(e=Ni){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function kv(e){return e.includes("\x1B[0n")}async function Fp(e=Ni){let t,n;try{t=hv("/dev/tty","r+"),n=new mv(t),n.setRawMode(!0)}catch{return new Map}try{gv(t,$v(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),kv(r))clearTimeout(s),i()})}),bv(r)}finally{n.setRawMode(!1),n.destroy()}}function Sl(e){if(e.NVIM)return"nvim";if(e.VIM_TERMINAL)return"vim";if(e.INSIDE_EMACS)return"emacs";return e.TERM_PROGRAM==="vscode"?"vscode":void 0}function Mt(e){if(Sl(e))return"editor";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.KONSOLE_VERSION)return"konsole";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"}var zt={ghostty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},warp:{links:!1,pictures:!0,bands:!0,files:!1,moves:!1,layers:!1,paints:!1},editor:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0}};function Tp(e){return zt[Mt(e)].links}function Hp(e){return zt[Mt(e)].pictures&&!e.TMUX}function xp(e){return zt[Mt(e)].bands}function Ap(e){return zt[Mt(e)].files}function Lp(e){return zt[Mt(e)].layers}function Cp(e){return zt[Mt(e)].moves}var Pi="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function cr(e,t){let n=Mt(e),r=zt[n];if(!t||gt(e)||e.TMUX||!r.paints)return;let i=r.repaint??Ni.map((o,a)=>a),s=Ni.filter((o,a)=>i.includes(a));return{slots:i,paint:(o)=>Ml(o,i),wear:(o,a)=>!r.schemes?Ml(o):a.includes(n)?Op(_(o.name),o.cursor):void 0,saved:()=>Fp(s),restore:(o)=>Rp(o,s,r.hex===!0)}}var St=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var yv=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"},{section:"support",title:"Support"}],Gs=[{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:["[directory]"],about:"Pick a palette for this directory, everything below it or its repository — cd in repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:["[directory]"],about:"Drop a pin — this directory's, every one below it, or the one above that paints it",section:"tab",shell:!0},{name:"pins",args:[],about:"Map every pinned directory as a tree in its palette's colors, and the pin that covers this one",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>, from blank in the palette editor — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"Open the editor on this palette's colors instead of blank"},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 the palette 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:"info",args:[],about:"Print what a bug report needs — version, OS, shell, terminal and the settings you changed",section:"support"},{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:St,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>","[picture]"],about:"Show one of a palette's saved backgrounds, remove one, draw one in its palette's tone or its own colors, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"flatten",args:["<source>","<out>","<background>","<opacity>","[canvas]","[place]"],about:"Lay a picture on a background color at an opacity, placed on a canvas when given one, for Warp, which fades the window instead — preview calls this",section:"setup",hidden:!0},{name:"bake",args:["<source>","<out>","<canvas>","<place>"],about:"Place a picture on a transparent canvas the way sips bakes preview's tuning — preview in Warp 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 _s(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function Il(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var Ev=[["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 Ws(e,t=!1){let n=Gs.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=yv.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>","",et.description,"","Start here",...Il(o.map((u)=>[_s(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(`
337
- `)}let s=Math.max(...n.map((o)=>_s(o).length));return["Usage: ttheme <command>","",et.description,...r.flatMap(({section:o,title:a})=>["",a,...Il(n.filter((u)=>u.section===o).map((u)=>[_s(u),u.about]),s)]),"","Examples",...Il(Ev),"",...i].join(`
338
- `)}import{readFileSync as vv}from"node:fs";import{join as Mv}from"node:path";var Nl="# ttheme begin",Pl="# ttheme end",Ri=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function lr(e,t){let n=`${Nl}
339
- ${t}
340
- ${Pl}
341
- `;if(Ri.test(e))return e.replace(Ri,n);if(e==="")return n;return`${e.replace(/\n*$/,`
335
+ `}class Gp{bytes=[];u8(t){this.bytes.push(t&255)}u16(t){this.u8(t>>8),this.u8(t)}u32(t){this.u16(Math.floor(t/65536)),this.u16(t%65536)}str(t=""){let e=new TextEncoder().encode(t);if(e.length>255)throw Error(`"${t}" is too long to share`);this.u8(e.length),this.bytes.push(...e)}color(t){let e=Number.parseInt(t.slice(1),16);this.u8(e>>16),this.u8(e>>8),this.u8(e)}done(){return Buffer.from(this.bytes).toString("base64url")}}class Up{at=0;bytes;constructor(t){this.bytes=t}u8(){let t=this.bytes[this.at++];if(t===void 0)throw Error("the share code is cut short");return t}u16(){return this.u8()*256+this.u8()}u32(){return this.u16()*65536+this.u16()}str(){let t=this.u8(),e=this.bytes.subarray(this.at,this.at+t);if(e.length!==t)throw Error("the share code is cut short");return this.at+=t,new TextDecoder("utf-8",{fatal:!0}).decode(e)}color(){return`#${[this.u8(),this.u8(),this.u8()].map((t)=>t.toString(16).padStart(2,"0")).join("")}`}end(){if(this.at!==this.bytes.length)throw Error("the share code has bytes left over")}}function Wp(t){let e=new Gp;e.str(t.name);for(let r of[t.background,t.foreground,t.cursor,t.selection,...t.ansi])e.color(r);for(let r of t.signature)e.u8(Ap.indexOf(r));e.str(t.base),e.str(t.group),e.str(t.ansiSource),e.str(t.booru),e.u16((t.waive??[]).reduce((r,i)=>r|1<<pu.indexOf(i),0)),e.str(t.waive&&t.waive.length>0?t.reason:"");let n=t.pictures??[];e.u8(n.length);for(let r of n)e.u8(q.findIndex((i)=>i.key===r.site)),e.u32(r.id),e.u16(r.size===void 0?0:r.size==="fill"?1:r.size),e.u8(r.position===void 0?0:Xt.indexOf(r.position)+1),e.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${ln}${e.done()}`}function _p(t){if(!t.startsWith(ln))throw Error(`a share code starts with ${ln}`);let e=t.slice(ln.length);if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error("the share code holds characters it never uses — was it copied whole?");let n=new Up(new Uint8Array(Buffer.from(e,"base64url"))),r=n.str(),[i,o,s,a,...c]=Array.from({length:20},()=>n.color()),u=[n.u8(),n.u8(),n.u8()].map((v)=>Ap[v]??`slot${v}`),l=n.str(),f=n.str(),d=n.str(),m=n.str(),g=n.u16(),$=n.str(),w=pu.filter((v,R)=>g&1<<R),b=Array.from({length:n.u8()},()=>{let v=q[n.u8()]?.key??"unknown",R=n.u32(),S=n.u16(),I=n.u8(),P=n.u16();return{site:v,id:R,...S===1?{size:"fill"}:S>1?{size:S}:{},...I>0?{position:Xt[I-1]??"unknown"}:{},...P>0?{opacity:(P-1)/1000}:{}}});if(n.end(),![i,o,s,a,...c].every(Bt))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...f?{group:f}:{},...d?{ansiSource:d}:{},...m?{booru:m}:{},signature:u,background:i,foreground:o,cursor:s,selection:a,ansi:c,...w.length>0?{waive:w,reason:$}:{},...b.length>0?{pictures:b}:{}}}function kl(t){return{background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi}}function yl(t,e){let n=t.indexOf("ansi = ["),r=t.indexOf("]",n);if(n<0||r<0)throw Error("no ansi = [...] list to rewrite");let i=0,o=t.slice(n,r).replace(/"#[0-9a-fA-F]{6}"/g,()=>bt(e.ansi[i++]));return[["background",e.background],["foreground",e.foreground],["cursor",e.cursor],["selection_background",e.selection]].reduce((a,[c,u])=>a.replace(new RegExp(`^(${c}\\s*=\\s*)"#[0-9a-fA-F]{6}"`,"m"),(l,f)=>`${f}${bt(u)}`),t.slice(0,n)+o+t.slice(r))}function Bp(t,e){return t.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${e.map(bt).join(", ")}]`)}function No(t){let e=Te(Se(t)),n=new Set(t.waived??[]),r=Math.max(...Dt.map((i)=>i.label.length));return Dt.map((i,o)=>{let s=e[o],a=n.has(i.rule)||Number.isNaN(s)||(i.min===void 0||s>=i.min)&&(i.max===void 0||s<=i.max),c=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",u=Number.isNaN(s)?"—":Number.isInteger(s)?String(s):s.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${u.padStart(6)} ${c}${n.has(i.rule)?" waived":""}`})}import{existsSync as h2,readFileSync as m2,rmSync as g2}from"node:fs";import{join as p2}from"node:path";var ba=["background","foreground","cursor","selection",...Array.from({length:16},(t,e)=>`ansi${e}`)],b2=1;function zp(t){return p2(t,"ttheme","tone.json")}function Kp(t){return ba.includes(t)}function fn(t){let e=zp(t);if(!h2(e))return{};let n;try{n=JSON.parse(m2(e,"utf8"))}catch{return{}}let r=n?.palettes;if(typeof r!=="object"||r===null)return{};let i={};for(let[o,s]of Object.entries(r)){if(typeof s!=="object"||s===null)continue;let a={};for(let[c,u]of Object.entries(s))if(Kp(c)&&typeof u==="string"&&Bt(u.toLowerCase()))a[c]=u.toLowerCase();if(Object.keys(a).length>0)i[o]=a}return i}function qp(t,e){let n=zp(t),r=Object.fromEntries(Object.entries(e).filter(([,i])=>Object.keys(i).length>0));if(Object.keys(r).length===0){g2(n,{force:!0});return}x(n,`${JSON.stringify({version:b2,palettes:r},null,2)}
336
+ `)}function pa(t,e){if(e==="background"||e==="foreground"||e==="cursor"||e==="selection")return t[e];return t.ansi[Number(e.slice(4))]}function Jp(t,e){let n={};return ba.forEach((r,i)=>{let o=e[i].toLowerCase();if(o!==pa(t,r).toLowerCase())n[r]=o}),n}function Ro(t,e){if(!e)return t;let n=(u)=>e[u]===void 0||e[u]===pa(t,u).toLowerCase();if(ba.every(n))return t;let r=(u)=>e[u]??pa(t,u),i={background:r("background"),foreground:r("foreground"),cursor:r("cursor"),selection:r("selection"),ansi:ba.slice(4).map(r)},o=t.signatureSlots.map((u)=>Kp(u)?r(u):pa(i,u)),s={...t,...i,signature:o},a=Se(s),c=Gn({name:s.name,background:i.background,foreground:i.foreground,cursor:i.cursor,selection:i.selection,ansi:i.ansi,waived:a.waive},s.signatureSlots);return{...s,gate:Te(a),backdrop:c}}function wa(t,e){return Object.keys(e).length===0?t:t.map((n)=>Ro(n,e[n.name]))}function Yp(t,e,n){let r={...t};if(Object.keys(n).length===0)delete r[e];else r[e]=n;return r}var Zp="https://kecan0406.github.io/ttheme/manifest.json",w2=20000;function Ie(t){return Vp(t,"ttheme","catalog.json")}function $a(t,e){x(Ie(t),`${JSON.stringify(e,null,2)}
337
+ `)}function ct(t,e=!0){let n=Si(t),r=Ie(t),i=vi();if(n.includes(J)){if(!Dp(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=ze(vl(r,"utf8"))}let o=n.filter(te).flatMap((s)=>$2(t,s,e));return{...i,palettes:[...i.palettes,...o]}}function qn(t,e){return El(vl(Me(t,e),"utf8"))}function Ii(t,e){return ee({owner:xp(t),name:e.name})}function $2(t,e,n){let r=Me(t,e);if(!Dp(r))return[];try{let i=qn(t,e);return ka(i,Ii(e,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
338
+ `);return[]}}function El(t){let e=ze(t),n=pl(e.owner,e.name);if(n)throw Error(`market index ${n}`);let r=e.palettes.find((i)=>rt(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return e}function ka(t,e){return t.palettes.map(({lead:n,default:r,native:i,...o})=>({...o,name:`${e}/${o.name}`,group:e}))}function ze(t){let e;try{e=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let n=e;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=Qp(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function Qp(t){if(typeof t?.name!=="string"||!Array.isArray(t.ansi)||t.ansi.length!==16)return"is missing name or its 16 ANSI colors";let e=ve(t.name)??(t.base===void 0?void 0:ve(t.base));if(e)return e;if(![t.background,t.foreground,t.cursor,t.selection,...t.ansi].every((n)=>typeof n==="string"&&Bt(n)))return'holds a color that is not "#rrggbb"';for(let n of[t.group,t.native??"-",t.catalog??"-",t.ansiSource]){let r=typeof n==="string"?yo(n):"has a field that is not text";if(r)return r}return}function Xp(t){return Vp(t,"ttheme","kept.json")}function ya(t,e){x(Xp(t),`${JSON.stringify({palettes:e},null,2)}
339
+ `)}function dn(t){try{let{palettes:e}=JSON.parse(vl(Xp(t),"utf8"));return Array.isArray(e)?e.filter((n)=>Qp(n)===void 0):[]}catch{return[]}}function Hr(t,e,n=!0){let r=[...e.palettes,...ga(t,e.palettes,n)],i=new Set(r.map((o)=>o.name));return{...e,palettes:[...r,...dn(t).filter((o)=>!i.has(o.name))]}}function wt(t,e,n=!0){let r=Hr(t,e,n);return{...r,palettes:wa(r.palettes,fn(t))}}function Oe(t){return wt(t,ct(t))}class va extends Error{}class Ea extends Error{}async function Po(t,e,n=w2,r){let i;try{let o=AbortSignal.timeout(n);i=await fetch(t,{signal:r?AbortSignal.any([o,r]):o})}catch(o){throw Error(`cannot reach ${t} — ${o instanceof Error?o.message:String(o)}`)}if(i.status===404)throw new va(`nothing at ${t}`);if(i.status===403||i.status===429)throw new Ea(`${new URL(t).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${t} answered ${i.status}`);return e(await i.text())}function Ho(t){let e=new Set(t.waived??[]),n=t.gate??Te(Se(t));return Dt.flatMap((r,i)=>{let o=n[i];if(e.has(r.rule)||typeof o!=="number"||Number.isNaN(o))return[];if(r.min!==void 0&&o<r.min)return[`${r.label} ${o} < ${r.min}`];if(r.max!==void 0&&o>r.max)return[`${r.label} ${o} > ${r.max}`];return[]})}function hn(t,e){let n=t.find((r)=>r.name===e);if(!n)throw Error(`no palette named ${e} in the catalog — ${Sl(t,[e])}`);return n}function Sl(t,e){let n=e.map((s)=>s.toLowerCase()),r=t.filter((s)=>n.some((a)=>s.name.includes(a))),i=t.filter((s)=>!r.includes(s)&&n.some((a)=>s.group.toLowerCase().includes(a))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function tb(t,e){let n=e.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function eb(t,e,n){let r=n.toLowerCase(),i=(o)=>o.name===e.name?0:o.group===e.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Ml(t,e){return t.booruSites?.[e]??(t.booru?[t.booru]:[])}var Jn=[{name:"preview",title:"Preview"},{name:"browse",title:"Browse"}],Sa=10,nb=20;function rb(t){return Jn.find((e)=>e.name===t.TTHEME_HUB)?.name}function ib(t,e){return 20+(Jn.findIndex((r)=>r.name===t)+e+Jn.length)%Jn.length+1}function ob(t,e){let n=Jn.map(({name:i,title:o})=>{if(!e)return i===t?`[${o}]`:` ${o} `;return i===t?`\x1B[7;1m\x1B[36m ${o} \x1B[0m`:`\x1B[2m ${o} \x1B[0m`}),r="tab next";return` ${n.join(" ")} ${e?"\x1B[2mtab next\x1B[0m":"tab next"}`}import{execFileSync as DI}from"node:child_process";import{existsSync as kf,mkdirSync as Tw,readdirSync as VI,readFileSync as vf,rmSync as Aw}from"node:fs";import{basename as ZI,join as Cr,relative as QI}from"node:path";import{existsSync as ff,readFileSync as mw,rmSync as df}from"node:fs";import{homedir as qe}from"node:os";import{join as Ja}from"node:path";var sb=44,he=[{name:"Shell",lines:["«B4»~/code/demo«d» on «5»main«2» +2«3» ~1","«2»❯ «»git status -sb","«w»## «2»main«»...«1»origin/main«3» [ahead 1]","«1» M«» src/main.rs","«1»??«» notes.md","","«w»«2»❯ «»ls","«w»«B4»docs«» «B4»src«» «B4»tests«» Cargo.toml README.md","«w»","«2»❯ «»cargo test","«2» ✓«» parses config","«n»«1» ✗«» renders frame","«w»«1» ✗«» renders frame«d» expected «2»3«d», received «1»2","","«2»❯ «»echo «s»selected text«» «c» "]},{name:"Code",lines:["«d» 12 │ «5»import«» { readFile } «5»from «2»'node:fs/promises'","«d» 13 │","«d» 14 │ «8»// Read a palette and check its sixteen colors","«d» 15 │ «5»export async function «4»load«»(path: «6»string«») {","«d» 16 │ «5»const«» text = «5»await «4»readFile«»(path, «2»'utf8'«»)","«b» 17 «d»│ «5»const«» colors = «s»parse(text)«».colors ?? {}","«d» 18 │ «5»if«» (colors.ansi.length !== «3»16«») {","«d» 19 │ «5»throw new «6»Error«»(«2»'needs 16 colors'«»)","«d» 20 │ }","«d» 21 │ «5»return«» { ...colors, ratio: «c»4«3».5«» }","«d» 22 │ }"]},{name:"Diff",lines:["«2»❯ «»git diff --stat","«» src/theme.ts | 3 «2»++«1»-","«2»❯ «»git diff","«b»diff --git a/src/theme.ts b/src/theme.ts","«6»@@ -16,3 +16,4 @@«» export async function load(","«» const text = await readFile(path, 'utf8')","«1»- const colors = parse(text).colors","«2»+ const colors = parse(text).colors ?? {}","«2»+ const ratio = contrast(colors)","«2»❯ «»git log --oneline --graph -4","«3»* 3f2a1c9 («B6»HEAD -> «B2»main«3»)«» Check contrast on load","«3»* 9b04e7d«» Merge branch ansi","«1»|«5»\\","«1»| «5»* «3»51cd0aa«» Add sixteen ANSI colors","«1»|«5»/","«3»* 07be2f1 («B1»origin/main«3», «B3»tag: v1.0«3»)«» Read palette files"]},{name:"Logs",lines:["«2»❯ «»npm run dev","«B2» VITE v6.2.0«d» ready in «b»412«d» ms","«2» ➜ «b»Local«»: «6»http://localhost:5173/","«d»10:42:07 «2»INFO «» GET /api/palettes «2»200«d» 12 ms","«d»10:42:08 «2»INFO «» GET /api/themes/kita «2»200«d» 8 ms","«d»10:42:09 «3»WARN «» slow query: palettes «3»812 ms","«d»10:42:10 «4»DEBUG«» cache hit themes/kita","«d»10:42:11 «B1»ERROR«» POST /api/share «1»500«d» 41 ms","«1» Error«»: read ECONNRESET","«d» at «»TCP.onStreamRead «d»(«6»node:net:216:20«d»)","«d» at «»share «d»(«6»src/share.ts:48:11«d»)","«d»10:42:12 «2»INFO «» retry 1/3 in 200 ms"]},{name:"Monitor",lines:["«6» 1 «b»[«2»|||||||||||||«1»||«» 42.1%«b»]«6» Tasks: «b»128«», 412 thr; «B2»3«» running","«6» 2 «b»[«2»||||||«4»||«» 21.4%«b»]«6» Load average: «b»1.42 «»1.18 0.97","«6» 3 «b»[«2»||||||||||||||«1»|||||«» 71.0%«b»]«6» Uptime: «b»3 days, 04:12:55","«6» 4 «b»[«2»||«» 7.9%«b»]","«6» Mem«b»[«2»||||||||«4»||«3»||«» 6.21G/16.0G«b»]","«6» Swp«b»[«1»|«» 0.10G/2.00G«b»]","","«K2» PID USER CPU% MEM% TIME+ Command ","«s» 4127 kec 38.2 2.1 3:12.44 node dev.js ","«» 2210 kec 12.0 4.8 1:02.10 «b»ghostty","«» 3301 kec 4.4 1.2 0:05.61 «b»zsh","«» 812 «1»root«» 3.1 0.3 0:44.02 «d»kernel_task","«» 167 «1»root«» 0.9 0.1 0:12.80 «d»WindowServer"]}];function Ma(t){let e=he.length;return he[(t%e+e)%e]}function ab(t,e){let n=t.split("«"),r=n[0]?[[n[0],""]]:[];for(let i of n.slice(1)){let o=i.indexOf("»"),s=i.slice(0,o),a=i.slice(o+1);if(s==="w"||s==="n"){if(s==="w"!==e>=44)return}if(a)r.push([a,s==="w"||s==="n"?"":s])}return r}import{openSync as k2,writeSync as y2}from"node:fs";import{ReadStream as v2}from"node:tty";var Oi=["11","10","12","17",...Array.from({length:16},(t,e)=>`4;${e}`)];function zt(t=process.env){return Boolean(t.NO_COLOR)||t.TERM==="dumb"}function Il(t,e){return`\x1B]${Oi[t]};${e}\x1B\\`}function Ol(t,e){return[t.background,t.foreground,t.cursor,t.selection,...t.ansi].map((n,r)=>e&&!e.includes(r)?"":Il(r,n)).join("")}function E2(t){return`\x1B]${t.startsWith("4;")?`104;${t.slice(2)}`:`1${t}`}\x1B\\`}function S2(t){let e=new Map;for(let n of t.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)e.set(i,o)}return e}function M2(t){return`#${t.slice(t.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function cb(t,e=[...t.keys()],n=!1){return e.map((r)=>{let i=t.get(r);return i?`\x1B]${r};${n?M2(i):i}\x1B\\`:E2(r)}).join("")}function ub(t,e){return`\x1B]50;ColorScheme=${t};UseCustomCursorColor=true;customCursorColor=${e}\x07`}function I2(t=Oi){return`${t.map((e)=>`\x1B]${e};?\x1B\\`).join("")}\x1B[5n`}function O2(t){return t.includes("\x1B[0n")}async function lb(t=Oi){let e,n;try{e=k2("/dev/tty","r+"),n=new v2(e),n.setRawMode(!0)}catch{return new Map}try{y2(e,I2(t));let r="";return await new Promise((i)=>{let o=setTimeout(i,120);n.on("data",(s)=>{if(r+=s.toString(),O2(r))clearTimeout(o),i()})}),S2(r)}finally{n.setRawMode(!1),n.destroy()}}function Nl(t){if(t.NVIM)return"nvim";if(t.VIM_TERMINAL)return"vim";if(t.INSIDE_EMACS)return"emacs";return t.TERM_PROGRAM==="vscode"?"vscode":void 0}function re(t){if(Nl(t))return"editor";if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.KONSOLE_VERSION)return"konsole";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}var Ne={ghostty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},warp:{links:!1,pictures:!0,bands:!0,files:!1,moves:!1,layers:!1,paints:!1},editor:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0}};function fb(t){return Ne[re(t)].links}function db(t){return Ne[re(t)].pictures&&!t.TMUX}function hb(t){return Ne[re(t)].bands}function mb(t){return Ne[re(t)].files}function gb(t){return Ne[re(t)].layers}function pb(t){return Ne[re(t)].moves}var Ni="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function Yn(t,e){let n=re(t),r=Ne[n];if(!e||zt(t)||t.TMUX||!r.paints)return;let i=r.repaint??Oi.map((s,a)=>a),o=Oi.filter((s,a)=>i.includes(a));return{slots:i,paint:(s)=>Ol(s,i),wear:(s,a)=>!r.schemes?Ol(s):a.includes(n)?ub(T(s.name),s.cursor):void 0,saved:()=>lb(o),restore:(s)=>cb(s,o,r.hex===!0)}}var ie=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var N2=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"},{section:"support",title:"Support"}],xo=[{name:"preview",args:[],about:"Try palettes live — focus repaints, enter edits its tone and picture and applies it, esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter tunes the one you land on and applies it",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:["[directory|ssh:<host>]"],about:"Pick a palette for this directory, everything below it, its repository or an ssh host — cd or ssh in repaints, leaving restores",section:"tab",shell:!0},{name:"unpin",args:["[directory|ssh:<host>]"],about:"Drop a pin — this directory's, every one below it, the one above that paints it, or an ssh host's",section:"tab",shell:!0},{name:"pins",args:[],about:"Map every pinned directory as a tree in its palette's colors, every ssh host, and the pin that covers this one",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 — shift+←/→ 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>, from blank in the palette editor — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"Open the editor on this palette's colors instead of blank"},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 the palette 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",flags:{tone:{type:"string",value:"<tuned|original>",choices:["tuned","original"],about:"Share the palette as you tuned its colors, or as it was — asked when you tuned it and omit this"}}},{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:"info",args:[],about:"Print what a bug report needs — version, OS, shell, terminal and the settings you changed",section:"support"},{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:ie,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>","[picture]"],about:"Show one of a palette's saved backgrounds, remove one, draw one in its palette's tone or its own colors (or get the other ready before it is asked for), or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"flatten",args:["<source>","<out>","<background>","<opacity>","[canvas]","[place]"],about:"Lay a picture on a background color at an opacity, placed on a canvas when given one, for Warp, which fades the window instead — preview calls this",section:"setup",hidden:!0},{name:"bake",args:["<source>","<out>","<canvas>","<place>"],about:"Place a picture on a transparent canvas the way sips bakes preview's tuning — preview in Warp calls this",section:"setup",hidden:!0},{name:"tone",args:["<palette>"],about:"Serve a palette's tone editor over stdin and stdout — preview's palette panel runs it",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 Fo(t){let e=Object.entries(t.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[t.name,...e,...t.args].join(" ")}function Rl(t,e=Math.max(...t.map(([n])=>n.length))){return t.map(([n,r])=>` ${n.padEnd(e)} ${r}`)}var R2=[["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 Lo(t,e=!1){let n=xo.filter((s)=>!s.hidden&&!(e&&s.section==="setup")),r=N2.filter(({section:s})=>n.some((a)=>a.section===s)),i=[...e?["ttheme alone opens preview and browse as tabs — tab and shift+tab move between them"]:[],t?"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(!t){let s=n.filter((c)=>c.start),a=Math.max(...r.map(({title:c})=>c.length));return["Usage: ttheme <command>","",Ot.description,"","Start here",...Rl(s.map((c)=>[Fo(c),c.start])),"",...r.map(({section:c,title:u})=>`${u.padEnd(a)} ${n.filter((l)=>l.section===c).map((l)=>l.name).join(" · ")}`),"",...i].join(`
340
+ `)}let o=Math.max(...n.map((s)=>Fo(s).length));return["Usage: ttheme <command>","",Ot.description,...r.flatMap(({section:s,title:a})=>["",a,...Rl(n.filter((c)=>c.section===s).map((c)=>[Fo(c),c.about]),o)]),"","Examples",...Rl(R2),"",...i].join(`
341
+ `)}import{readFileSync as P2}from"node:fs";import{join as H2}from"node:path";var Pl="# ttheme begin",Hl="# ttheme end",Ri=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function Dn(t,e){let n=`${Pl}
342
+ ${e}
343
+ ${Hl}
344
+ `;if(Ri.test(t))return t.replace(Ri,n);if(t==="")return n;return`${t.replace(/\n*$/,`
342
345
  `)}
343
- ${n}`}function fr(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*$/,`
344
- `)}function dr(e,t){let n=e.replace(Ri,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function _p(e){return`source ${e}/ttheme.zsh`}var Sv="# ttheme settings — uncomment a line to change it; exported variables win over this file",Oi={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_BG_COLORS:{doc:"# the colors new background pictures are drawn in: tone tints a picture in one color of its palette, original keeps its own — preview switches each picture later (default tone)",default:"tone"},TTHEME_WARP_FAST:{doc:"# Warp tab switches: on keeps Warp rereading its settings while it is in front with tabs of different palettes, so the tab you switch to shows its palette in about 0.2 s instead of 0.6 s — about 8% CPU meanwhile; off leaves it to Warp (default on)",default:"on"},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 Us(e){return Oi[e]?.default}function Rl(e,t){let n=`: \${${e}:=${t}}`;return Us(e)===t?`# ${n}`:n}function Gp(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function Iv(e,t){if(Gp(t).test(e))return e;let n=Oi[t];return`${e.replace(/\n*$/,`
346
+ ${n}`}function Vn(t){let e=t.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(e===t)return t;return e.trim()===""?"":e.replace(/\n*$/,`
347
+ `)}function Zn(t,e){let n=t.replace(Ri,"");return new RegExp(String.raw`^[ \t]*${e}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function bb(t){return`source ${t}/ttheme.zsh`}var F2="# ttheme settings — uncomment a line to change it; exported variables win over this file",Pi={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_BG_COLORS:{doc:"# the colors new background pictures are drawn in: tone tints a picture in one color of its palette, original keeps its own — preview switches each picture later (default tone)",default:"tone"},TTHEME_WARP_FAST:{doc:"# Warp tab switches: on keeps Warp rereading its settings while it is in front with tabs of different palettes, so the tab you switch to shows its palette in about 0.2 s instead of 0.6 s — about 8% CPU meanwhile; off leaves it to Warp (default on)",default:"on"},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 To(t){return Pi[t]?.default}function Fl(t,e){let n=`: \${${t}:=${e}}`;return To(t)===e?`# ${n}`:n}function wb(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function x2(t,e){if(wb(e).test(t))return t;let n=Pi[e];return`${t.replace(/\n*$/,`
345
348
  `)}
346
349
  ${n.doc}
347
- ${Rl(t,n.default)}
348
- `}var Ra=Object.keys(Oi),Nv=8;function Oa(e,t){let n="";try{n=vv(Mv(e,"ttheme","config.zsh"),"utf8")}catch{}return(new RegExp(String.raw`^: \$\{${t}:=([^}\n]*)\}`,"m").exec(n)?.[1]??Oi[t].default).replace(/^(["'])(.*)\1$/,"$2")}function Lr(e){let t=Number(Oa(e,"TTHEME_BG_BLUR"));return Number.isFinite(t)?Math.min(Nv,Math.max(0,t)):0}function Fa(e){return Oa(e,"TTHEME_BG_COLORS")==="original"?"original":"tone"}function Ol(){let e=Object.entries(Oi).map(([t,n])=>`${n.doc}
349
- ${Rl(t,n.default)}`);return`${[Sv,...e].join(`
350
+ ${Fl(e,n.default)}
351
+ `}var Ia=Object.keys(Pi),L2=8;function Oa(t,e){let n="";try{n=P2(H2(t,"ttheme","config.zsh"),"utf8")}catch{}return(new RegExp(String.raw`^: \$\{${e}:=([^}\n]*)\}`,"m").exec(n)?.[1]??Pi[e].default).replace(/^(["'])(.*)\1$/,"$2")}function Qn(t){let e=Number(Oa(t,"TTHEME_BG_BLUR"));return Number.isFinite(e)?Math.min(L2,Math.max(0,e)):0}function Na(t){return Oa(t,"TTHEME_BG_COLORS")==="original"?"original":"tone"}function xl(){let t=Object.entries(Pi).map(([e,n])=>`${n.doc}
352
+ ${Fl(e,n.default)}`);return`${[F2,...t].join(`
350
353
 
351
354
  `)}
352
- `}function Ta(e,t,n){let r=Rl(t,n),i=Gp(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
355
+ `}function Ra(t,e,n){let r=Fl(e,n),i=wb(e);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
353
356
  `)}
354
357
  ${r}
355
- `}function Wp(e){if(e==="")return Ol();return Object.keys(Oi).reduce(Iv,e)}var Up=/["$`\\]/;function Pv(e){return e.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Fl(e,t,n=[],r={}){for(let l of e)for(let f of[l.name,l.group,l.native??"",...l.nativeNames??[],l.ansiSource])if(Up.test(f))throw Error(`${l.name}: "${f}" contains a character that breaks zsh quoting`);let i=Math.max(0,...e.map((l)=>l.name.length)),s=(l,f)=>` ${l.name.padEnd(i)} "${f}"`,o=(l)=>l.map((f)=>f.name).join(" "),a=Xe(e),u=(l)=>`'${l.replaceAll("'","'\\''")}'`,c=Gs.filter((l)=>l.section!=="setup"&&!l.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${et.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(" ")})`,...Object.keys(r).length>0?["","# what a wired terminal's adapter needs to know of it (src/terminals/)",...Object.entries(r).map(([l,f])=>`typeset -g ${l}=${u(f)}`)]:[],"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${c.map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_TAB_VERBS=(${c.filter((l)=>l.section==="tab").map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${c.filter((l)=>l.shell).map((l)=>l.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...c.map((l)=>` ${l.name} ${u(l.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...c.map((l)=>` ${l.name} ${u(l.about)}`),")",`typeset -g TTHEME_HELP=${u(Ws(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(Ws(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Ra.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Ol().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((l)=>s(l,[l.background,l.foreground,l.cursor,l.selection,...l.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(a)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Tr(a))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((l)=>s(l,l.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((l)=>l.catalog).map((l)=>s(l,l.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((l)=>l.native).map((l)=>s(l,l.native??"")),")","","# the character's names in its original language, |-separated, and as its booru tag spells it: preview searches both","typeset -gA TTHEME_NATIVE_NAMES=(",...e.filter((l)=>l.nativeNames).map((l)=>s(l,(l.nativeNames??[]).join("|"))),")","typeset -gA TTHEME_CHARACTER=(",...e.filter((l)=>l.booru&&!Up.test(l.booru)).map((l)=>s(l,Pv(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${Gt.map((l)=>l.name).join(" ")})`,...Gt.flatMap((l,f)=>[`typeset -ga TTHEME_SCENE_${f+1}=(`,...l.lines.map((d)=>` ${u(d)}`),")"]),"","# each booru's ANSI color, which marks a link to one of its posts",`typeset -gA TTHEME_SITE_ANSI=(${X.map((l)=>`${l.name} ${l.ansi}`).join(" ")})`,"","# the terminals that open OSC 8 links (src/terminal.ts)",`typeset -ga TTHEME_LINKS=(${Object.entries(zt).flatMap(([l,f])=>f.links?[l]:[]).join(" ")})`,"","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...e.map((l)=>s(l,$a(l).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...e.map((l)=>s(l,l.ansiSource)),")",""].join(`
356
- `)}var Tl={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Fl(e.map(Jt))}]}};import{createHash as Rv}from"node:crypto";var Ov=["black","red","green","yellow","blue","magenta","cyan","white"];function jp(e,t){return[` ${e}:`,...Ov.map((n,r)=>` ${n}: "${t[r]}"`)]}function Fv(e,t,n){let r=Rv("sha1");for(let i of t)r.update(i);return`${_(e)}.${r.digest("hex").slice(0,8)}.${n}`}function Kp(e,t,n){let r=2166136261;for(let i of Buffer.from(`${t}
357
- ${n.toLowerCase()}`,"utf8"))r=Math.imul(r^i,16777619)>>>0;return`${_(e)}.${r.toString(16).padStart(8,"0")}.png`}function js(e,t){return t?Fv(e,[t.image,String(Bp(t))],"yaml"):`${_(e)}.yaml`}function Bp(e){return Math.max(0,Math.min(100,Math.round(e.opacity*100)))}function Ks(e,t){return[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${ze(e.background)<0.18?"darker":"lighter"}`,...t?["background_image:",` path: "${t.image}"`,` opacity: ${Bp(t)}`]:[],"terminal_colors:",...jp("normal",e.ansi.slice(0,8)),...jp("bright",e.ansi.slice(8,16)),""].join(`
358
- `)}var Hl={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){return[{path:`warp/themes/${js(e.name)}`,content:Ks(e)}]}};var Jp=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,xl={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${_(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 = ${Jp(e.ansi.slice(0,8))}`,`brights = ${Jp(e.ansi.slice(8,16))}`,""].join(`
359
- `);return[{path:`wezterm/colors/${_(e.name)}.toml`,content:t}]}},Fi=(e)=>JSON.stringify(e);function qp(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Fi(e.path)}`,`local COLORS = ${Fi(e.colors)}`,`local BACKGROUNDS = ${Fi(e.backgrounds)}`,`local STARTUP = ${e.startup?Fi(_(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Fi(t.name)}] = ${Fi(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 function framed(window, view)"," local color, image, opacity, W, H, w, h, x, y, at ="," view:match('^([^|]*)|([^|]*)|([^|]*)|(%d+)|(%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%d)$')"," if not image or image == '' or tonumber(W) == 0 or tonumber(H) == 0 then"," return nil, 'none'"," end"," local d = window:get_dimensions()"," local k = math.max(d.pixel_width / W, d.pixel_height / H)"," local n = tonumber(at) - 1"," local ax, ay = n % 3, n // 3"," local px = function(n) return string.format('%.2fpx', n) end"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = image },"," opacity = tonumber(opacity) or 1,"," width = px(w * k),"," height = px(h * k),"," horizontal_align = 'Left',"," vertical_align = 'Top',"," horizontal_offset = px(ax * (d.pixel_width - W * k) / 2 + x * k),"," vertical_offset = px(ay * (d.pixel_height - H * k) / 2 + y * k),"," repeat_x = 'NoRepeat',"," repeat_y = 'NoRepeat',"," },"," }, table.concat({ view, d.pixel_width, d.pixel_height }, '|')","end","","local shown = {}","","local function show(window, pane)"," local vars = pane:get_user_vars()"," local id = window:window_id()"," local background, key"," if vars.ttheme_view and vars.ttheme_view ~= '' then"," background, key = framed(window, vars.ttheme_view)"," elseif vars.ttheme_shown and vars.ttheme_shown ~= '' then"," background, key = layers(vars.ttheme_shown)"," elseif shown[id] == nil then"," return"," end"," 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' or name == 'ttheme_view' 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(`
360
- `)}var Vp=["black","red","green","yellow","blue","purple","cyan","white"];function zp(e){return{name:_(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Vp.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(Vp.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function Al(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:_(n)}]}:{},schemes:e.map(zp)};return`${JSON.stringify(r,null,2)}
361
- `}var Ll={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${_(e.name)}.json`,content:`${JSON.stringify(zp(e),null,2)}
362
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Al(e)}]}};function ar(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}import{execFileSync as Tv}from"node:child_process";import{existsSync as Yp,readdirSync as Hv,readFileSync as xv}from"node:fs";import{join as Qp}from"node:path";function Ie(e){return Yp(e)?xv(e,"utf8"):""}function De(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Ha(e){return[...new Set(e.split(`
363
- `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function fn(e,t){let n=Ie(e),r=t(n);return r===n?[]:[{file:e,content:r}]}function Bs(e){return process.env.XDG_DATA_HOME??Qp(e,".local","share")}function xa(e){return Yp(e)?Hv(e).flatMap((t)=>t.startsWith(_(""))?[Qp(e,t)]:[]):[]}function Cl(e,t){if(!e.shelf)return[];let n=`${[e.id,e.shelf.from].filter(Boolean).join("/")}/`;return(e.emitter.emit?.(t)??[]).flatMap((r)=>{let i=r.path.startsWith(n)?r.path.slice(n.length):"";return i!==""&&!i.includes("/")?[{file:i,content:r.content}]:[]})}function Cr(){return{platform:process.platform,env:process.env,run:(e,t)=>{try{return Tv(e,[...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as Zp}from"node:fs";import{join as La}from"node:path";function Av(e){let t=e.replace(Ri,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var Lv=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Xp=/^[ \t]*\[/m,Dp=/^[ \t]*import[ \t]*=/m,Cv=/^[ \t]*general[ \t]*[.=]/m;function _v(e){return e?`[general]
364
- import = ["${e}"]`:""}function _l(e,t){let n=e.replace(Ri,""),r=Lv.exec(n);if(!r){let u=n.search(Xp),c=u<0?n:n.slice(0,u);if(Cv.test(n)||Dp.test(c))return;return lr(e,_v(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(Xp);if(Dp.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
358
+ `}function $b(t){if(t==="")return xl();return Object.keys(Pi).reduce(x2,t)}var kb=/["$`\\]/;function T2(t){return t.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Ll(t,e,n=[],r={}){for(let l of t)for(let f of[l.name,l.group,l.native??"",...l.nativeNames??[],l.ansiSource])if(kb.test(f))throw Error(`${l.name}: "${f}" contains a character that breaks zsh quoting`);let i=Math.max(0,...t.map((l)=>l.name.length)),o=(l,f)=>` ${l.name.padEnd(i)} "${f}"`,s=(l)=>l.map((f)=>f.name).join(" "),a=Mt(t),c=(l)=>`'${l.replaceAll("'","'\\''")}'`,u=xo.filter((l)=>l.section!=="setup"&&!l.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${Ot.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${e??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,...Object.keys(r).length>0?["","# what a wired terminal's adapter needs to know of it (src/terminals/)",...Object.entries(r).map(([l,f])=>`typeset -g ${l}=${c(f)}`)]:[],"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${u.map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_TAB_VERBS=(${u.filter((l)=>l.section==="tab").map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((l)=>l.shell).map((l)=>l.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((l)=>` ${l.name} ${c(l.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((l)=>` ${l.name} ${c(l.about)}`),")",`typeset -g TTHEME_HELP=${c(Lo(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${c(Lo(!0,!0))}`,"","# the screens the bare ttheme switches between (src/hub.ts): the exit status of a screen run by the CLI says where it went",`typeset -ga TTHEME_HUB_TABS=(${Jn.map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_HUB_TITLES=(${Jn.map((l)=>l.title).join(" ")})`,`typeset -gi TTHEME_HUB_CLOSED=${Sa} TTHEME_HUB_SWITCH=${nb}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Ia.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${xl().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((l)=>o(l,[l.background,l.foreground,l.cursor,l.selection,...l.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(a)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${s(Nr(a))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((l)=>o(l,l.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=(",...t.filter((l)=>l.catalog).map((l)=>o(l,l.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((l)=>l.native).map((l)=>o(l,l.native??"")),")","","# the character's names in its original language, |-separated, and as its booru tag spells it: preview searches both","typeset -gA TTHEME_NATIVE_NAMES=(",...t.filter((l)=>l.nativeNames).map((l)=>o(l,(l.nativeNames??[]).join("|"))),")","typeset -gA TTHEME_CHARACTER=(",...t.filter((l)=>l.booru&&!kb.test(l.booru)).map((l)=>o(l,T2(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${he.map((l)=>l.name).join(" ")})`,...he.flatMap((l,f)=>[`typeset -ga TTHEME_SCENE_${f+1}=(`,...l.lines.map((d)=>` ${c(d)}`),")"]),"","# each booru's ANSI color, which marks a link to one of its posts",`typeset -gA TTHEME_SITE_ANSI=(${q.map((l)=>`${l.name} ${l.ansi}`).join(" ")})`,"","# the terminals that open OSC 8 links (src/terminal.ts)",`typeset -ga TTHEME_LINKS=(${Object.entries(Ne).flatMap(([l,f])=>f.links?[l]:[]).join(" ")})`,"","# the six colors a list row shows: foreground, the signature, then red and green","typeset -gA TTHEME_SWATCH=(",...t.map((l)=>o(l,da(l).join(" "))),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((l)=>o(l,l.ansiSource)),")",""].join(`
359
+ `)}var Tl={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:Ll(t.map(de))}]}};import{execFileSync as A2}from"node:child_process";import{existsSync as yb,readdirSync as C2,readFileSync as j2}from"node:fs";import{join as vb}from"node:path";function it(t){return yb(t)?j2(t,"utf8"):""}function It(t,e){return t.startsWith(`${e}/`)?`~${t.slice(e.length)}`:t}function Pa(t){return[...new Set(t.split(`
360
+ `).map((e)=>e.split(/[ =]/)[0]))].join(", ")}function Ke(t,e){let n=it(t),r=e(n);return r===n?[]:[{file:t,content:r}]}function Ao(t){return process.env.XDG_DATA_HOME??vb(t,".local","share")}function Ha(t){return yb(t)?C2(t).flatMap((e)=>e.startsWith(T(""))?[vb(t,e)]:[]):[]}function Al(t,e){if(!t.shelf)return[];let n=`${[t.id,t.shelf.from].filter(Boolean).join("/")}/`;return(t.emitter.emit?.(e)??[]).flatMap((r)=>{let i=r.path.startsWith(n)?r.path.slice(n.length):"";return i!==""&&!i.includes("/")?[{file:i,content:r.content}]:[]})}function Fr(){return{platform:process.platform,env:process.env,run:(t,e)=>{try{return A2(t,[...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as Tb}from"node:fs";import{join as xa}from"node:path";function Xn(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var G2=["black","red","green","yellow","blue","magenta","cyan","white"];function Eb(t,e){return[t,...G2.map((n,r)=>`${n} = '${e[r]}'`),""].join(`
361
+ `)}var Cl={id:"alacritty",limits:"no runtime color API (OSC only)",emit(t){let e=[...Xn(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",Eb("[colors.normal]",t.ansi.slice(0,8)),Eb("[colors.bright]",t.ansi.slice(8,16))].join(`
362
+ `);return[{path:`alacritty/themes/${T(t.name)}.toml`,content:e}]}};var jl={id:"ghostty",emit(t){let e=[...Xn(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((n,r)=>`palette = ${r}=${n}`),"","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
363
+ `);return[{path:`ghostty/themes/${T(t.name)}`,content:e}]}};function tr(t){let[e,n,r]=nt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":e/255}}function Mb(t){return{...Object.fromEntries(t.ansi.map((e,n)=>[`Ansi ${n} Color`,tr(e)])),"Background Color":tr(t.background),"Bold Color":tr(t.foreground),"Cursor Color":tr(t.cursor),"Cursor Text Color":tr(t.background),"Foreground Color":tr(t.foreground),"Selected Text Color":tr(t.foreground),"Selection Color":tr(t.selectionBackground)}}function Sb(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function Ib(t,e,n,r,i=!1){let o=(c,u)=>({Name:`ttheme · ${u}`,Guid:T(u),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,...Sb(e.get(c.name)),...Mb(c)}),s={Name:"ttheme · default",Guid:T("default"),"Dynamic Profile Parent GUID":r,...Sb(void 0)},a=[...n?[o(n,"default")]:i&&r?[s]:[],...t.map((c)=>o(c,c.name))];return`${JSON.stringify({Profiles:a},null,2)}
364
+ `}function U2(t,e){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(e).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
365
+ `)}var Gl={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let e=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(Mb(t)).map(([n,r])=>U2(n,r)),"</dict>","</plist>",""].join(`
366
+ `);return[{path:`iterm2/${T(t.name)}.itermcolors`,content:e}]}};var Ul={id:"kitty",emit(t){let e=[...Xn(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
367
+ `);return[{path:`kitty/themes/${T(t.name)}.conf`,content:e}]}};function Ob(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette.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(`
368
+ `)}function mn(t,e){return[`[${t}]`,`Color=${nt(e).join(",")}`,""]}function W2(t){let e=(n)=>Ht(n,t.background,0.5);return[...Xn(t),"",...mn("Background",t.background),...mn("BackgroundFaint",t.background),...mn("BackgroundIntense",t.background),...t.ansi.slice(0,8).flatMap((n,r)=>[...mn(`Color${r}`,n),...mn(`Color${r}Faint`,e(n)),...mn(`Color${r}Intense`,t.ansi[r+8])]),...mn("Foreground",t.foreground),...mn("ForegroundFaint",e(t.foreground)),...mn("ForegroundIntense",t.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${t.name}`,"Opacity=1","Wallpaper=",""].join(`
369
+ `)}var Wl={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(t){return[{path:`konsole/${T(t.name)}.colorscheme`,content:W2(t)}]}};function _2(t){let[e]=t;if(!e)throw Error("manifest needs at least one theme");return{...vi(),palettes:t.map(de)}}var _l={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(_2(t),null,2)}
370
+ `}]}};import{createHash as B2}from"node:crypto";var z2=["black","red","green","yellow","blue","magenta","cyan","white"];function Nb(t,e){return[` ${t}:`,...z2.map((n,r)=>` ${n}: "${e[r]}"`)]}function K2(t,e,n){let r=B2("sha1");for(let i of e)r.update(i);return`${T(t)}.${r.digest("hex").slice(0,8)}.${n}`}function Rb(t,e,n){let r=2166136261;for(let i of Buffer.from(`${e}
371
+ ${n.toLowerCase()}`,"utf8"))r=Math.imul(r^i,16777619)>>>0;return`${T(t)}.${r.toString(16).padStart(8,"0")}.png`}function Co(t,e){return e?K2(t,[e.image,String(Pb(e))],"yaml"):`${T(t)}.yaml`}function Pb(t){return Math.max(0,Math.min(100,Math.round(t.opacity*100)))}function jo(t,e){return[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${yt(t.background)<0.18?"darker":"lighter"}`,...e?["background_image:",` path: "${e.image}"`,` opacity: ${Pb(e)}`]:[],"terminal_colors:",...Nb("normal",t.ansi.slice(0,8)),...Nb("bright",t.ansi.slice(8,16)),""].join(`
372
+ `)}var Bl={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(t){return[{path:`warp/themes/${Co(t.name)}`,content:jo(t)}]}};var Hb=(t)=>`[${t.map((e)=>`"${e}"`).join(", ")}]`,zl={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(t){let e=["[metadata]",`name = "${T(t.name)}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${Hb(t.ansi.slice(0,8))}`,`brights = ${Hb(t.ansi.slice(8,16))}`,""].join(`
373
+ `);return[{path:`wezterm/colors/${T(t.name)}.toml`,content:e}]}},Hi=(t)=>JSON.stringify(t);function Fb(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Hi(t.path)}`,`local COLORS = ${Hi(t.colors)}`,`local BACKGROUNDS = ${Hi(t.backgrounds)}`,`local STARTUP = ${t.startup?Hi(T(t.startup)):"nil"}`,"local PALETTES = {",...t.palettes.map((e)=>` [${Hi(e.name)}] = ${Hi(e.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. ((palette: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 function framed(window, view)"," local color, image, opacity, W, H, w, h, x, y, at ="," view:match('^([^|]*)|([^|]*)|([^|]*)|(%d+)|(%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%d)$')"," if not image or image == '' or tonumber(W) == 0 or tonumber(H) == 0 then"," return nil, 'none'"," end"," local d = window:get_dimensions()"," local k = math.max(d.pixel_width / W, d.pixel_height / H)"," local n = tonumber(at) - 1"," local ax, ay = n % 3, n // 3"," local px = function(n) return string.format('%.2fpx', n) end"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = image },"," opacity = tonumber(opacity) or 1,"," width = px(w * k),"," height = px(h * k),"," horizontal_align = 'Left',"," vertical_align = 'Top',"," horizontal_offset = px(ax * (d.pixel_width - W * k) / 2 + x * k),"," vertical_offset = px(ay * (d.pixel_height - H * k) / 2 + y * k),"," repeat_x = 'NoRepeat',"," repeat_y = 'NoRepeat',"," },"," }, table.concat({ view, d.pixel_width, d.pixel_height }, '|')","end","","local shown = {}","","local function show(window, pane)"," local vars = pane:get_user_vars()"," local id = window:window_id()"," local background, key"," if vars.ttheme_view and vars.ttheme_view ~= '' then"," background, key = framed(window, vars.ttheme_view)"," elseif vars.ttheme_shown and vars.ttheme_shown ~= '' then"," background, key = layers(vars.ttheme_shown)"," elseif shown[id] == nil then"," return"," end"," 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' or name == 'ttheme_view' 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(`
374
+ `)}var xb=["black","red","green","yellow","blue","purple","cyan","white"];function Lb(t){return{name:T(t.name),background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(xb.map((e,n)=>[e,t.ansi[n]])),...Object.fromEntries(xb.map((e,n)=>[`bright${e[0]?.toUpperCase()}${e.slice(1)}`,t.ansi[n+8]]))}}function Kl(t,e,n){let r={...e&&n?{profiles:[{updates:e,colorScheme:T(n)}]}:{},schemes:t.map(Lb)};return`${JSON.stringify(r,null,2)}
375
+ `}var ql={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${T(t.name)}.json`,content:`${JSON.stringify(Lb(t),null,2)}
376
+ `}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:Kl(t)}]}};function q2(t){let e=t.replace(Ri,"");return/^[ \t]*\[colors[\].]/m.test(e)||/^[ \t]*colors[ \t]*[.=]/m.test(e)}var J2=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Ab=/^[ \t]*\[/m,Cb=/^[ \t]*import[ \t]*=/m,Y2=/^[ \t]*general[ \t]*[.=]/m;function D2(t){return t?`[general]
377
+ import = ["${t}"]`:""}function Jl(t,e){let n=t.replace(Ri,""),r=J2.exec(n);if(!r){let c=n.search(Ab),u=c<0?n:n.slice(0,c);if(Y2.test(n)||Cb.test(u))return;return Dn(t,D2(e))}let i=r.index+r[0].length,o=n.slice(i),s=o.search(Ab);if(Cb.test(s<0?o:o.slice(0,s)))return;let a=e?`import = ["${e}"]
365
378
  `:"";return`${n.slice(0,i)}
366
- ${Nl}
367
- ${a}${Pl}${s}`}function Aa(e){return La(e,"alacritty","alacritty.toml")}function eb(e){return La(e.configHome,"alacritty","themes")}function Gv(e,t){return t?La(e,"alacritty","themes",`${_(t)}.toml`):void 0}var Gl={id:"alacritty",name:"Alacritty",emitter:wl,shelf:{from:"themes",dir:eb},offered:()=>!0,present:(e)=>Zp(La(e.configHome,"alacritty")),sync(e,t){t.themes(Gl);let n=Aa(e.configHome),r=_l(Ie(n),Gv(e.configHome,e.startup));if(r!==void 0)t.wire(n,r)},plan(e){let t=Aa(e.configHome);return _l(Ie(t),void 0)!==void 0?[`Edit ${De(t,e.home)} — a ttheme block: general.import`]:[]},notes(e){let t=Aa(e.configHome),n=Ie(t);return[...Zp(t)&&_l(n,void 0)===void 0?[`${t} already imports files under [general] — ttheme left it alone; add ${eb(e)}/<palette>.toml to that import list yourself`]:[],...Av(n)?[`${De(t,e.home)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`]:[]]},next:()=>["Alacritty Reloads its config by itself"],unwire:(e)=>({edits:fn(Aa(e.configHome),fr),removals:[],touches:[]})};import{existsSync as Wv}from"node:fs";import{join as _a}from"node:path";function Uv(e,t,n=""){let r=[];if(!dr(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!dr(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${_(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
368
- `)}function Ca(e){return _a(e,"ghostty","config")}function tb(e,t,n){return Uv(_a(e.configHome,"ttheme"),t,n)}var Wl={id:"ghostty",name:"Ghostty",emitter:$l,shelf:{from:"themes",dir:(e)=>_a(e.configHome,"ghostty","themes")},offered:()=>!0,present:(e)=>Wv(_a(e.configHome,"ghostty")),sync(e,t){t.themes(Wl);let n=Ca(e.configHome),r=Ie(n);t.wire(n,lr(r,tb(e,e.startup,r)))},plan(e){let t=Ca(e.configHome);return[`Edit ${De(t,e.home)} — a ttheme block: ${Ha(tb(e,e.startup,Ie(t)))}`]},notes(e){let t=Ca(e.configHome);return dr(Ie(t),"command")?[`${De(t,e.home)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`]:[]},next:()=>["Restart Ghostty New tabs pick up its config"],unwire:(e)=>({edits:fn(Ca(e.configHome),fr),removals:[],touches:[]})};import{existsSync as nb}from"node:fs";import{join as sb}from"node:path";var Ul="ttheme-default";function Js(e){return sb(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ob(e){return e.itermBase!==void 0&&e.palettes.length>0}function rb(e){let t=Se(e.configHome),n=new Map;for(let i of e.themes){let s=Os(t,i.name,e.home);if(s)n.set(i.name,s)}let r=new Set(Xe(e.entries).map((i)=>i.name));return Sp(e.themes.filter((i)=>r.has(i.name)),n,e.themes.find((i)=>i.name===e.startup),e.state.itermBase,ob(e.state))}function ab(e){return e.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function ib(e){return e.run("defaults",["read",ab(e),"Default Bookmark Guid"])||void 0}var jv={key:"itermBase",profile:()=>"ttheme · default",base(e){let t=ib(e.host);return t&&!t.startsWith("ttheme-")?{...e.state,itermBase:t}:e.state},point(e,t){let n=ib(e.host),r=e.startup?t||n===Ul?Ul:void 0:n===Ul&&!ob(e.state)?e.state.itermBase:void 0;if(!r||r===n)return;return e.host.run("defaults",["write",ab(e.host),"Default Bookmark Guid","-string",r]),{restart:Boolean(e.host.run("pgrep",["-x","iTerm2"]))}}},ub={id:"iterm2",name:"iTerm2",emitter:kl,bakes:!0,offered:(e,t)=>t.platform==="darwin",present:(e)=>nb(sb(e.home,"Library","Application Support","iTerm2")),sync(e,t){t.write(Js(e.home),rb(e))},pictures(e,t){t.write(Js(e.home),rb(e))},plan:(e)=>[`Write ${De(Js(e.home),e.home)} — a "ttheme · <palette>" profile per palette`],notes:()=>[],next(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e.startup)n.push(t?.restart?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e.startup}`:`iTerm2 default "ttheme · default" wears ${e.startup} and follows \`ttheme default\``);return n},unwire:(e)=>({edits:[],removals:nb(Js(e.home))?[Js(e.home)]:[],touches:[]}),defaults:jv};import{existsSync as Kv}from"node:fs";import{join as Wa}from"node:path";function cb(e,t,n=""){return[...e?[`include themes/${_(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!dr(n,r.split(" ")[0]))].join(`
369
- `)}function Ga(e){return Wa(e,"kitty","kitty.conf")}function jl(e){return Wa(e,"ttheme","kitty.py")}function lb(e){return Wa(e.configHome,"kitty","themes")}var Kl={id:"kitty",name:"kitty",emitter:yl,shelf:{from:"themes",dir:lb},offered:()=>!0,present:(e)=>Kv(Wa(e.configHome,"kitty")),sync(e,t){t.themes(Kl),t.write(jl(e.configHome),Ip({themes:lb(e),backgrounds:Se(e.configHome)}));let n=Ga(e.configHome),r=Ie(n);t.wire(n,lr(r,cb(e.startup,jl(e.configHome),r)))},plan(e){let t=Ga(e.configHome),n=cb(e.startup,jl(e.configHome),Ie(t));return[`Edit ${De(t,e.home)} — a ttheme block: ${Ha(n)}`]},notes(e){let t=Ie(Ga(e.configHome));return dr(t,"window_logo_scale")||dr(t,"window_logo_alpha")?["kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them"]:[]},next:()=>["New kitty window Pictures follow it — kitty reloads its colors by itself"],unwire:(e)=>({edits:fn(Ga(e.configHome),fr),removals:[],touches:[]})};import{existsSync as ja}from"node:fs";import{isAbsolute as Bv,join as Vs}from"node:path";function Ua(e){return Vs(Bs(e),"konsole")}function qs(e){return Vs(e,"konsolerc")}function fb(e){return`${_(e)}.profile`}function zs(e){return`ttheme · ${e}`}function db(e,t){let n=e.findIndex((i)=>i.trim()===`[${t}]`);if(n<0)return;let r=e.findIndex((i,s)=>s>n&&i.trimStart().startsWith("["));return[n,r<0?e.length:r]}function Bl(e){return new RegExp(String.raw`^\s*${e}\s*=`)}function hr(e,t,n){let r=e.split(`
370
- `),i=db(r,t);return(i&&r.slice(i[0]+1,i[1]).find((o)=>Bl(n).test(o)))?.replace(Bl(n),"").trim()}function hb(e,t){let n=e.split(`
371
- `),r=db(n,"Desktop Entry"),i=t===void 0?[]:[`DefaultProfile=${t}`];if(!r)return t===void 0?e:`${e===""?"":e.replace(/\n*$/,`
379
+ ${Pl}
380
+ ${a}${Hl}${o}`}function Fa(t){return xa(t,"alacritty","alacritty.toml")}function jb(t){return xa(t.configHome,"alacritty","themes")}function V2(t,e){return e?xa(t,"alacritty","themes",`${T(e)}.toml`):void 0}var Yl={id:"alacritty",name:"Alacritty",emitter:Cl,shelf:{from:"themes",dir:jb},offered:()=>!0,present:(t)=>Tb(xa(t.configHome,"alacritty")),sync(t,e){e.themes(Yl);let n=Fa(t.configHome),r=Jl(it(n),V2(t.configHome,t.startup));if(r!==void 0)e.wire(n,r)},plan(t){let e=Fa(t.configHome);return Jl(it(e),void 0)!==void 0?[`Edit ${It(e,t.home)} — a ttheme block: general.import`]:[]},notes(t){let e=Fa(t.configHome),n=it(e);return[...Tb(e)&&Jl(n,void 0)===void 0?[`${e} already imports files under [general] — ttheme left it alone; add ${jb(t)}/<palette>.toml to that import list yourself`]:[],...q2(n)?[`${It(e,t.home)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`]:[]]},next:()=>["Alacritty Reloads its config by itself"],unwire:(t)=>({edits:Ke(Fa(t.configHome),Vn),removals:[],touches:[]})};import{existsSync as Z2}from"node:fs";import{join as Ta}from"node:path";function Q2(t,e,n=""){let r=[];if(!Zn(n,"command")){if(r.push(`command = ${t}/launch-tab.zsh`),!Zn(n,"shell-integration"))r.push("shell-integration = zsh")}if(e)r.push(`theme = ${T(e)}`);return r.push(`config-file = ?${t}/backgrounds/shown.conf`),r.join(`
381
+ `)}function La(t){return Ta(t,"ghostty","config")}function Gb(t,e,n){return Q2(Ta(t.configHome,"ttheme"),e,n)}var Dl={id:"ghostty",name:"Ghostty",emitter:jl,shelf:{from:"themes",dir:(t)=>Ta(t.configHome,"ghostty","themes")},offered:()=>!0,present:(t)=>Z2(Ta(t.configHome,"ghostty")),sync(t,e){e.themes(Dl);let n=La(t.configHome),r=it(n);e.wire(n,Dn(r,Gb(t,t.startup,r)))},plan(t){let e=La(t.configHome);return[`Edit ${It(e,t.home)} — a ttheme block: ${Pa(Gb(t,t.startup,it(e)))}`]},notes(t){let e=La(t.configHome);return Zn(it(e),"command")?[`${It(e,t.home)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`]:[]},next:()=>["Restart Ghostty New tabs pick up its config"],unwire:(t)=>({edits:Ke(La(t.configHome),Vn),removals:[],touches:[]})};import{existsSync as Ub}from"node:fs";import{join as Bb}from"node:path";var Vl="ttheme-default";function Go(t){return Bb(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function zb(t){return t.itermBase!==void 0&&t.palettes.length>0}function Wb(t){let e=X(t.configHome),n=new Map;for(let i of t.themes){let o=Eo(e,i.name,t.home);if(o)n.set(i.name,o)}let r=new Set(Mt(t.entries).map((i)=>i.name));return Ib(t.themes.filter((i)=>r.has(i.name)),n,t.themes.find((i)=>i.name===t.startup),t.state.itermBase,zb(t.state))}function Kb(t){return t.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function _b(t){return t.run("defaults",["read",Kb(t),"Default Bookmark Guid"])||void 0}var X2={key:"itermBase",profile:()=>"ttheme · default",base(t){let e=_b(t.host);return e&&!e.startsWith("ttheme-")?{...t.state,itermBase:e}:t.state},point(t,e){let n=_b(t.host),r=t.startup?e||n===Vl?Vl:void 0:n===Vl&&!zb(t.state)?t.state.itermBase:void 0;if(!r||r===n)return;return t.host.run("defaults",["write",Kb(t.host),"Default Bookmark Guid","-string",r]),{restart:Boolean(t.host.run("pgrep",["-x","iTerm2"]))}}},qb={id:"iterm2",name:"iTerm2",emitter:Gl,bakes:!0,offered:(t,e)=>e.platform==="darwin",present:(t)=>Ub(Bb(t.home,"Library","Application Support","iTerm2")),sync(t,e){e.write(Go(t.home),Wb(t))},pictures(t,e){e.write(Go(t.home),Wb(t))},plan:(t)=>[`Write ${It(Go(t.home),t.home)} — a "ttheme · <palette>" profile per palette`],notes:()=>[],next(t,e){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(t.startup)n.push(e?.restart?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${t.startup}`:`iTerm2 default "ttheme · default" wears ${t.startup} and follows \`ttheme default\``);return n},unwire:(t)=>({edits:[],removals:Ub(Go(t.home))?[Go(t.home)]:[],touches:[]}),defaults:X2};import{existsSync as tI}from"node:fs";import{join as Ca}from"node:path";function Jb(t,e,n=""){return[...t?[`include themes/${T(t)}.conf`]:[],`watcher ${e}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!Zn(n,r.split(" ")[0]))].join(`
382
+ `)}function Aa(t){return Ca(t,"kitty","kitty.conf")}function Zl(t){return Ca(t,"ttheme","kitty.py")}function Yb(t){return Ca(t.configHome,"kitty","themes")}var Ql={id:"kitty",name:"kitty",emitter:Ul,shelf:{from:"themes",dir:Yb},offered:()=>!0,present:(t)=>tI(Ca(t.configHome,"kitty")),sync(t,e){e.themes(Ql),e.write(Zl(t.configHome),Ob({themes:Yb(t),backgrounds:X(t.configHome)}));let n=Aa(t.configHome),r=it(n);e.wire(n,Dn(r,Jb(t.startup,Zl(t.configHome),r)))},plan(t){let e=Aa(t.configHome),n=Jb(t.startup,Zl(t.configHome),it(e));return[`Edit ${It(e,t.home)} — a ttheme block: ${Pa(n)}`]},notes(t){let e=it(Aa(t.configHome));return Zn(e,"window_logo_scale")||Zn(e,"window_logo_alpha")?["kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them"]:[]},next:()=>["New kitty window Pictures follow it — kitty reloads its colors by itself"],unwire:(t)=>({edits:Ke(Aa(t.configHome),Vn),removals:[],touches:[]})};import{existsSync as Ga}from"node:fs";import{isAbsolute as eI,join as Wo}from"node:path";function ja(t){return Wo(Ao(t),"konsole")}function Uo(t){return Wo(t,"konsolerc")}function Db(t){return`${T(t)}.profile`}function _o(t){return`ttheme · ${t}`}function Vb(t,e){let n=t.findIndex((i)=>i.trim()===`[${e}]`);if(n<0)return;let r=t.findIndex((i,o)=>o>n&&i.trimStart().startsWith("["));return[n,r<0?t.length:r]}function Xl(t){return new RegExp(String.raw`^\s*${t}\s*=`)}function er(t,e,n){let r=t.split(`
383
+ `),i=Vb(r,e);return(i&&r.slice(i[0]+1,i[1]).find((s)=>Xl(n).test(s)))?.replace(Xl(n),"").trim()}function Zb(t,e){let n=t.split(`
384
+ `),r=Vb(n,"Desktop Entry"),i=e===void 0?[]:[`DefaultProfile=${e}`];if(!r)return e===void 0?t:`${t===""?"":t.replace(/\n*$/,`
372
385
 
373
386
  `)}[Desktop Entry]
374
387
  ${i[0]}
375
- `;let s=n.findIndex((a,u)=>u>r[0]&&u<r[1]&&Bl("DefaultProfile").test(a));if(s>=0)n.splice(s,1,...i);else n.splice(r[0]+1,0,...i);let o=r[1]+i.length-(s>=0?1:0);if(n.slice(r[0]+1,o).every((a)=>a.trim()==="")){let a=r[0]>0&&n[r[0]-1]?.trim()===""?r[0]-1:r[0],u=o===n.length&&n[o-1]===""?o-1:o;n.splice(a,u-a)}return n.join(`
376
- `)}function Jv(e){if(e&&Ht(e.toLowerCase()))return e.toLowerCase();let t=e?.split(",").map((n)=>Number(n.trim()));if(!t||t.length<3||t.slice(0,3).some((n)=>!Number.isInteger(n)||n<0||n>255))return;return`#${t.slice(0,3).map((n)=>n.toString(16).padStart(2,"0")).join("")}`}function gb(e,t){let n=t.endsWith(".profile")?t:`${t}.profile`;if(Bv(n))return ja(n)?n:void 0;let r=n.includes("/")?n:Vs("konsole",n);return[Bs(e.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((s)=>Vs(s,r)).find((s)=>ja(s))}function mb(e,t,n=0){let r=t&&t!=="FALLBACK/"&&n<8?gb(e,t):void 0;if(!r)return{};let i=Ie(r),s=mb(e,hr(i,"General","Parent"),n+1);return{scheme:hr(i,"Appearance","ColorScheme")||s.scheme,use:hr(i,"Cursor Options","UseCustomCursorColor")??s.use,cursor:hr(i,"Cursor Options","CustomCursorColor")??s.cursor}}function qv(e,t){let n=mb(e,t),r=n.use==="true"?Jv(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function Vv(e,t){return["[Appearance]",`ColorScheme=${_(e.name)}`,"","[Cursor Options]",`CustomCursorColor=${ve(e.cursor).join(",")}`,`CustomCursorTextColor=${ve(e.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${zs(e.name)}`,`Parent=${t}`,""].join(`
377
- `)}function zv(e){let t=new Set(Xe(e.entries).map((n)=>n.name));return e.themes.filter((n)=>t.has(n.name)||n.name===e.startup)}var Jl=["--session","--print-reply","--reply-timeout=2000"];function Yv(e){return[...(e.run("dbus-send",[...Jl,"--dest=org.freedesktop.DBus","/org/freedesktop/DBus","org.freedesktop.DBus.ListNames"])??"").matchAll(/string "(org\.kde\.konsole(?:-\d+)?)"/g)].flatMap(([,n=""])=>{let i=e.run("dbus-send",[...Jl,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function Qv(e,{service:t,window:n},r){let i=(s,...o)=>e.run("dbus-send",[...Jl,`--dest=${t}`,n,`org.kde.konsole.Window.${s}`,...o]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function Zv(e,t){let n=gb(e,t);return n?hr(Ie(n),"General","Name"):void 0}function Xv(e){return hr(Ie(qs(e)),"Desktop Entry","DefaultProfile")}var Dv={key:"konsoleBase",profile:zs,base(e){let t=Xv(e.configHome);return t&&!t.startsWith(_(""))?{...e.state,konsoleBase:t}:e.state},point(e,t){let n=qs(e.configHome),r=Ie(n),i=hr(r,"Desktop Entry","DefaultProfile"),s=i?.startsWith(_(""))===!0,o=e.startup?t||s?fb(e.startup):void 0:s?e.state.konsoleBase??"":void 0;if(o===void 0||o===(i??"")&&!t)return;if(o!==(i??""))en(n,hb(r,o||void 0));let a=e.startup?zs(e.startup):o?Zv(e,o):void 0,u=Yv(e.host),c=a!==void 0&&u.every((l)=>Qv(e.host,l,a));return{restart:u.length>0&&!c}}},ql={id:"konsole",name:"Konsole",emitter:El,shelf:{from:"",dir:(e)=>Ua(e.home)},offered:(e,t)=>t.platform!=="darwin"&&t.platform!=="win32",present:(e)=>ja(Ua(e.home))||ja(qs(e.configHome)),sync(e,t){t.themes(ql);let n=Ua(e.home),r=e.state.konsoleBase??"FALLBACK/",i=new Set;for(let s of zv(e)){let o=Vs(n,fb(s.name));i.add(o),t.write(o,Vv(s,r))}for(let s of xa(n))if(s.endsWith(".profile")&&!i.has(s))t.remove(s)},layer:(e)=>({TTHEME_KONSOLE_BASE:qv(e,e.state.konsoleBase)}),plan(e){return[`Write ${De(Ua(e.home),e.home)}/${_("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...e.startup?[`Edit ${De(qs(e.configHome),e.home)} — DefaultProfile; \`ttheme off\` puts yours back`]:[]]},notes:()=>[],next(e,t){let n=['Konsole profiles A "ttheme · <palette>" per palette in its profile list'];if(e.startup)n.push(t?.restart?`Restart Konsole New tabs open on "${zs(e.startup)}"`:`Konsole default "${zs(e.startup)}", which follows \`ttheme default\``);return n},unwire(e,t){let n=qs(e.configHome),r=Ie(n);return{edits:hr(r,"Desktop Entry","DefaultProfile")?.startsWith(_(""))?[{file:n,content:hb(r,t?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:Dv};import{spawn as eM}from"node:child_process";import{existsSync as gr,mkdirSync as tM,readdirSync as Vl,readFileSync as zl,realpathSync as nM,rmSync as rM,writeFileSync as iM}from"node:fs";import{dirname as $b,join as It}from"node:path";function _r(e){return process.platform==="darwin"?It(e,".warp","themes"):It(Bs(e),"warp-terminal","themes")}function mr(e,t){return process.platform==="darwin"?It(e,".warp","settings.toml"):It(t,"warp-terminal","settings.toml")}var Ka='"dark"';function Ba(e){return It(e,"ttheme","warp.base")}var kb="[appearance.themes]";function yb(e){let t=e.findIndex((r)=>r.trim()===kb);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function pr(e){let t=e.split(`
378
- `),n=yb(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Ql(e,t=`${_(e)}.yaml`){return`{ custom = { name = "${e}", path = "${t}" } }`}function sM(e){return e?.includes(`path = "${_("")}`)===!0?/name = "([^"]+)"/.exec(e)?.[1]:void 0}function Ja(e,t){let n=e.split(`
379
- `),r=yb(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
388
+ `;let o=n.findIndex((a,c)=>c>r[0]&&c<r[1]&&Xl("DefaultProfile").test(a));if(o>=0)n.splice(o,1,...i);else n.splice(r[0]+1,0,...i);let s=r[1]+i.length-(o>=0?1:0);if(n.slice(r[0]+1,s).every((a)=>a.trim()==="")){let a=r[0]>0&&n[r[0]-1]?.trim()===""?r[0]-1:r[0],c=s===n.length&&n[s-1]===""?s-1:s;n.splice(a,c-a)}return n.join(`
389
+ `)}function nI(t){if(t&&Bt(t.toLowerCase()))return t.toLowerCase();let e=t?.split(",").map((n)=>Number(n.trim()));if(!e||e.length<3||e.slice(0,3).some((n)=>!Number.isInteger(n)||n<0||n>255))return;return`#${e.slice(0,3).map((n)=>n.toString(16).padStart(2,"0")).join("")}`}function Qb(t,e){let n=e.endsWith(".profile")?e:`${e}.profile`;if(eI(n))return Ga(n)?n:void 0;let r=n.includes("/")?n:Wo("konsole",n);return[Ao(t.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((o)=>Wo(o,r)).find((o)=>Ga(o))}function Xb(t,e,n=0){let r=e&&e!=="FALLBACK/"&&n<8?Qb(t,e):void 0;if(!r)return{};let i=it(r),o=Xb(t,er(i,"General","Parent"),n+1);return{scheme:er(i,"Appearance","ColorScheme")||o.scheme,use:er(i,"Cursor Options","UseCustomCursorColor")??o.use,cursor:er(i,"Cursor Options","CustomCursorColor")??o.cursor}}function rI(t,e){let n=Xb(t,e),r=n.use==="true"?nI(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function iI(t,e){return["[Appearance]",`ColorScheme=${T(t.name)}`,"","[Cursor Options]",`CustomCursorColor=${nt(t.cursor).join(",")}`,`CustomCursorTextColor=${nt(t.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${_o(t.name)}`,`Parent=${e}`,""].join(`
390
+ `)}function oI(t){let e=new Set(Mt(t.entries).map((n)=>n.name));return t.themes.filter((n)=>e.has(n.name)||n.name===t.startup)}var tf=["--session","--print-reply","--reply-timeout=2000"];function sI(t){return[...(t.run("dbus-send",[...tf,"--dest=org.freedesktop.DBus","/org/freedesktop/DBus","org.freedesktop.DBus.ListNames"])??"").matchAll(/string "(org\.kde\.konsole(?:-\d+)?)"/g)].flatMap(([,n=""])=>{let i=t.run("dbus-send",[...tf,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function aI(t,{service:e,window:n},r){let i=(o,...s)=>t.run("dbus-send",[...tf,`--dest=${e}`,n,`org.kde.konsole.Window.${o}`,...s]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function cI(t,e){let n=Qb(t,e);return n?er(it(n),"General","Name"):void 0}function uI(t){return er(it(Uo(t)),"Desktop Entry","DefaultProfile")}var lI={key:"konsoleBase",profile:_o,base(t){let e=uI(t.configHome);return e&&!e.startsWith(T(""))?{...t.state,konsoleBase:e}:t.state},point(t,e){let n=Uo(t.configHome),r=it(n),i=er(r,"Desktop Entry","DefaultProfile"),o=i?.startsWith(T(""))===!0,s=t.startup?e||o?Db(t.startup):void 0:o?t.state.konsoleBase??"":void 0;if(s===void 0||s===(i??"")&&!e)return;if(s!==(i??""))Ae(n,Zb(r,s||void 0));let a=t.startup?_o(t.startup):s?cI(t,s):void 0,c=sI(t.host),u=a!==void 0&&c.every((l)=>aI(t.host,l,a));return{restart:c.length>0&&!u}}},ef={id:"konsole",name:"Konsole",emitter:Wl,shelf:{from:"",dir:(t)=>ja(t.home)},offered:(t,e)=>e.platform!=="darwin"&&e.platform!=="win32",present:(t)=>Ga(ja(t.home))||Ga(Uo(t.configHome)),sync(t,e){e.themes(ef);let n=ja(t.home),r=t.state.konsoleBase??"FALLBACK/",i=new Set;for(let o of oI(t)){let s=Wo(n,Db(o.name));i.add(s),e.write(s,iI(o,r))}for(let o of Ha(n))if(o.endsWith(".profile")&&!i.has(o))e.remove(o)},layer:(t)=>({TTHEME_KONSOLE_BASE:rI(t,t.state.konsoleBase)}),plan(t){return[`Write ${It(ja(t.home),t.home)}/${T("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...t.startup?[`Edit ${It(Uo(t.configHome),t.home)} — DefaultProfile; \`ttheme off\` puts yours back`]:[]]},notes:()=>[],next(t,e){let n=['Konsole profiles A "ttheme · <palette>" per palette in its profile list'];if(t.startup)n.push(e?.restart?`Restart Konsole New tabs open on "${_o(t.startup)}"`:`Konsole default "${_o(t.startup)}", which follows \`ttheme default\``);return n},unwire(t,e){let n=Uo(t.configHome),r=it(n);return{edits:er(r,"Desktop Entry","DefaultProfile")?.startsWith(T(""))?[{file:n,content:Zb(r,e?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:lI};import{spawn as fI}from"node:child_process";import{existsSync as nr,mkdirSync as dI,readdirSync as nf,readFileSync as rf,realpathSync as hI,rmSync as mI,writeFileSync as gI}from"node:fs";import{dirname as rw,join as oe}from"node:path";function xr(t){return process.platform==="darwin"?oe(t,".warp","themes"):oe(Ao(t),"warp-terminal","themes")}function rr(t,e){return process.platform==="darwin"?oe(t,".warp","settings.toml"):oe(e,"warp-terminal","settings.toml")}var Ua='"dark"';function Wa(t){return oe(t,"ttheme","warp.base")}var iw="[appearance.themes]";function ow(t){let e=t.findIndex((r)=>r.trim()===iw);if(e<0)return;let n=t.findIndex((r,i)=>i>e&&r.trimStart().startsWith("["));return[e,n<0?t.length:n]}function ir(t){let e=t.split(`
391
+ `),n=ow(e);if(!n)return;return e.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function sf(t,e=`${T(t)}.yaml`){return`{ custom = { name = "${t}", path = "${e}" } }`}function pI(t){return t?.includes(`path = "${T("")}`)===!0?/name = "([^"]+)"/.exec(t)?.[1]:void 0}function _a(t,e){let n=t.split(`
392
+ `),r=ow(n);if(!r)return e===void 0?t:`${t.replace(/\n*$/,`
380
393
  `)}
381
- ${kb}
382
- theme = ${t}
383
- `;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(`
384
- `)}function Yl(e){return pr(e)?.includes(`path = "${_("")}`)===!0}var oM="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen, theme] = process.argv.slice(-4); if (fs.readFileSync(file, 'utf8') !== seen || !fs.existsSync(theme)) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 500)";function Eb(e,t,n){return{image:It(e,Kp(t.name,n.image,t.background)),opacity:n.opacity}}function pb(e){let t=_r(e.home),n=Se(e.configHome),r=new Map,i=new Set;for(let s of e.themes){let o=Os(n,s.name,e.home),a=js(s.name,o&&Eb(t,s,o));r.set(s.name,a);for(let u of new Set([a,js(s.name)]))if(!gr(It(t,u)))i.add(u)}return{files:r,fresh:i}}function bb(e,t,n){let r=_r(e.home),i=Se(e.configHome),s=new Set(n.values()),o=pr(Ie(mr(e.home,e.configHome)))??"";for(let c of e.themes){let l=Os(i,c.name,e.home),f=n.get(c.name);if(l&&f){let d=Eb(r,c,l);if(!gr(d.image))try{let h=At(new Uint8Array(zl(l.image)));K(d.image,zo(Vo(h,c.background,1)))}catch{n.set(c.name,js(c.name));continue}t.write(It(r,f),Ks(c,d))}}if(!gr(r))return;let a=(c,l)=>c.startsWith(_(""))&&new RegExp(`\\.[0-9a-f]{8}\\.${l}$`).test(c);for(let c of Vl(r))if(a(c,"yaml")&&!s.has(c)&&!o.includes(`path = "${c}"`))t.remove(It(r,c));let u=new Set;for(let c of Vl(r)){let l=c.startsWith(_(""))&&c.endsWith(".yaml")?/^ {2}path: "(.+)"$/m.exec(Ie(It(r,c)))?.[1]:void 0;if(l)u.add(l)}for(let c of Vl(r))if(a(c,"png")&&!u.has(It(r,c)))t.remove(It(r,c))}function wb(e,t,n,r=!1){let i=mr(e.home,e.configHome);if(!gr(i))return;let s=Ba(e.configHome),o=zl(i,"utf8"),a=r?sM(pr(o)):t;if(r&&(a===void 0||!n.files.has(a)))return;let u;if(a){if(!Yl(o)&&!gr(s))tM($b(s),{recursive:!0}),iM(s,pr(o)??"");u=Ql(a,n.files.get(a))}else{if(!Yl(o))return;u=gr(s)&&zl(s,"utf8")||Ka,rM(s,{force:!0})}let c=Ja(o,u);if(c===o)return;let l=a===void 0?void 0:n.files.get(a)??`${_(a)}.yaml`;if(l!==void 0&&n.fresh.has(l))fc(i),eM(process.execPath,["-e",oM,nM(i),c,o,It(_r(e.home),l)],{detached:!0,stdio:"ignore"}).unref();else en(i,c);return i}var Zl={id:"warp",name:"Warp",emitter:Hl,shelf:{from:"themes",dir:(e)=>_r(e.home)},bakes:!0,offered:(e,t)=>t.platform!=="win32",present:(e)=>gr($b(_r(e.home))),sync(e,t){let n=pb(e);t.themes(Zl),bb(e,t,n.files);let r=wb(e,e.startup,n);if(r)t.note(r)},pictures(e,t){let n=pb(e);bb(e,t,n.files),wb(e,void 0,n,!0)},plan(e){let t=mr(e.home,e.configHome);return e.startup&&gr(t)?[`Edit ${De(t,e.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears one theme for the whole app, set through its settings.toml — a tab that takes a palette (`ttheme use`, a pin, preview) switches it, and switching tabs puts on the palette of the tab in front, read from Warp’s session database with sqlite3"],next:()=>[],unwire(e){let t=mr(e.home,e.configHome),n=Ie(t);return{edits:Yl(n)?[{file:t,content:Ja(n,Ie(Ba(e.configHome))||Ka)}]:[],removals:[],touches:[]}}};import{existsSync as za}from"node:fs";import{join as Ti}from"node:path";var vb=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,aM=/^return config[ \t]*$/gm;function uM(e){return`dofile(${JSON.stringify(e)})(config)`}var Sb=`local wezterm = require 'wezterm'
394
+ ${iw}
395
+ theme = ${e}
396
+ `;let i=n.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)n.splice(i,1,...e===void 0?[]:[`theme = ${e}`]);else if(e!==void 0)n.splice(r[0]+1,0,`theme = ${e}`);return n.join(`
397
+ `)}function of(t){return ir(t)?.includes(`path = "${T("")}`)===!0}var bI="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen, theme] = process.argv.slice(-4); if (fs.readFileSync(file, 'utf8') !== seen || !fs.existsSync(theme)) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 500)";function sw(t,e,n){return{image:oe(t,Rb(e.name,n.image,e.background)),opacity:n.opacity}}function tw(t){let e=xr(t.home),n=X(t.configHome),r=new Map,i=new Set;for(let o of t.themes){let s=Eo(n,o.name,t.home),a=Co(o.name,s&&sw(e,o,s));r.set(o.name,a);for(let c of new Set([a,Co(o.name)]))if(!nr(oe(e,c)))i.add(c)}return{files:r,fresh:i}}function ew(t,e,n){let r=xr(t.home),i=X(t.configHome),o=new Set(n.values()),s=ir(it(rr(t.home,t.configHome)))??"";for(let u of t.themes){let l=Eo(i,u.name,t.home),f=n.get(u.name);if(l&&f){let d=sw(r,u,l);if(!nr(d.image))try{let m=le(new Uint8Array(rf(l.image)));x(d.image,Ks(zs(m,u.background,1)))}catch{n.set(u.name,Co(u.name));continue}e.write(oe(r,f),jo(u,d))}}if(!nr(r))return;let a=(u,l)=>u.startsWith(T(""))&&new RegExp(`\\.[0-9a-f]{8}\\.${l}$`).test(u);for(let u of nf(r))if(a(u,"yaml")&&!o.has(u)&&!s.includes(`path = "${u}"`))e.remove(oe(r,u));let c=new Set;for(let u of nf(r)){let l=u.startsWith(T(""))&&u.endsWith(".yaml")?/^ {2}path: "(.+)"$/m.exec(it(oe(r,u)))?.[1]:void 0;if(l)c.add(l)}for(let u of nf(r))if(a(u,"png")&&!c.has(oe(r,u)))e.remove(oe(r,u))}function nw(t,e,n,r=!1){let i=rr(t.home,t.configHome);if(!nr(i))return;let o=Wa(t.configHome),s=rf(i,"utf8"),a=r?pI(ir(s)):e;if(r&&(a===void 0||!n.files.has(a)))return;let c;if(a){if(!of(s)&&!nr(o))dI(rw(o),{recursive:!0}),gI(o,ir(s)??"");c=sf(a,n.files.get(a))}else{if(!of(s))return;c=nr(o)&&rf(o,"utf8")||Ua,mI(o,{force:!0})}let u=_a(s,c);if(u===s)return;let l=a===void 0?void 0:n.files.get(a)??`${T(a)}.yaml`;if(l!==void 0&&n.fresh.has(l))wu(i),fI(process.execPath,["-e",bI,hI(i),u,s,oe(xr(t.home),l)],{detached:!0,stdio:"ignore"}).unref();else Ae(i,u);return i}var af={id:"warp",name:"Warp",emitter:Bl,shelf:{from:"themes",dir:(t)=>xr(t.home)},bakes:!0,offered:(t,e)=>e.platform!=="win32",present:(t)=>nr(rw(xr(t.home))),sync(t,e){let n=tw(t);e.themes(af),ew(t,e,n.files);let r=nw(t,t.startup,n);if(r)e.note(r)},pictures(t,e){let n=tw(t);ew(t,e,n.files),nw(t,void 0,n,!0)},plan(t){let e=rr(t.home,t.configHome);return t.startup&&nr(e)?[`Edit ${It(e,t.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears one theme for the whole app, set through its settings.toml — a tab that takes a palette (`ttheme use`, a pin, preview) switches it, and switching tabs puts on the palette of the tab in front, read from Warp’s session database with sqlite3"],next:()=>[],unwire(t){let e=rr(t.home,t.configHome),n=it(e);return{edits:of(n)?[{file:e,content:_a(n,it(Wa(t.configHome))||Ua)}]:[],removals:[],touches:[]}}};import{existsSync as Ka}from"node:fs";import{join as Fi}from"node:path";var aw=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,wI=/^return config[ \t]*$/gm;function $I(t){return`dofile(${JSON.stringify(t)})(config)`}var uw=`local wezterm = require 'wezterm'
385
398
  local config = wezterm.config_builder()
386
399
 
387
- `;function cM(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${Sb}return config
388
- `?"":t}function Xl(e,t){let n=`-- ttheme begin
389
- ${t}
400
+ `;function kI(t){let e=t.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return e===`${uw}return config
401
+ `?"":e}function cf(t,e){let n=`-- ttheme begin
402
+ ${e}
390
403
  -- ttheme end
391
- `;if(vb.test(e))return e.replace(vb,n);if(e==="")return`${Sb}${n}
404
+ `;if(aw.test(t))return t.replace(aw,n);if(t==="")return`${uw}${n}
392
405
  return config
393
- `;let r=[...e.matchAll(aM)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
394
- ${e.slice(r.index)}`}function qa(e,t){let n=Ti(t,".wezterm.lua");return za(n)?n:Ti(e,"wezterm","wezterm.lua")}function Mb(e){return Ti(e.configHome,"wezterm","colors")}function Va(e){return Ti(e.configHome,"ttheme","wezterm.lua")}var Dl={id:"wezterm",name:"WezTerm",emitter:xl,shelf:{from:"colors",dir:Mb},offered:()=>!0,present:(e)=>za(Ti(e.configHome,"wezterm"))||za(Ti(e.home,".wezterm.lua")),sync(e,t){t.themes(Dl),t.write(Va(e),qp({path:Va(e),colors:Mb(e),backgrounds:Se(e.configHome),...e.startup?{startup:e.startup}:{},palettes:e.themes}));let n=qa(e.configHome,e.home),r=Xl(Ie(n),uM(Va(e)));if(r!==void 0)t.wire(n,r)},plan(e){let t=qa(e.configHome,e.home);return Xl(Ie(t),"")!==void 0?[`Edit ${De(t,e.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(e){let t=qa(e.configHome,e.home);return za(t)&&Xl(Ie(t),"")===void 0?[`${t} has no \`return config\` line — ttheme left it alone; call \`dofile("${Va(e)}")(config)\` from it yourself`]:[]},next:()=>["WezTerm Reloads its config by itself"],unwire:(e)=>({edits:fn(qa(e.configHome,e.home),cM),removals:[],touches:[]})};import{existsSync as Nb,readFileSync as lM,utimesSync as fM}from"node:fs";import{dirname as dM,join as Ya}from"node:path";function ef(e){return Ya(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Ib(e){return[Ya(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Ya(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Ya(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Nb(t))}function hM(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(lM(t,"utf8"))?.[1];if(n)return n}return}function Pb(e){if(e.platform==="win32")return e.env.LOCALAPPDATA;if(!e.env.WSL_DISTRO_NAME)return;let t=e.run("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"]);return t&&e.run("wslpath",["-u",t])||void 0}var Rb={id:"windows-terminal",name:"Windows Terminal",emitter:Ll,offered:(e)=>e.wtHome!==void 0,present:(e)=>e.wtHome!==void 0,installs:(e)=>({wtHome:e.wtHome,wtProfile:e.wtProfile}),sync(e,t){let{wtHome:n,wtProfile:r}=e.state;if(!n)return;let i=Ib(n);if(t.write(ef(n),Al(e.themes,r??hM(i),e.startup))){let s=new Date;for(let o of i)fM(o,s,s);if(i.length>0)t.repaint()}},plan:(e)=>e.state.wtHome?[`Write ${ef(e.state.wtHome)} — its schemes, and touch settings.json so it reloads`]:[],notes:(e)=>e.state.wtHome?[]:["Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself"],next:()=>["Windows Terminal Reloads its settings by itself"],unwire(e,t){let n=t?.wtHome,r=n?dM(ef(n)):void 0;return{edits:[],removals:r&&Nb(r)?[r]:[],touches:n?Ib(n):[]}}};var br={ghostty:Wl,kitty:Kl,alacritty:Gl,wezterm:Dl,iterm2:ub,"windows-terminal":Rb,warp:Zl,konsole:ql};function Ce(e=St){return e.map((t)=>br[t])}function Gr(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Yt(e){return e.off?void 0:Gr(e)}function ue(){return process.env.XDG_CONFIG_HOME??Qa(dn(),".config")}var Hi=(e)=>typeof e==="string"&&e!==""?e:void 0,gM={author:Hi,startup:Hi,off:(e)=>e?!0:void 0,itermBase:Hi,konsoleBase:Hi,wtHome:Hi,wtProfile:Hi,markets:(e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"):void 0,updates:(e)=>e&&typeof e==="object"?Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="boolean")):void 0};function ne(e){let t=tr(e);if(!tf(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Ob(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)=>St.includes(r)),...Object.fromEntries(Object.entries(gM).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function hn(e,t){K(tr(e),`${JSON.stringify(t,null,2)}
395
- `)}function Fb(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`:bl(Xe(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Ys(e,t,n){return{configHome:e,home:n,state:t,startup:Yt(t)}}function Tb(e,t,n,r){return{...Ys(e,n,r),entries:t,themes:t.map(Sn)}}function Hb(e){let t=[],n={written:t,repainted:!1,write(r,i){if(t.push(r),tf(r)&&Ob(r,"utf8")===i)return!1;return K(r,i),!0},wire(r,i){t.push(r),en(r,i)},note(r){t.push(r)},remove(r){nf(r,{force:!0})},themes(r){let i=r.shelf?.dir(e);if(!i)return;for(let s of e.themes)for(let{file:o,content:a}of Cl(r,s))n.write(Qa(i,o),a)},repaint(){n.repainted=!0}};return n}function mM(e){return Object.assign({},...Ce(e.state.terminals).map((t)=>t.layer?.(e)??{}))}function mt(e,t,n,r=dn()){ct(Se(e));let i=Fb(Ke(e,t),n.palettes);Xm(e,new Map(i.map((c)=>[c.name,Ps(c)]))),Km(e),Sa(e,i);let s=Tb(e,i,n,r),o=Hb(s);for(let c of Ce(n.terminals))c.sync(s,o);let a=Qa(e,"ttheme","palettes.zsh"),u=Fl(i,s.startup,n.terminals,mM(s));if(o.repainted||Ie(a)!==u)K(a,u),nf(`${a}.zwc`,{force:!0});return o.written.push(a),o.written}function Nt(e,t=dn()){let n=ne(e),r=Ce(n.terminals).filter((o)=>o.pictures);if(r.length===0)return;let i=Tb(e,Fb(ln(e),n.palettes),n,t),s=Hb(i);for(let o of r)o.pictures?.(i,s)}function Wr(e){return!Ce(e).some((t)=>t.bakes)}function xb(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>[...i.shelf?[`Write ${De(i.shelf.dir(r),n)}/${_("*")} — a theme file per palette`]:[],...i.plan(r)])}function Ab(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>i.notes(r))}function Lb(e,t,n,r=dn()){let i=Ys(e,t,r);return Ce(t.terminals).flatMap((s)=>s.next(i,n.get(s.id)))}function Za(e,t,n,r,i=dn()){let s=[],o=Ke(e,t,!1).palettes;for(let a of Ce(n)){let u=a.shelf?.dir({configHome:e,home:i});for(let c of u?o.filter((l)=>r.includes(l.name)):[])for(let{file:l}of Cl(a,Sn(c))){let f=Qa(u,l);if(tf(f))nf(f,{force:!0}),s.push(f)}}return s}function Cb(e,t,n,r){return{...Ys(e,t,r),host:n}}function rf(e,t,n,r=dn()){return Ce(t.terminals).reduce((i,s)=>s.defaults?.base(Cb(e,i,n,r))??i,t)}function Qs(e,t,n,r,i=dn()){let s=new Map;for(let o of Ce(t.terminals)){let a=o.defaults?.point(Cb(e,t,r,i),n);if(a)s.set(o.id,a)}return s}function gn(e,t,n,r,i=!1,s=Cr(),o=dn()){let a=i||!Yt(n)&&Yt(r)!==void 0,u=a?rf(e,r,s,o):r;return mt(e,t,u,o),hn(e,u),a||Yt(n)!==Yt(r)?Qs(e,u,a,s,o):new Map}var pM=300,bM=80,_b=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Xa(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Da(e,t){if(!t)return Xa(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function wr(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=gt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${rt(`${_b[i%_b.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},bM),o.unref()},pM);return u.unref(),{set(c){if(e=c,s)a()},say(c){if(s)t.write("\r\x1B[2K");if(console.log(c),s)a()},done(){if(clearTimeout(u),clearInterval(o),s)t.write("\r\x1B[2K"),s=!1}}}import{existsSync as RM,mkdirSync as Jb,readFileSync as qb,statSync as OM}from"node:fs";import{homedir as FM}from"node:os";import{dirname as TM,join as Kb}from"node:path";import{existsSync as sf,mkdirSync as Wb,readFileSync as Ai}from"node:fs";import{homedir as vM}from"node:os";import{dirname as Ub,join as Li}from"node:path";import{spawn as wM}from"node:child_process";var $M=30000,kM=3,yM=97,EM=`ObjC.import('Vision')
406
+ `;let r=[...t.matchAll(wI)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${n}
407
+ ${t.slice(r.index)}`}function Ba(t,e){let n=Fi(e,".wezterm.lua");return Ka(n)?n:Fi(t,"wezterm","wezterm.lua")}function cw(t){return Fi(t.configHome,"wezterm","colors")}function za(t){return Fi(t.configHome,"ttheme","wezterm.lua")}var uf={id:"wezterm",name:"WezTerm",emitter:zl,shelf:{from:"colors",dir:cw},offered:()=>!0,present:(t)=>Ka(Fi(t.configHome,"wezterm"))||Ka(Fi(t.home,".wezterm.lua")),sync(t,e){e.themes(uf),e.write(za(t),Fb({path:za(t),colors:cw(t),backgrounds:X(t.configHome),...t.startup?{startup:t.startup}:{},palettes:t.themes}));let n=Ba(t.configHome,t.home),r=cf(it(n),$I(za(t)));if(r!==void 0)e.wire(n,r)},plan(t){let e=Ba(t.configHome,t.home);return cf(it(e),"")!==void 0?[`Edit ${It(e,t.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(t){let e=Ba(t.configHome,t.home);return Ka(e)&&cf(it(e),"")===void 0?[`${e} has no \`return config\` line — ttheme left it alone; call \`dofile("${za(t)}")(config)\` from it yourself`]:[]},next:()=>["WezTerm Reloads its config by itself"],unwire:(t)=>({edits:Ke(Ba(t.configHome,t.home),kI),removals:[],touches:[]})};import{existsSync as fw,readFileSync as yI,utimesSync as vI}from"node:fs";import{dirname as EI,join as qa}from"node:path";function lf(t){return qa(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function lw(t){return[qa(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),qa(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),qa(t,"Microsoft","Windows Terminal","settings.json")].filter((e)=>fw(e))}function SI(t){for(let e of t){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(yI(e,"utf8"))?.[1];if(n)return n}return}function dw(t){if(t.platform==="win32")return t.env.LOCALAPPDATA;if(!t.env.WSL_DISTRO_NAME)return;let e=t.run("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"]);return e&&t.run("wslpath",["-u",e])||void 0}var hw={id:"windows-terminal",name:"Windows Terminal",emitter:ql,offered:(t)=>t.wtHome!==void 0,present:(t)=>t.wtHome!==void 0,installs:(t)=>({wtHome:t.wtHome,wtProfile:t.wtProfile}),sync(t,e){let{wtHome:n,wtProfile:r}=t.state;if(!n)return;let i=lw(n);if(e.write(lf(n),Kl(t.themes,r??SI(i),t.startup))){let o=new Date;for(let s of i)vI(s,o,o);if(i.length>0)e.repaint()}},plan:(t)=>t.state.wtHome?[`Write ${lf(t.state.wtHome)} — its schemes, and touch settings.json so it reloads`]:[],notes:(t)=>t.state.wtHome?[]:["Windows Terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself"],next:()=>["Windows Terminal Reloads its settings by itself"],unwire(t,e){let n=e?.wtHome,r=n?EI(lf(n)):void 0;return{edits:[],removals:r&&fw(r)?[r]:[],touches:n?lw(n):[]}}};var or={ghostty:Dl,kitty:Ql,alacritty:Yl,wezterm:uf,iterm2:qb,"windows-terminal":hw,warp:af,konsole:ef};function ft(t=ie){return t.map((e)=>or[e])}function Lr(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function Re(t){return t.off?void 0:Lr(t)}function Y(){return process.env.XDG_CONFIG_HOME??Ja(qe(),".config")}var xi=(t)=>typeof t==="string"&&t!==""?t:void 0,MI={author:xi,startup:xi,off:(t)=>t?!0:void 0,itermBase:xi,konsoleBase:xi,wtHome:xi,wtProfile:xi,markets:(t)=>Array.isArray(t)?t.filter((e)=>typeof e==="string"):void 0,updates:(t)=>t&&typeof t==="object"?Object.fromEntries(Object.entries(t).filter((e)=>typeof e[1]==="boolean")):void 0};function B(t){let e=Wn(t);if(!ff(e))throw Error(`nothing installed yet at ${e} — run \`ttheme init\` first`);let n=JSON.parse(mw(e,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${e} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>ie.includes(r)),...Object.fromEntries(Object.entries(MI).flatMap(([r,i])=>{let o=i(n[r]);return o===void 0?[]:[[r,o]]})),palettes:n.palettes}}function Je(t,e){x(Wn(t),`${JSON.stringify(e,null,2)}
408
+ `)}function gw(t,e){let n=new Map(t.palettes.map((i)=>[i.name,i])),r=e.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((s)=>rt(s)??[]))].filter((s)=>!t.palettes.some((a)=>rt(a.name)===s)),o=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Sl(Mt(t.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${o}`)}return t.palettes.filter((i)=>e.includes(i.name))}function Bo(t,e,n){return{configHome:t,home:n,state:e,startup:Re(e)}}function pw(t,e,n,r){return{...Bo(t,n,r),entries:e,themes:e.map(Se)}}function bw(t){let e=[],n={written:e,repainted:!1,write(r,i){if(e.push(r),ff(r)&&mw(r,"utf8")===i)return!1;return x(r,i),!0},wire(r,i){e.push(r),Ae(r,i)},note(r){e.push(r)},remove(r){df(r,{force:!0})},themes(r){let i=r.shelf?.dir(t);if(!i)return;for(let o of t.themes)for(let{file:s,content:a}of Al(r,o))n.write(Ja(i,s),a)},repaint(){n.repainted=!0}};return n}function II(t){return Object.assign({},...ft(t.state.terminals).map((e)=>e.layer?.(t)??{}))}function At(t,e,n,r=qe()){Rt(X(t));let i=gw(Hr(t,e),n.palettes),o=wa(i,fn(t));Np(t,new Map(o.map((l)=>[l.name,wi(l)]))),gp(t),ya(t,i);let s=pw(t,o,n,r),a=bw(s);for(let l of ft(n.terminals))l.sync(s,a);let c=Ja(t,"ttheme","palettes.zsh"),u=Ll(o,s.startup,n.terminals,II(s));if(a.repainted||it(c)!==u)x(c,u),df(`${c}.zwc`,{force:!0});return a.written.push(c),a.written}function se(t,e=qe()){let n=B(t),r=ft(n.terminals).filter((s)=>s.pictures);if(r.length===0)return;let i=pw(t,gw(Oe(t),n.palettes),n,e),o=bw(i);for(let s of r)s.pictures?.(i,o)}function Tr(t){return!ft(t).some((e)=>e.bakes)}function ww(t,e,n=qe()){let r=Bo(t,e,n);return ft(e.terminals).flatMap((i)=>[...i.shelf?[`Write ${It(i.shelf.dir(r),n)}/${T("*")} — a theme file per palette`]:[],...i.plan(r)])}function $w(t,e,n=qe()){let r=Bo(t,e,n);return ft(e.terminals).flatMap((i)=>i.notes(r))}function kw(t,e,n,r=qe()){let i=Bo(t,e,r);return ft(e.terminals).flatMap((o)=>o.next(i,n.get(o.id)))}function Ya(t,e,n,r,i=qe()){let o=[],s=wt(t,e,!1).palettes;for(let a of ft(n)){let c=a.shelf?.dir({configHome:t,home:i});for(let u of c?s.filter((l)=>r.includes(l.name)):[])for(let{file:l}of Al(a,Se(u))){let f=Ja(c,l);if(ff(f))df(f,{force:!0}),o.push(f)}}return o}function yw(t,e,n,r){return{...Bo(t,e,r),host:n}}function hf(t,e,n,r=qe()){return ft(e.terminals).reduce((i,o)=>o.defaults?.base(yw(t,i,n,r))??i,e)}function zo(t,e,n,r,i=qe()){let o=new Map;for(let s of ft(e.terminals)){let a=s.defaults?.point(yw(t,e,r,i),n);if(a)o.set(s.id,a)}return o}function Ye(t,e,n,r,i=!1,o=Fr(),s=qe()){let a=i||!Re(n)&&Re(r)!==void 0,c=a?hf(t,r,o,s):r;return At(t,e,c,s),Je(t,c),a||Re(n)!==Re(r)?zo(t,c,a,o,s):new Map}var OI=300,NI=80,vw=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Da(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Va(t,e){if(!e)return Da(t);return e>=1e6?`${(t/1e6).toFixed(1)}/${(e/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(e/1000)} KB`}function sr(t=""){let e=process.stdout;if(!e.isTTY||process.env.TERM==="dumb")return{set(){},say:(u)=>console.log(u),done(){}};let[n,r]=zt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,o=!1,s,a=()=>{e.write(`\r\x1B[2K${n}${Et(`${vw[i%vw.length]} ${t}`,(e.columns||80)-1,!1)}${r}`)},c=setTimeout(()=>{o=!0,a(),s=setInterval(()=>{i++,a()},NI),s.unref()},OI);return c.unref(),{set(u){if(t=u,o)a()},say(u){if(o)e.write("\r\x1B[2K");if(console.log(u),o)a()},done(){if(clearTimeout(c),clearInterval(s),o)e.write("\r\x1B[2K"),o=!1}}}import{existsSync as UI,mkdirSync as Hw,readFileSync as Fw,statSync as WI}from"node:fs";import{homedir as _I}from"node:os";import{dirname as BI,join as Rw}from"node:path";import{existsSync as mf,mkdirSync as Ew,readFileSync as Ti}from"node:fs";import{homedir as LI}from"node:os";import{dirname as Sw,join as Ar}from"node:path";import{spawn as RI}from"node:child_process";var PI=30000,HI=3,FI=97,xI=`ObjC.import('Vision')
396
409
  ObjC.import('CoreImage')
397
410
  ObjC.import('CoreGraphics')
398
411
  function run(argv) {
@@ -411,11 +424,11 @@ function run(argv) {
411
424
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
412
425
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
413
426
  if (!written) throw new Error('write failed')
414
- }`;function xi(){return process.platform==="darwin"}function eu(e){return e>=kM&&e<=yM}function Zs(e,t,n){return new Promise((r,i)=>{let s=wM("osascript",["-l","JavaScript","-e",EM,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout($M)])}),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(`
415
- `).at(-1)||`osascript exited ${a}`))})})}var jb=90000;function tu(e,t){let n=Se(e),r=_t(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&X.some((a)=>a.key===s)?[{site:s,id:Number(o),...rl(n,i)}]:[]});return r.length>0?r:void 0}function MM(e,t){let n=new Set(ct(Se(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ft(r)))}function Ci(e,t){let n=new Set((t??[]).map((r)=>ft(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ft(r)))}}async function SM(e,t,n,r,i,s){let o=X.find((p)=>p.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await ys(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==Lt&&a.md5)try{aa([a],await ua([a.md5],i))}catch{}let u=oa(o,a)?sa(o,a.id,i).then((p)=>{if(p)vs(a,p)},()=>{}):void 0;if(!ra(o,a,Or(process.env.TTHEME_FIND_RATING))||na(a,gi(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=nn(a);if(!c)throw Error("too large to use");let l=Li(rn(o),"orig",`${n.id}.${c.ext}`),f;if(sf(l))f=new Uint8Array(Ai(l));else{s("Downloading");let p=mi(o,a,c);f=await la(p.site,p.url,i,(m,k)=>s("Downloading",Da(m,k))),K(l,f)}let d=Kn(f,$t),h=!1;if(yn(d)===0&&xi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let p=Li(rn(o),"cut",`${n.id}.png`);try{if(!sf(p))s("Cutting out"),Wb(Ub(p),{recursive:!0}),await Zs(l,p,i);let m=Kn(new Uint8Array(Ai(p)),$t);if(eu(yn(m)))d=m,h=!0}catch{}}await u;let g=el(t);s("Drawing"),ba(e,g,ki(g,t.signatureSlots),d,{site:o.key,id:n.id,ext:c.ext,bytes:f,from:`${o.name} ${n.id} ${o.pageUrl(n.id)}`,artist:a.named.artist,source:Es(a.source),cut:h},{width:0,height:0},Lr(e),Fa(e));let b=_t(e,t.name).find((p)=>p.key===ft(n));if(b)Fs(Se(e),b,n,r,vM())}function IM(e,t){let n=X.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${gt()?ss:`\x1B[${30+n.ansi}m${ss}\x1B[39m`} ${jo(r,n.pageUrl(e.id))}`}async function Rn(e,t,n){let r=t.flatMap((u)=>MM(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=Wr(n),s=process.stdout.isTTY&&Tp(process.env),o=new Set,a=wr();for(let[u,{entry:c,shared:l}]of r.entries()){let f=`${c.name} · ${IM(l,s)}`,d=r.length>1?` · ${u+1}/${r.length}`:"",h=(g,b)=>a.set(`${g} ${f}${b?` · ${b}`:""}${d}`);try{await SM(e,c,l,i,AbortSignal.timeout(jb),h),a.say(` ▣ ${f}`),o.add(c)}catch(g){a.say(` ▢ ${f} — ${g instanceof Error?g.message:String(g)}`)}}a.done();for(let u of o){let c=(u.pictures??[]).find((l)=>_t(e,u.name).some((f)=>f.key===ft(l)));if(c)Ei(e,u.name,ft(c))}if(o.size>0)Nt(e)}function Gb(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 NM(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Li(pi(),n??"local","cut",`${r??e}.png`);if(!sf(i)){if(!xi())return;Wb(Ub(i),{recursive:!0}),await Zs(t,i,AbortSignal.timeout(jb))}return Kn(new Uint8Array(Ai(i)),$t)}function PM(e,t){try{return yn(At(new Uint8Array(Ai(Li(e,`${t.stem}.png`)))))>0}catch{return!1}}async function nu(e,t,n,r,i,s,o,a){let u=Se(e),c=ct(u).palettes[t]?.pictures.find((d)=>d.key===n);if(!c?.original)return null;let l=Li(u,c.original),f=Kn(new Uint8Array(Ai(l)),$t);if(c.cut){if(!Gb(f,At(new Uint8Array(Ai(Li(u,c.cut)))),0))return null;return wa(e,t,c,f,r,i,s,o,!1,a)}if(Rs(c)&&yn(f)===0&&PM(u,c)){let d=await NM(n,l);if(!d||!Gb(f,d,3))return null;return wa(e,t,c,f,r,i,s,o,!0,a)}return wa(e,t,c,f,r,i,s,o,!1,a)}var HM=86400000,xM=3600000,af=5000;function of(){return Kb(process.env.XDG_STATE_HOME??Kb(FM(),".local","state"),"ttheme","markets.json")}function On(){try{let e=JSON.parse(qb(of(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Bb(e,t){let n=On();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Jb(TM(of()),{recursive:!0}),K(of(),`${JSON.stringify(n,null,2)}
416
- `)}function Xs(e,t){let n=t===ee?Vt(e):yt(t)?qt(e,t):void 0;try{return n?OM(n).mtimeMs:void 0}catch{return}}function AM(e,t,n,r){return e&&(t===void 0||r-t>=HM)&&(n===void 0||r-n>=xM)}function uf(e,t,n=Date.now()){let r=On();return st(t.markets).filter((i)=>AM(nr(i,t.updates),Xs(e,i),r[i]?.at,n))}async function LM(e,t,n){try{return await Ls(np(e),pl,t,n)}catch(r){if(r instanceof Ia)throw Error(`${ye(e)} has no ${an} — is the repository public, and has its action run?`);throw r}}async function Ds(e,t,n){if(e===ee){let s=await Ls(pp,cn,t,n);return{source:e,id:ee,manifest:s,entries:s.palettes}}let r=await LM(e,t,n),i=Ii(e,r);return{source:e,id:i,manifest:r,entries:Ma(r,i)}}function _i(e,t){if(t.source===ee){va(e,t.manifest);return}Jb(al(e),{recursive:!0}),K(qt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
417
- `)}function Gi(e,t){try{if(t===ee)return cn(qb(Vt(e),"utf8")).palettes;let n=or(e,t);return Ma(n,Ii(t,n))}catch{return[]}}function CM(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 eo(e,t,n){let r=Gi(e,t),i;try{i=await Ds(t,n)}catch(s){throw Bb(t,s.message),s}return _i(e,i),Bb(t,void 0),{source:t,id:i.id,...t===ee?{version:i.manifest.version}:{},count:Xe(i.entries).length,change:CM(r,i.entries)}}function dt(e){return`${e} palette${e===1?"":"s"}`}function to(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 Vb({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 cf(e){let t=Vb(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${dt(e.count)}${t?` (${t})`:""}`}function lf(e){return Vb(e.change)?`Updated ${cf(e)}`:void 0}async function ru(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=We(e,!1);mt(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 Rn(e,Ke(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ci(c,u.get(c.name))),t.terminals)}async function zb(e=ue()){try{if(!RM(tr(e)))return;let t=ne(e),n=uf(e,t);if(n.length===0)return;let r=Nn(e),i=wr(`Checking ${n.map(ye).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>eo(e,a,af)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>lf(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await ru(e,t,r,s)}catch{return}}var Db=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,jM=["add","remove","search","init"];function gf(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function KM(){try{let e=_M("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Db.test(e)?e:void 0}catch{return}}async function BM(e,t){if(t.author)return t.author;let n=KM();if(!n){if(!gf())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 ic({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Db.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(ht(r))throw Error("no handle given");n=r.toLowerCase()}return hn(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Wi(e,t){if(t===ee)return ee;return xe(t)?Et(un(t)):Ii(t,or(e,t))}function iu(e,t){try{return Wi(e,t)}catch{return}}function ew(e){return Me(e)??ee}function su(e){return We(e).palettes.filter((t)=>Me(t.name)===void 0)}function JM(e){let t=Ur(import.meta.dirname,"..","dist","manifest.json");return ff(t)?cn(hf(t,"utf8")).palettes:su(e)}function no(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==nr(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function tw(e,t,n,r){return t.find((i)=>i!==n&&!Si(i,n)&&iu(e,i)===r)}function df(e,t,n,r){let i=ne(e),s=st(i.markets),o=tw(e,s,t,n);if(o)throw Error(`${n} already names the market at ${ye(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};hn(e,no(i,s.includes(t)?s:[...s,t],a))}async function qM(e){if(!gf())return!1;let t=await bn({message:`Update ${e} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(ht(t))throw Error("no answer given — nothing was added");return t}async function nw(e){let t=wr(`Fetching ${ye(e)}`);try{return await Ds(e)}finally{t.done()}}async function VM(e,t,n){let r=await nw(n),i=ne(e),s=st(i.markets),o=tw(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${ye(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return hn(e,no(i,s.map((l)=>l===t?n:l),c)),_i(e,r),r}async function mf(e,t){let n=rr(t),r=st(ne(e).markets);if(r.includes(n))return console.log(`${ye(n)} is already added`),{source:n,id:Wi(e,n),fresh:!1};let i=yt(n)?r.find((u)=>yt(u)&&Si(u,n)):void 0;if(i){let u=await VM(e,i,n);return console.log(`Moved ${u.id} to ${ol(n)??"its default branch"} · ${ye(n)} — ${dt(Xe(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(xe(n)){let u=Et(un(n));df(e,n,u);let c=sr(n,u,su(e)).length;return console.log(`Added ${u} · ${ye(n)} — ${dt(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await nw(n),o=n===ee?void 0:await qM(s.id);df(e,n,s.id,o),_i(e,s);let a=dt(Xe(s.entries).length);return console.log(n===ee?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${ye(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function zM(e){let t=ue(),{source:n,id:r,fresh:i}=await mf(t,e);if(!i)return;if(xe(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===ee)console.log("\n`ttheme browse` picks them");else console.log(`
418
- \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function pf(e,t){if(t===ee)Qb(Vt(e),{force:!0});else if(yt(t))Qb(qt(e,t),{force:!0})}function bf(e){return`${dt(e.length)} installed from it keep${e.length===1?"s":""} working: ${e.join(", ")} — \`ttheme remove\` drops ${e.length===1?"it":"them"}`}function YM(e){let t=ue(),n=ne(t),r=st(n.markets),i=r.find((c)=>iu(t,c)===e)??r.find((c)=>c===rw(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=iu(t,i),o=n.palettes.filter((c)=>ew(c)===s),a=r.filter((c)=>c!==i),u=no(n,a,n.updates??{});if(hn(t,u),pf(t,i),mt(t,We(t),u),console.log(`Removed ${s??e} · ${ye(i)}`),o.length>0)console.log(bf(o))}function rw(e){try{return rr(e)}catch{return}}function QM(e,t){try{if(t===ee)return Xe(cn(hf(Vt(e),"utf8")).palettes).length;if(xe(t))return sr(t,Wi(e,t),su(e),!1).length;return or(e,t).palettes.length}catch{return}}function wf(e,t,n=On(),r=Date.now()){if(xe(t))return"read in place";let i=n[t],s=Xs(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${to(i.at,r)}`;return s===void 0?"never updated":`updated ${to(s,r)}`}function ZM(){let e=ue(),t=ne(e),n=st(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=On(),i=n.map((a)=>{let u=iu(e,a)??"?",c=QM(e,a),l=t.palettes.filter((d)=>ew(d)===u).length,f=xe(a)?[]:[`auto-update ${nr(a,t.updates)?"on":"off"}`];return{name:u,where:ye(a),note:[c===void 0?"Unreadable":dt(c),...l>0?[`${l} installed`]:[],...f,wf(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 $f(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function kf(e,t){let n=encodeURIComponent(`topic:${vi}${e?` ${e}`:""}`);try{let{items:r}=await Ls(`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 Na)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function XM(e){let t=ue(),n=await kf(e);if(n.length===0){console.log(`No repository carries the ${vi} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(st(ne(t).markets).map(er)),i=n.map((o)=>{let a=$f(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 DM=`name: ttheme market
427
+ }`;function Li(){return process.platform==="darwin"}function Za(t){return t>=HI&&t<=FI}function Ko(t,e,n){return new Promise((r,i)=>{let o=RI("osascript",["-l","JavaScript","-e",xI,t,e],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(PI)])}),s="";o.stderr.on("data",(a)=>{s+=a}),o.on("error",i),o.on("close",(a)=>{if(a===0){r();return}i(Error(s.trim().split(`
428
+ `).at(-1)||`osascript exited ${a}`))})})}var Mw=90000;function Xa(t,e){let n=X(t),r=fe(t,e).flatMap((i)=>{let[,o,s]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return o&&s&&q.some((a)=>a.key===o)?[{site:o,id:Number(s),...fl(n,i)}]:[]});return r.length>0?r:void 0}function TI(t,e){let n=new Set(Rt(X(t)).palettes[e.name]?.pictures.map((r)=>r.key));return(e.pictures??[]).filter((r)=>!n.has(Wt(r)))}function Ai(t,e){let n=new Set((e??[]).map((r)=>Wt(r)));return{...t,pictures:(t.pictures??[]).filter((r)=>!n.has(Wt(r)))}}async function AI(t,e,n,r,i,o){let s=q.find((w)=>w.key===n.site);if(!s)throw Error(`no site called ${n.site}`);o("Fetching");let a=await fi(s,n.id,i);if(!a)throw Error("the post is gone");if(s!==Ut&&a.md5)try{ea([a],await na([a.md5],i))}catch{}let c=ta(s,a)?Xs(s,a.id,i).then((w)=>{if(w)mo(a,w)},()=>{}):void 0;if(!Zs(s,a,Mr(process.env.TTHEME_FIND_RATING))||Vs(a,li(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let u=Ge(a);if(!u)throw Error("too large to use");let l=Ar(ke(s),"orig",`${n.id}.${u.ext}`),f;if(mf(l))f=new Uint8Array(Ti(l));else{o("Downloading");let w=Ir(s,a,u);f=await ra(w.site,w.url,i,(b,v)=>o("Downloading",Va(b,v))),x(l,f)}let d=Rn(f,Vt),m=!1;if(sn(d)===0&&Li()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let w=Ar(ke(s),"cut",`${n.id}.png`);try{if(!mf(w))o("Cutting out"),Ew(Sw(w),{recursive:!0}),await Ko(l,w,i);let b=Rn(new Uint8Array(Ti(w)),Vt);if(Za(sn(b)))d=b,m=!0}catch{}}await c;let g=cl(e);o("Drawing"),fa(t,g,Gn(g,e.signatureSlots),d,{site:s.key,id:n.id,ext:u.ext,bytes:f,from:`${s.name} ${n.id} ${s.pageUrl(n.id)}`,artist:a.named.artist,source:ho(a.source),cut:m},{width:0,height:0},Qn(t),Na(t));let $=fe(t,e.name).find((w)=>w.key===Wt(n));if($)So(X(t),$,n,r,LI())}function CI(t,e){let n=q.find((o)=>o.key===t.site),r=`${n?.name??t.site} ${t.id}`;if(!n||!e)return r;return`${zt()?Qi:`\x1B[${30+n.ansi}m${Qi}\x1B[39m`} ${Ws(r,n.pageUrl(t.id))}`}async function gn(t,e,n){let r=e.flatMap((c)=>TI(t,c).map((u)=>({entry:c,shared:u})));if(r.length===0)return;let i=Tr(n),o=process.stdout.isTTY&&fb(process.env),s=new Set,a=sr();for(let[c,{entry:u,shared:l}]of r.entries()){let f=`${u.name} · ${CI(l,o)}`,d=r.length>1?` · ${c+1}/${r.length}`:"",m=(g,$)=>a.set(`${g} ${f}${$?` · ${$}`:""}${d}`);try{await AI(t,u,l,i,AbortSignal.timeout(Mw),m),a.say(` ▣ ${f}`),s.add(u)}catch(g){a.say(` ▢ ${f} — ${g instanceof Error?g.message:String(g)}`)}}a.done();for(let c of s){let u=(c.pictures??[]).find((l)=>fe(t,c.name).some((f)=>f.key===Wt(l)));if(u)yi(t,c.name,Wt(u))}if(s.size>0)se(t)}function Iw(t,e,n){if(e.width!==t.width||e.height!==t.height)return!1;for(let r=0;r<t.width*t.height;r++)t.data[r*4+3]=e.data[r*4+n]??0;return!0}async function jI(t,e){let[,n,r]=/^(.+)_(\d+)$/.exec(t)??[],i=Ar(Tn(),n??"local","cut",`${r??t}.png`);if(!mf(i)){if(!Li())return;Ew(Sw(i),{recursive:!0}),await Ko(e,i,AbortSignal.timeout(Mw))}return Rn(new Uint8Array(Ti(i)),Vt)}function GI(t,e){try{return sn(le(new Uint8Array(Ti(Ar(t,`${e.stem}.png`)))))>0}catch{return!1}}function Qa(t,e){return()=>Rn(new Uint8Array(Ti(Ar(t,e.original))),Vt)}function Ow(t,e){let n=Qa(t,e);return()=>{let r=n(),i=le(new Uint8Array(Ti(Ar(t,e.cut))));return Iw(r,i,0)?r:null}}async function tc(t,e,n,r,i,o,s,a){let c=X(t),u=Rt(c).palettes[e]?.pictures.find((l)=>l.key===n);if(!u?.original)return null;if(u.cut)return Mo(t,e,u,Ow(c,u),r,i,o,s,!1,a);if($i(u)){let l=Qa(c,u)();if(sn(l)===0&&GI(c,u)){let f=await jI(n,Ar(c,u.original));if(!f||!Iw(l,f,3))return null;return Mo(t,e,u,()=>l,r,i,o,s,!0,a)}return Mo(t,e,u,()=>l,r,i,o,s,!1,a)}return Mo(t,e,u,Qa(c,u),r,i,o,s,!1,a)}function Nw(t,e,n,r,i,o){let s=X(t),a=Rt(s).palettes[e]?.pictures.find((u)=>u.key===n);if(!a?.original||$i(a))return!1;let c=a.cut?Ow(s,a):Qa(s,a);return Mp(t,e,a,c,r,i,o)}var zI=86400000,KI=3600000,pf=5000;function gf(){return Rw(process.env.XDG_STATE_HOME??Rw(_I(),".local","state"),"ttheme","markets.json")}function pn(){try{let t=JSON.parse(Fw(gf(),"utf8"));return Object.fromEntries(Object.entries(t).filter((e)=>typeof e[1]?.at==="number"&&typeof e[1].error==="string"))}catch{return{}}}function Pw(t,e){let n=pn();if(e===void 0){if(!(t in n))return;delete n[t]}else n[t]={at:Date.now(),error:e};Hw(BI(gf()),{recursive:!0}),x(gf(),`${JSON.stringify(n,null,2)}
429
+ `)}function qo(t,e){let n=e===J?Ie(t):te(e)?Me(t,e):void 0;try{return n?WI(n).mtimeMs:void 0}catch{return}}function qI(t,e,n,r){return t&&(e===void 0||r-e>=zI)&&(n===void 0||r-n>=KI)}function bf(t,e,n=Date.now()){let r=pn();return Ft(e.markets).filter((i)=>qI(_n(i,e.updates),qo(t,i),r[i]?.at,n))}async function JI(t,e,n){try{return await Po(Fp(t),El,e,n)}catch(r){if(r instanceof va)throw Error(`${et(t)} has no ${_e} — is the repository public, and has its action run?`);throw r}}async function Jo(t,e,n){if(t===J){let o=await Po(Zp,ze,e,n);return{source:t,id:J,manifest:o,entries:o.palettes}}let r=await JI(t,e,n),i=Ii(t,r);return{source:t,id:i,manifest:r,entries:ka(r,i)}}function Ci(t,e){if(e.source===J){$a(t,e.manifest);return}Hw(ml(t),{recursive:!0}),x(Me(t,e.source),`${JSON.stringify(e.manifest,null,2)}
430
+ `)}function ji(t,e){try{if(e===J)return ze(Fw(Ie(t),"utf8")).palettes;let n=qn(t,e);return ka(n,Ii(e,n))}catch{return[]}}function YI(t,e){let n=new Map(t.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(e.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,o])=>n.has(i)&&n.get(i)!==o).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function Yo(t,e,n){let r=ji(t,e),i;try{i=await Jo(e,n)}catch(o){throw Pw(e,o.message),o}return Ci(t,i),Pw(e,void 0),{source:e,id:i.id,...e===J?{version:i.manifest.version}:{},count:Mt(i.entries).length,change:YI(r,i.entries)}}function _t(t){return`${t} palette${t===1?"":"s"}`}function Do(t,e=Date.now()){let n=Math.floor(Math.max(0,e-t)/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 xw({added:t,changed:e,gone:n}){return[t.length>0?`${t.length} new`:"",e.length>0?`${e.length} changed`:"",n.length>0?`${n.length} gone`:""].filter(Boolean).join(", ")}function wf(t){let e=xw(t.change);return`${t.version?`${t.id} ${t.version}`:t.id} — ${_t(t.count)}${e?` (${e})`:""}`}function $f(t){return xw(t.change)?`Updated ${wf(t)}`:void 0}async function Vo(t,e,n,r){let i=new Set(r.flatMap((u)=>[...u.change.changed,...u.change.gone])),o=e.palettes.filter((u)=>i.has(u));if(o.length===0)return;let s=ct(t,!1);At(t,s,e);let a=new Set(r.flatMap((u)=>u.change.gone));for(let u of o.filter((l)=>a.has(l)))console.log(`${u} left its market — ttheme keeps the copy you have`);let c=new Map(n.map((u)=>[u.name,u.pictures]));await gn(t,wt(t,s,!1).palettes.filter((u)=>o.includes(u.name)&&c.has(u.name)).map((u)=>Ai(u,c.get(u.name))),e.terminals)}async function Lw(t=Y()){try{if(!UI(Wn(t)))return;let e=B(t),n=bf(t,e);if(n.length===0)return;let r=dn(t),i=sr(`Checking ${n.map(et).join(", ")} for updates`),o=(await Promise.allSettled(n.map((a)=>Yo(t,a,pf)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let s=o.flatMap((a)=>$f(a)??[]);if(s.length===0)return;for(let a of s)console.log(a);await Vo(t,e,r,o)}catch{return}}var Gw=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,XI=["add","remove","search","init"];function Ef(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function tO(){try{let t=DI("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Gw.test(t)?t:void 0}catch{return}}async function eO(t,e){if(e.author)return e.author;let n=tO();if(!n){if(!Ef())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 fu({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Gw.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(Lt(r))throw Error("no handle given");n=r.toLowerCase()}return Je(t,{...e,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Gi(t,e){if(e===J)return J;return ut(e)?ee(Be(e)):Ii(e,qn(t,e))}function ec(t,e){try{return Gi(t,e)}catch{return}}function Uw(t){return rt(t)??J}function nc(t){return ct(t).palettes.filter((e)=>rt(e.name)===void 0)}function nO(t){let e=Cr(import.meta.dirname,"..","dist","manifest.json");return kf(e)?ze(vf(e,"utf8")).palettes:nc(t)}function Zo(t,e,n){let{updates:r,...i}=t,o=Object.entries(n).filter(([s,a])=>e.includes(s)&&a!==_n(s,{}));return{...i,markets:e,...o.length>0?{updates:Object.fromEntries(o)}:{}}}function Ww(t,e,n,r){return e.find((i)=>i!==n&&!Mi(i,n)&&ec(t,i)===r)}function yf(t,e,n,r){let i=B(t),o=Ft(i.markets),s=Ww(t,o,e,n);if(s)throw Error(`${n} already names the market at ${et(s)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[e]:r};Je(t,Zo(i,o.includes(e)?o:[...o,e],a))}async function rO(t){if(!Ef())return!1;let e=await nn({message:`Update ${t} on its own when its author changes it? ttheme checks once a day, when you run it`,initialValue:!1});if(Lt(e))throw Error("no answer given — nothing was added");return e}async function _w(t){let e=sr(`Fetching ${et(t)}`);try{return await Jo(t)}finally{e.done()}}async function iO(t,e,n){let r=await _w(n),i=B(t),o=Ft(i.markets),s=Ww(t,o,n,r.id);if(s)throw Error(`${r.id} already names the market at ${et(s)} — \`ttheme market remove ${r.id}\` first`);let{[e]:a,...c}=i.updates??{},u=a===void 0?c:{...c,[n]:a};return Je(t,Zo(i,o.map((l)=>l===e?n:l),u)),Ci(t,r),r}async function Sf(t,e){let n=Bn(e),r=Ft(B(t).markets);if(r.includes(n))return console.log(`${et(n)} is already added`),{source:n,id:Gi(t,n),fresh:!1};let i=te(n)?r.find((c)=>te(c)&&Mi(c,n)):void 0;if(i){let c=await iO(t,i,n);return console.log(`Moved ${c.id} to ${hl(n)??"its default branch"} · ${et(n)} — ${_t(Mt(c.entries).length)}`),{source:n,id:c.id,fresh:!1}}if(ut(n)){let c=ee(Be(n));yf(t,n,c);let u=Kn(n,c,nc(t)).length;return console.log(`Added ${c} · ${et(n)} — ${_t(u)}, read in place`),{source:n,id:c,fresh:!0}}let o=await _w(n),s=n===J?void 0:await rO(o.id);yf(t,n,o.id,s),Ci(t,o);let a=_t(Mt(o.entries).length);return console.log(n===J?`Added the ttheme catalog — ${a}`:`Added ${o.id} · ${et(n)} — ${a}${s?", updating on its own":""}`),{source:n,id:o.id,fresh:!0}}async function oO(t){let e=Y(),{source:n,id:r,fresh:i}=await Sf(e,t);if(!i)return;if(ut(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===J)console.log("\n`ttheme browse` picks them");else console.log(`
431
+ \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function Mf(t,e){if(e===J)Aw(Ie(t),{force:!0});else if(te(e))Aw(Me(t,e),{force:!0})}function If(t){return`${_t(t.length)} installed from it keep${t.length===1?"s":""} working: ${t.join(", ")} — \`ttheme remove\` drops ${t.length===1?"it":"them"}`}function sO(t){let e=Y(),n=B(e),r=Ft(n.markets),i=r.find((u)=>ec(e,u)===t)??r.find((u)=>u===Bw(t));if(!i)throw Error(`no market named ${t} — \`ttheme market\` lists them`);let o=ec(e,i),s=n.palettes.filter((u)=>Uw(u)===o),a=r.filter((u)=>u!==i),c=Zo(n,a,n.updates??{});if(Je(e,c),Mf(e,i),At(e,ct(e),c),console.log(`Removed ${o??t} · ${et(i)}`),s.length>0)console.log(If(s))}function Bw(t){try{return Bn(t)}catch{return}}function aO(t,e){try{if(e===J)return Mt(ze(vf(Ie(t),"utf8")).palettes).length;if(ut(e))return Kn(e,Gi(t,e),nc(t),!1).length;return qn(t,e).palettes.length}catch{return}}function Of(t,e,n=pn(),r=Date.now()){if(ut(e))return"read in place";let i=n[e],o=qo(t,e);if(i&&(o===void 0||i.at>o))return`update failed ${Do(i.at,r)}`;return o===void 0?"never updated":`updated ${Do(o,r)}`}function cO(){let t=Y(),e=B(t),n=Ft(e.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=pn(),i=n.map((a)=>{let c=ec(t,a)??"?",u=aO(t,a),l=e.palettes.filter((d)=>Uw(d)===c).length,f=ut(a)?[]:[`auto-update ${_n(a,e.updates)?"on":"off"}`];return{name:c,where:et(a),note:[u===void 0?"Unreadable":_t(u),...l>0?[`${l} installed`]:[],...f,Of(t,a,r)].join(" · ")}}),o=Math.max(...i.map((a)=>a.name.length)),s=Math.max(...i.map((a)=>a.where.length));for(let a of i)console.log(` ${a.name.padEnd(o)} ${a.where.padEnd(s)} ${a.note}`)}function Nf(t){return`${t.owner.login.toLowerCase()}/${t.name}`}async function Rf(t,e){let n=encodeURIComponent(`topic:${Ei}${t?` ${t}`:""}`);try{let{items:r}=await Po(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,e);return r}catch(r){if(r instanceof Ea)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function uO(t){let e=Y(),n=await Rf(t);if(n.length===0){console.log(`No repository carries the ${Ei} topic${t?` and matches ${t}`:""} yet`);return}let r=new Set(Ft(B(e).markets).map(Un)),i=n.map((s)=>{let a=Nf(s);return{arg:a,added:r.has(a),stars:`★${s.stargazers_count}`,about:s.description??""}}),o=Math.max(...i.map((s)=>s.arg.length));for(let s of i)console.log(` ${s.added?"●":"○"} ${s.arg.padEnd(o)} ${s.stars.padStart(5)} ${s.about}`);console.log("\n`ttheme market add <name>` adds one")}var lO=`name: ttheme market
419
432
 
420
433
  on:
421
434
  push:
@@ -430,33 +443,35 @@ jobs:
430
443
  runs-on: ubuntu-latest
431
444
  steps:
432
445
  - uses: kecan0406/ttheme/market@v1
433
- `;function iw({name:e}){return`ttheme-${e}`}function eS(e,t){Yb(ya(e),{recursive:!0}),Yb(Ur(e,".github","workflows"),{recursive:!0}),sw(e,t,[]),K(Ur(e,".github","workflows","ttheme.yml"),DM),K(Ur(e,"README.md"),`# ${Et(t)}
446
+ `;function zw({name:t}){return`ttheme-${t}`}function fO(t,e){Tw(ma(t),{recursive:!0}),Tw(Cr(t,".github","workflows"),{recursive:!0}),Kw(t,e,[]),x(Cr(t,".github","workflows","ttheme.yml"),lO),x(Cr(t,"README.md"),`# ${ee(e)}
434
447
 
435
448
  A [ttheme](https://github.com/kecan0406/ttheme) market:
436
449
 
437
450
  \`\`\`sh
438
- ttheme market add ${t.owner}/${iw(t)}
451
+ ttheme market add ${e.owner}/${zw(e)}
439
452
  ttheme browse
440
453
  \`\`\`
441
- `)}function sw(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Ts(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};K(Ur(e,an),`${JSON.stringify(a,null,2)}
442
- `)}function ow(e){return on(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function aw(){if(!gf())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await ic({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>ow((t??"").toLowerCase())});if(ht(e))throw Error("no market name given");return e.toLowerCase()}async function uw(e,t){let n=xr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===rw(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 aw();return cw(e,ul(e,s),s)}async function cw(e,t,n){let r=!ff(Ur(t,an)),i;if(r){let o=ow(n);if(o)throw Error(`the market name ${n} ${o}`);if(ff(t)&&GM(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await BM(e,ne(e)),name:n},eS(t,i)}else i=un(t);let s=Et(i);return df(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ye(t)}`),{dir:t,...i,id:s}}function Zb(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function tS(e){let t=ue(),n=e&&!Zb(e)?e.toLowerCase():e?WM(rr(e)).toLowerCase():await aw(),r=e&&Zb(e)?rr(e):ul(t,n),i=await cw(t,r,n),s=`${i.owner}/${iw(i)}`;console.log(`
454
+ `)}function Kw(t,{owner:e,name:n},r){let{version:i,gate:o,placement:s}=vi(),a={version:i,gate:o,placement:s,owner:e,name:n,palettes:r};x(Cr(t,_e),`${JSON.stringify(a,null,2)}
455
+ `)}function qw(t){return ve(`x@${t}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function Jw(){if(!Ef())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let t=await fu({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(e)=>qw((e??"").toLowerCase())});if(Lt(t))throw Error("no market name given");return t.toLowerCase()}async function Yw(t,e){let n=Pr(t);if(e){let s=n.find((a)=>a.name===e||a.id===e||a.dir===Bw(e));if(!s)throw Error(`${e} is not one of your local markets — \`ttheme market init ${e}\` makes it one`);return s}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((s)=>s.name).join(", ")}`);let o=await Jw();return Dw(t,gl(t,o),o)}async function Dw(t,e,n){let r=!kf(Cr(e,_e)),i;if(r){let s=qw(n);if(s)throw Error(`the market name ${n} ${s}`);if(kf(e)&&VI(e).length>0)throw Error(`${e} is not empty — pick a new folder for the market`);i={owner:await eO(t,B(t)),name:n},fO(e,i)}else i=Be(e);let o=ee(i);return yf(t,e,o),console.log(`${r?"Made":"Added"} your market ${o} · ${et(e)}`),{dir:e,...i,id:o}}function Cw(t){return t.startsWith(".")||t.startsWith("/")||t.startsWith("~")}async function dO(t){let e=Y(),n=t&&!Cw(t)?t.toLowerCase():t?ZI(Bn(t)).toLowerCase():await Jw(),r=t&&Cw(t)?Bn(t):gl(e,n),i=await Dw(e,r,n),o=`${i.owner}/${zw(i)}`;console.log(`
443
456
  \`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:
444
457
 
445
- cd ${ye(r)}
458
+ cd ${et(r)}
446
459
  git init -b main && git add -A && git commit -m "${i.id}"
447
- gh repo create ${s} --public --source . --push
448
- gh repo edit ${s} --add-topic ${vi}
460
+ gh repo create ${o} --public --source . --push
461
+ gh repo edit ${o} --add-topic ${Ei}
449
462
 
450
- Its action rebuilds ${an} on every push; then \`ttheme market add ${s}\` works anywhere`)}function nS(e){let t=e?rr(e):process.cwd(),n=un(t),r=Et(n),i=JM(ue()),s=new Map,o=[],a=[];for(let u of ir(t))try{let c=xs(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=vt(`${r}/${u.slug}`,hf(u.path,"utf8"),i),f=Jt({...l,name:u.slug});o.push(u.catalog?{...f,catalog:u.catalog}:f)}catch(c){a.push(` ${UM(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:
463
+ Its action rebuilds ${_e} on every push; then \`ttheme market add ${o}\` works anywhere`)}function hO(t){let e=t?Bn(t):process.cwd(),n=Be(e),r=ee(n),i=nO(Y()),o=new Map,s=[],a=[];for(let c of zn(e))try{let u=Oo(c,o);if(u)throw Error(u);o.set(c.slug,c);let l=ne(`${r}/${c.slug}`,vf(c.path,"utf8"),i),f=de({...l,name:c.slug});s.push(c.catalog?{...f,catalog:c.catalog}:f)}catch(u){a.push(` ${QI(e,c.path)}: ${u.message}`)}if(a.length>0)return console.error(`${a.length} palettes cannot be read — the index was left as it was:
451
464
  ${a.join(`
452
- `)}`),1;for(let u of o){let l=As(u).filter((d)=>d.startsWith(" ✗")),f=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${f}${l.length>0?`
465
+ `)}`),1;for(let c of s){let l=No(c).filter((d)=>d.startsWith(" ✗")),f=c.catalog?`${c.catalog}/${c.name}`:c.name;console.log(` ${f}${l.length>0?`
453
466
  ${l.join(`
454
- `)}`:" passes the gate"}`)}return sw(t,n,o),console.log(`
455
- ${r} · ${dt(o.length)} → ${Ur(t,an)}`),0}async function lw(e,t){switch(e){case void 0:ZM();return;case"add":await zM(Xb(e,t));return;case"remove":YM(Xb(e,t));return;case"search":await XM(t);return;case"init":await tS(t);return;case"build":return nS(t);default:throw Error(`unknown market action ${e} — ${jM.join(", ")}, or none to list them`)}}function Xb(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 fw(e,t){let n=Wi(e,t);return`${n} — ${dt(sr(t,n,su(e),!1).length)}, read in place`}function io(e,t){return`${e}/${t}`}function dw(e){return Me(e.name)?wi(e.name):e.name}function ro(e){return e.catalog!==void 0&&gw(e.group)?io(e.group,e.catalog):void 0}function yf(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${io(e.group,e.name)}`;return e?.kind??""}function ou(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function hw(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((d)=>!d.default&&d.group===a.group),c=r?u.filter((d)=>ou(d,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((d)=>d.lead)??a,expanded:l,count:c.length}),!l)continue;let f=c.filter((d)=>ro(d)!==void 0);for(let d of new Set(f.map((h)=>h.catalog))){let h=f.filter((b)=>b.catalog===d),g=r.length>0||t.has(io(a.group,d));if(i.push({kind:"catalog",group:a.group,name:d,lead:h[0],expanded:g,count:h.length}),g)i.push(...h.map(o))}i.push(...c.filter((d)=>ro(d)===void 0).map(o))}return i}function rS(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||ou(i,n))).map((i)=>i.group));return hw(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function gw(e){return e.includes("@")}function Ef(e,t,n,r){let i=n-1;if(i<0)return e;let s;if(!Number.isFinite(t))s=t>0?i:0;else if(t>0)s=e>=i?0:Math.min(i,e+t);else s=e<=0?i:Math.max(0,e+t);return r(s)?s+Math.sign(t):s}function vf(e,t){let n={home:Number.NEGATIVE_INFINITY,end:Number.POSITIVE_INFINITY,pageup:-t,pagedown:t};return e===void 0?void 0:n[e]}function iS(e){let t=e.findIndex((n)=>n.kind==="group"&&gw(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 sS(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var $r="\x1B[0m",so="\x1B[2m",oo="\x1B[1m",jr="\x1B[22m",Mf="\x1B[36m",Sf="\x1B[33m";function au(e){return e==="decode"||e==="glitch"?e:"typewriter"}class ao{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+dw(t).length))}indent(e){return ro(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===""||ou(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)=>ou(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"?rS(this.entries,this.filter):hw(this.entries,this.expanded,this.filter);this.rows=n.length>0?iS([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[sS(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=yf(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>yf(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){this.cursor=Ef(this.cursor,e,this.rows.length,(t)=>this.rows[t]?.kind==="rule"),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)=>yf(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(io(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=ro(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?`${so}${"── Markets ──────────"}${$r}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(m)=>this.color?`${so}${m}${jr}`:m,s=(m)=>this.color?`${oo}${m}${jr}`:m,o=(m)=>this.color?` ${fh($a(m),r?Xt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${Xt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Uo(n.selection,n.foreground)} ${m} ${$r}`:`${a} ${m}`;if(e.kind==="all"){let m=this.everyone(this.rows).every((k)=>this.picked.has(k.name))?"●":"○";return u(`${m} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let m=this.pickedIn(e.name)===e.count?"●":"○",k=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${m} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i(k)}`)}let c=this.rows[this.cursor],l=(m,k)=>this.color&&c?.kind==="palette"&&m?`${oo}${Xt(c.entry.cursor)}${k}${jr}\x1B[39m`:s(k);if(e.kind==="group"){let m=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),k=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${k}`)}if(e.kind==="catalog"){let m=c?.kind==="palette"&&ro(c.entry)===io(e.group,e.name),k=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(m,e.name)} ${k}`)}let f=e.entry,d=this.picked.has(f.name)?"●":"○",h=this.indent(f),g=dw(f),b=this.color?g.padEnd(this.namePad-h.length):g,p=t?s(b):b;return u(`${h}${d} ${p}${o(f)}`)}}function If(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 uu{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 Nf extends Ft{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 ao({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 uu(e.fx??"typewriter",()=>If(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)=>{let r=vf(n?.name,this.list.maxItems);if(r!==void 0)this.list.move(r);else if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(h)=>this.color?`${so}${h}${$r}`:h,t=(h)=>this.color?`${Mf}${h}${$r}`:h,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((h)=>`${t("│")} ${h}`):[`${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",f=this.scope==="series"?"continue":"install",d=this.state==="error"?`${t("└")} ${this.color?`${Sf}${this.error}${$r}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,s,...u,c,d].join(`
456
- `)}}var uo=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],Pf=34,oS=72,aS=94,Rf={title:"",lines:[],brief:""};function cu(e){let t=e.trim();if(t!==ee&&!t.includes("/")&&!t.startsWith("~"))return;try{return rr(t)}catch{return}}function uS(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Of extends Ft{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 ao({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new ao({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new uu(e.fx??"typewriter",()=>If(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}let n=vf(t?.name,this.maxItems);if(n!==void 0)this.move(n);else 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 r=this.tab==="markets"?this.marketRow():void 0;if(r?.kind==="market"&&!this.adds.has(r.market.source))this.update(r.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=uo.findIndex((i)=>i.tab===this.tab),n=uo[(t+e+uo.length)%uo.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((i)=>i.kind==="rule"):this.problemRows().map(()=>!1);this.cursor[n]=Ef(this.cursor[n],e,r.length,(i)=>r[i]===!0)}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"&&!xe(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)=>Si(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(xe(e)||e===ee)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&&!cu(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=cu(this.filters.markets);if(i&&!n.some((o)=>Si(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:$f(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?`${so}${e}${jr}`:e}bold(e){return this.color?`${oo}${e}${jr}`:e}warn(e){return this.color?`${Sf}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${Xt(e.cursor)}▌\x1B[39m ${Uo(e.selection,e.foreground)} ${n} ${$r}`;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 ${ye(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!cu(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 uo.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===ee?"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 Rf;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((d)=>d.group===e.name&&!d.default),l=this.sourceOf(e.lead),f=`${dt(c.length)} · ${c.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?Qe(e.native,t).map((d)=>this.dim(d)):[],...Qe(l,t),f],brief:`${l} · ${f}`}}if(e.kind==="catalog"){let c=this.entries().filter((d)=>d.group===e.group&&d.catalog===e.name),l=this.sourceOf(e.lead),f=`${dt(c.length)} · ${c.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(e.name),lines:[e.group,...Qe(l,t),f],brief:`${e.group} · ${f}`}}let n=e.entry,r=this.sourceOf(n),i=Cs(n),s=`Gate ${bt.length-i.length}/${bt.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.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${oo}${Xt(n.cursor)}${n.name}${jr}\x1B[39m`:n.name,lines:[...Qe(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>Qe(c,t-2).map((l,f)=>`${f===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return Rf;if(e.kind==="market"){let i=e.market,s=i.source===ee?"The ttheme catalog":i.shown,o=i.entries.filter((h)=>!h.default),a=o.filter((h)=>this.installed.has(h.name)).map((h)=>h.name),u=`${dt(o.length)} · ${a.length} installed`,c=xe(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??uS(i.status),f=this.failed.get(i.source),d=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:[...Qe(s,t),u,"",xe(i.source)?c:`${c} ${this.dim("←→")}`,...xe(i.source)?[]:[l],...f?Qe(f,t).map((h)=>this.warn(h)):[],...d.length>0?["",...d.flatMap((h)=>Qe(h,t))]:[]],brief:[s,c,...d,...xe(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(ye(e.source)),lines:["Not added","",...Qe(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:[...Qe(`Repositories with the ${vi} topic`,t),...i&&!cu(i)?[`Matching "${i}"`]:[],"",...Qe(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}`,...Qe(e.repo.description??"",t),"",...Qe(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:Qe(r.message,e),brief:r.message}:Rf}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=(f)=>this.color?`${Mf}${f}${$r}`:f;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>=aS,r=n?Math.min(t-Pf-4,oS):t-1,{lines:i,below:s,empty:o}=this.body(),a=i.length>0?i.map((f)=>`${e("│")} ${f}`):[`${e("│")} ${this.dim(o)}`];while(a.length<this.maxItems)a.push(e("│"));let u=[`${e("◆")} ${this.tabBar()}`,wn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?Pf:r-2);return[...n?u.map((f,d)=>`${rt(f,r)} ${this.dim("│")} ${rt(d===0?c.title:c.lines[d-1]??"",Pf,!1)}`):[...u.map((f)=>rt(f,r,!1)),rt(`${e("│")} ${this.dim(c.brief)}`,r,!1)],rt(this.footer(e,n),t-1,!1)].join(`
457
- `)}}import{existsSync as ZN}from"node:fs";import{existsSync as So,mkdirSync as KN,readFileSync as ad}from"node:fs";import{dirname as BN}from"node:path";import{execFile as cS}from"node:child_process";import{createHash as ww}from"node:crypto";import{existsSync as lS,mkdtempSync as fS,readFileSync as hu,rmSync as dS,statSync as $w,writeFileSync as kw}from"node:fs";import{homedir as hS,tmpdir as gS}from"node:os";import{join as lu}from"node:path";import{fileURLToPath as mS}from"node:url";import{promisify as pS}from"node:util";var mn=pS(cS),fu=67108864,bS=4096,Hf=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],wS=["text/uri-list","text/plain;charset=utf-8","text/plain"],Ff=[...Hf,"text/uri-list","text/plain"];function $S(e){try{return $w(e).isFile()}catch{return!1}}function kS(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 mw(e){if(/^file:\/\//i.test(e))try{return mS(e)}catch{return}if(e.startsWith("~/"))return lu(hS(),e.slice(2));return e.startsWith("/")?e:void 0}function Ui(e,t=$S){let n=[];for(let r of e.replace(/\r\n?/g,`
467
+ `)}`:" passes the gate"}`)}return Kw(e,n,s),console.log(`
468
+ ${r} · ${_t(s.length)} → ${Cr(e,_e)}`),0}async function Vw(t,e){switch(t){case void 0:cO();return;case"add":await oO(jw(t,e));return;case"remove":sO(jw(t,e));return;case"search":await uO(e);return;case"init":await dO(e);return;case"build":return hO(e);default:throw Error(`unknown market action ${t} — ${XI.join(", ")}, or none to list them`)}}function jw(t,e){if(!e)throw Error(t==="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 e}function Zw(t,e){let n=Gi(t,e);return`${n} — ${_t(Kn(e,n,nc(t),!1).length)}, read in place`}function Xo(t,e){return`${t}/${e}`}function Qw(t){return rt(t.name)?gi(t.name):t.name}function Qo(t){return t.catalog!==void 0&&t0(t.group)?Xo(t.group,t.catalog):void 0}function Pf(t){if(t?.kind==="palette")return`palette ${t.entry.name}`;if(t?.kind==="group")return`group ${t.name}`;if(t?.kind==="catalog")return`catalog ${Xo(t.group,t.name)}`;return t?.kind??""}function rc(t,e){let n=e.toLowerCase();return[t.name,t.group,t.native??"",t.catalog??""].some((r)=>r.toLowerCase().includes(n))}function Xw(t,e,n){let r=n.trim(),i=[],o=new Set,s=(a)=>({kind:"palette",entry:a});for(let a of t){if(a.default||o.has(a.group))continue;o.add(a.group);let c=t.filter((d)=>!d.default&&d.group===a.group),u=r?c.filter((d)=>rc(d,r)):c;if(r&&u.length===0)continue;let l=r.length>0||e.has(a.group);if(i.push({kind:"group",name:a.group,native:a.native,lead:c.find((d)=>d.lead)??a,expanded:l,count:u.length}),!l)continue;let f=u.filter((d)=>Qo(d)!==void 0);for(let d of new Set(f.map((m)=>m.catalog))){let m=f.filter(($)=>$.catalog===d),g=r.length>0||e.has(Xo(a.group,d));if(i.push({kind:"catalog",group:a.group,name:d,lead:m[0],expanded:g,count:m.length}),g)i.push(...m.map(s))}i.push(...u.filter((d)=>Qo(d)===void 0).map(s))}return i}function mO(t,e){let n=e.trim(),r=new Set(t.filter((i)=>!i.default&&(n===""||rc(i,n))).map((i)=>i.group));return Xw(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function t0(t){return t.includes("@")}function Hf(t,e,n,r){let i=n-1;if(i<0)return t;let o;if(!Number.isFinite(e))o=e>0?i:0;else if(e>0)o=t>=i?0:Math.min(i,t+e);else o=t<=0?i:Math.max(0,t+e);return r(o)?o+Math.sign(e):o}function Ff(t,e){let n={home:Number.NEGATIVE_INFINITY,end:Number.POSITIVE_INFINITY,pageup:-e,pagedown:e};return t===void 0?void 0:n[t]}function gO(t){let e=t.findIndex((n)=>n.kind==="group"&&t0(n.name));return e>0&&t.slice(0,e).some((n)=>n.kind==="group")?[...t.slice(0,e),{kind:"rule"},...t.slice(e)]:t}function pO(t){let e=t.findIndex((n)=>n.kind==="palette");return e===-1?0:e}var ar="\x1B[0m",ts="\x1B[2m",es="\x1B[1m",jr="\x1B[22m",xf="\x1B[36m",Lf="\x1B[33m";function ic(t){return t==="decode"||t==="glitch"?t:"typewriter"}class ns{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(t){this.picked=t.picked,this.scope=t.scope??"palette",this.maxItems=t.maxItems??12,this.color=t.color??!0,this.onFocus=t.onFocus,this.load(t.entries),this.rebuild("first")}load(t){this.entries=t,this.named=t.filter((e)=>!e.default),this.series=[...new Set(this.named.map((e)=>e.group))],this.seriesPad=Math.max(0,...this.series.map((e)=>e.length)),this.namePad=Math.max(0,...this.named.map((e)=>this.indent(e).length+Qw(e).length))}indent(t){return Qo(t)===void 0?" ":" "}setEntries(t){this.load(t),this.rebuild("stay")}setFilter(t){if(t!==this.filter)this.filter=t,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(t,e){let n=this.scope==="palette"?this.filter.trim():"";return this.named.filter((r)=>r.group===t&&(e===void 0||r.catalog===e)&&(n===""||rc(r,n)))}everyone(t){return t.flatMap((e)=>e.kind==="group"?this.members(e.name):[])}pick(){let t=this.rows[this.cursor],e=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="catalog"?this.members(t.group,t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(e.length===0)return;let n=e.some((r)=>!this.picked.has(r));for(let r of e)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(t,e){return this.members(t,e).filter((n)=>this.picked.has(n.name)).length}pickedCount(){if(this.scope==="palette")return this.named.filter((t)=>this.picked.has(t.name)).length;return this.series.filter((t)=>this.members(t).every((e)=>this.picked.has(e.name))).length}total(){return this.scope==="series"?this.series.length:this.named.length}matched(){let t=this.filter.trim();if(this.scope==="series")return this.rows.filter((e)=>e.kind==="group").length;return t?this.named.filter((e)=>rc(e,t)).length:this.named.length}sync(){let t=this.rows[this.cursor],e=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(e&&e.name!==this.lastFocused)this.lastFocused=e.name,this.onFocus?.(e)}rebuild(t){let e=this.rows[this.cursor],n=this.scope==="series"?mO(this.entries,this.filter):Xw(this.entries,this.expanded,this.filter);this.rows=n.length>0?gO([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[pO(n)]):0;if(t==="first")this.cursor=r;else if(t==="keep"||t==="stay"){let i=Pf(e),o=e?.kind==="palette"||t==="stay"?this.rows.findIndex((s)=>Pf(s)===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){this.cursor=Hf(this.cursor,t,this.rows.length,(e)=>this.rows[e]?.kind==="rule"),this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}climb(t,e){this.expanded.delete(t),this.rebuild("clamp"),this.cursor=Math.max(0,this.rows.findIndex((n)=>Pf(n)===e)),this.sync()}fold(t){if(this.filter||this.scope==="series")return;let e=this.rows[this.cursor];if(e?.kind==="group"){if(t!==e.expanded)this.toggle(e.name)}else if(e?.kind==="catalog"){if(t!==e.expanded)this.toggle(Xo(e.group,e.name));else if(!t)this.climb(e.group,`group ${e.group}`)}else if(e?.kind==="palette"&&!t&&!e.entry.default){let n=Qo(e.entry);if(n===void 0)this.climb(e.entry.group,`group ${e.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 t=this.rows.slice(this.top,this.top+this.maxItems);return{lines:t.map((e,n)=>this.renderRow(e,this.top+n===this.cursor)),below:this.rows.length-this.top-t.length}}renderRow(t,e){if(t.kind==="rule")return` ${this.color?`${ts}${"── Markets ──────────"}${ar}`:"── Markets ──────────"}`;let n=t.kind==="palette"?t.entry:t.kind==="all"?void 0:t.lead,r=this.color&&e&&n!==void 0,i=(b)=>this.color?`${ts}${b}${jr}`:b,o=(b)=>this.color?`${es}${b}${jr}`:b,s=(b)=>this.color?` ${Ah(da(b),r?xe(b.foreground):"\x1B[39m")}`:"",a=e?r?`${xe(n.cursor)}▌\x1B[39m `:"▌ ":" ",c=(b)=>r?`${a}${Us(n.selection,n.foreground)} ${b} ${ar}`:`${a} ${b}`;if(t.kind==="all"){let b=this.everyone(this.rows).every((v)=>this.picked.has(v.name))?"●":"○";return c(`${b} Select all ${i(`(${t.count})`)}`)}if(t.kind==="group"&&this.scope==="series"){let b=this.pickedIn(t.name)===t.count?"●":"○",v=`(${t.count})${t.native?` ${t.native}`:""}`;return c(`${b} ${o(t.name.padEnd(this.seriesPad))}${s(t.lead)}${this.color?" ":" "}${i(v)}`)}let u=this.rows[this.cursor],l=(b,v)=>this.color&&u?.kind==="palette"&&b?`${es}${xe(u.entry.cursor)}${v}${jr}\x1B[39m`:o(v);if(t.kind==="group"){let b=l(u?.kind==="palette"&&u.entry.group===t.name,t.name),v=t.native?` ${i(t.native)}`:"";return c(`${t.expanded?"▾":"▸"} ${b} ${i(`(${this.pickedIn(t.name)}/${t.count})`)}${v}`)}if(t.kind==="catalog"){let b=u?.kind==="palette"&&Qo(u.entry)===Xo(t.group,t.name),v=i(`(${this.pickedIn(t.group,t.name)}/${t.count})`);return c(` ${t.expanded?"▾":"▸"} ${l(b,t.name)} ${v}`)}let f=t.entry,d=this.picked.has(f.name)?"●":"○",m=this.indent(f),g=Qw(f),$=this.color?g.padEnd(this.namePad-m.length):g,w=e?o($):$;return c(`${m}${d} ${w}${s(f)}`)}}function Tf(t){let e=t.named[Math.floor(Math.random()*t.named.length)],n=t.series[Math.floor(Math.random()*t.series.length)];return e&&n?`${e.name} | ${n}`:""}class oc{fx;make;redraw;roller;example="";step=0;seed=0;timer;constructor(t,e,n){this.fx=t,this.make=e,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 t=this.make();this.example=t.length>30?`${t.slice(0,29)}…`:t,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 t=Math.floor(this.example.length*(8-this.step)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let e=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.seed)%3<t||n(r)?r:e[Math.floor(Math.random()*e.length)]??r).join("")}}class Af extends Yt{picked;list;scope;color;hint;lastInput="";constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`Pick at least one ${this.scope}`:void 0:void 0},!0);this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.color=t.color??!0,this.list=new ns({entries:t.entries,picked:this.picked,scope:this.scope,...t.maxItems===void 0?{}:{maxItems:t.maxItems},color:this.color,...t.onFocus?{onFocus:t.onFocus}:{}}),this.hint=new oc(t.fx??"typewriter",()=>Tf(this.list),()=>this.output.emit("resize")),this.once("finalize",()=>this.hint.stop()),this.on("cursor",(e)=>{if(e==="up")this.list.move(-1);else if(e==="down")this.list.move(1);else if(e==="left")this.list.fold(!1);else if(e==="right")this.list.fold(!0)}),this.on("userInput",(e)=>{if(e!==this.lastInput)this.lastInput=e,this.list.setFilter(e)}),this.on("key",(e,n)=>{let r=Ff(n?.name,this.list.maxItems);if(r!==void 0)this.list.move(r);else if(n?.name==="space")this.list.pick()})}_isActionKey(t){return t==="\t"||t===" "}draw(){let t=(m)=>this.color?`${ts}${m}${ar}`:m,e=(m)=>this.color?`${xf}${m}${ar}`:m,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${t("◇")} ${n} ${t(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${n} · cancelled`)}`;let r=`${e("◆")} ${n} ${t(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),o=`${e("│")} ${this.userInput?`${this.userInput}_`:t(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:s,below:a}=this.list.window(),c=s.length>0?s.map((m)=>`${e("│")} ${m}`):[`${e("│")} ${t(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(c.length<this.list.maxItems)c.push(e("│"));let u=a>0?`${e("│")} ${t(`↓ ${a} more`)}`:e("│"),l=this.scope==="series"?"":" · ←→ fold",f=this.scope==="series"?"continue":"install",d=this.state==="error"?`${e("└")} ${this.color?`${Lf}${this.error}${ar}`:this.error}`:`${e("└")} ${t(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,o,...c,u,d].join(`
469
+ `)}}var rs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],Cf=34,bO=72,e0=94,n0=40,r0=10,wO=3,jf={title:"",lines:[],brief:""};function sc(t){let e=t.trim();if(e!==J&&!e.includes("/")&&!e.startsWith("~"))return;try{return Bn(e)}catch{return}}function $O(t){return t.charAt(0).toUpperCase()+t.slice(1)}class Gf extends Yt{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;hub;maxItems=12;paint;catalog;mine;hint;asking;leaving;shifted=!1;goto;repos;searching=!1;searchError;lastInput="";constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output},!0);Object.assign(this,{render:()=>this.screen()}),this.markets=t.markets,this.problems=t.problems,this.kept=t.kept,this.installed=new Set(t.installed),this.startup=t.startup,this.io=t.io,this.order=t.order??((r)=>r),this.color=t.color??!0,this.hub=t.hub,this.paint=t.onFocus,this.picked=new Set(t.installed);let e=this.entries();this.catalog=new ns({entries:e,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(r)=>this.focus("catalog",r)}),this.mine=new ns({entries:this.mineOf(e),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(r)=>this.focus("installed",r)}),this.hint=new oc(t.fx??"typewriter",()=>Tf(this.tab==="installed"?this.mine:this.catalog),()=>this.redraw());let n=(r,i)=>{this.shifted=i?.shift===!0};this.input.on("keypress",n),this.once("finalize",()=>{this.hint.stop(),this.input.off("keypress",n)}),this.on("cursor",(r)=>{if(this.asking||this.leaving!==void 0||this.shifted)return;if(r==="up"||r==="down")this.move(r==="up"?-1:1);else if(r==="left"||r==="right")this.side(r==="right")}),this.on("userInput",(r)=>{if(r!==this.lastInput)this.lastInput=r,this.filters[this.tab]=r,this.list()?.setFilter(r)}),this.on("key",(r,i)=>this.key(r,i));for(let r of t.due)this.update(r)}_isActionKey(t){return t==="\t"||t===" "||(this.asking!==void 0||this.leaving!==void 0)&&t!==void 0}_shouldSubmit(){return this.asking===void 0&&this.leaving===void 0}next(){return this.goto}async idle(){await Promise.allSettled([...this.inflight])}result(){let t=new Set(this.entries().map((e)=>e.name));return{picked:new Set([...this.picked].filter((e)=>t.has(e))),adds:[...this.adds.values()],removes:[...this.removes],auto:Object.fromEntries(this.want),refreshed:this.refreshed}}key(t,e){if(this.leaving!==void 0){if(e?.name==="escape")this.leaving=void 0,Object.assign(e,{name:"answered",sequence:""});else if(t&&/^[yn]$/i.test(t)){if(t.toLowerCase()==="y")this.state="submit";else this.goto=this.leaving,this.state="cancel";this.leaving=void 0}return}if(this.asking){if(e?.name==="escape")this.asking=void 0,Object.assign(e,{name:"answered",sequence:""});else if(t&&/^[yn]$/i.test(t))this.answer(t.toLowerCase()==="y");return}let n=Ff(e?.name,this.maxItems);if(n!==void 0)this.move(n);else if(e?.name==="tab"){if(this.hub)this.leave(ib(this.hub,e.shift?-1:1))}else if(e?.shift&&(e.name==="left"||e.name==="right"))this.switchTab(e.name==="right"?1:-1);else if(e?.name==="space")this.activate();else if(e?.ctrl&&e.name==="r"){let r=this.tab==="markets"?this.marketRow():void 0;if(r?.kind==="market"&&!this.adds.has(r.market.source))this.update(r.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(t,e){if(this.tab===t&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(e)}track(t){this.inflight.add(t);let e=()=>this.inflight.delete(t);return t.then(e,e),t}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((t)=>!this.removes.has(t.source)),...this.adds.values()]}entries(){let t=this.active().flatMap((i)=>i.entries),e=new Set(t.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)&&!e.has(i.name))n.set(i.name,i);return this.order([...t,...n.values()])}mineOf(t){return t.filter((e)=>this.installed.has(e.name))}reload(){let t=this.entries();this.catalog.setEntries(t),this.mine.setEntries(this.mineOf(t))}switchTab(t){let e=rs.findIndex((i)=>i.tab===this.tab),n=rs[(e+t+rs.length)%rs.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(t){let e=this.list();if(e){e.move(t);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((i)=>i.kind==="rule"):this.problemRows().map(()=>!1);this.cursor[n]=Hf(this.cursor[n],t,r.length,(i)=>r[i]===!0)}side(t){let e=this.list();if(e){e.fold(t);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!ut(n.market.source))if(t===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,t)}activate(){let t=this.list();if(t){t.pick();return}let e=this.tab==="markets"?this.marketRow():void 0;if(e?.kind==="market")this.toggleMarket(e.market);else if(e?.kind==="add")this.fetch(e.source);else if(e?.kind==="repo"){let n=this.known(e.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(e.source)}else if(e?.kind==="find")this.search()}toggleMarket(t){if(this.adds.has(t.source))this.adds.delete(t.source),this.want.delete(t.source);else if(this.removes.has(t.source))this.removes.delete(t.source);else this.removes.add(t.source);this.reload()}known(t){return[...this.markets,...this.adds.values()].find((e)=>Mi(e.source,t))}fetch(t){if(this.busy.has(t))return;this.failed.delete(t),this.busy.set(t,"Fetching…"),this.track(this.io.fetch(t)).then((e)=>{this.busy.delete(t);let n=this.active().find((r)=>r.id===e.id);if(n)this.failed.set(t,`${e.id} already names the market at ${n.shown}`);else if(ut(t)||t===J)this.stage(e,e.auto);else this.asking=e;this.redraw()},(e)=>{this.busy.delete(t),this.failed.set(t,e.message),this.redraw()})}answer(t){let e=this.asking;if(this.asking=void 0,e)this.stage(e,t)}stage(t,e){if(this.adds.set(t.source,t),e===t.auto)this.want.delete(t.source);else this.want.set(t.source,e);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===t.source))}update(t){if(this.busy.has(t))return;this.failed.delete(t),this.busy.set(t,"Updating…"),this.track(this.io.refresh(t)).then(({market:e,refreshed:n})=>{this.busy.delete(t),this.markets=this.markets.map((r)=>r.source===t?e:r),this.problems=this.problems.filter((r)=>r.source!==t),this.refreshed.push(n),this.reload(),this.redraw()},(e)=>{this.busy.delete(t),this.failed.set(t,`Update failed: ${e.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let t=this.filters.markets.trim();this.track(this.io.search(t&&!sc(t)?t:void 0)).then((e)=>{this.searching=!1,this.repos=e,this.redraw()},(e)=>{this.searching=!1,this.searchError=e.message,this.redraw()})}marketRows(){let t=this.filters.markets.trim().toLowerCase(),e=(...s)=>t===""||s.some((a)=>a.toLowerCase().includes(t)),n=[...this.markets,...this.adds.values()],r=n.filter((s)=>e(s.id,s.shown,s.source)).map((s)=>({kind:"market",market:s})),i=sc(this.filters.markets);if(i&&!n.some((s)=>Mi(s.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let o=(this.repos??[]).map((s)=>({repo:s,source:Nf(s)})).filter(({repo:s,source:a})=>e(a,s.description??""));if(o.length>0)r.push({kind:"rule"},...o.map(({repo:s,source:a})=>({kind:"repo",repo:s,source:a})));return r}marketRow(){let t=this.marketRows();return t[Math.min(this.cursor.markets,t.length-1)]}problemList(){let t=new Map([...this.markets,...this.adds.values()].map((e)=>[e.source,e.id]));return[...this.problems.filter((e)=>!(e.update&&e.source&&this.failed.has(e.source))),...[...this.failed].map(([e,n])=>({where:t.get(e)??e,message:n,source:e}))]}problemRows(){let t=this.filters.errors.trim().toLowerCase();return this.problemList().filter((e)=>t===""||`${e.where} ${e.message}`.toLowerCase().includes(t))}windowOf(t,e,n,r=()=>!1){let i=Math.min(this.cursor[e],Math.max(0,t.length-1));if(r(t[i]))i-=1;this.cursor[e]=i;let o=Math.min(this.top[e],i);if(i>=o+this.maxItems)o=i-this.maxItems+1;o=Math.max(0,Math.min(o,t.length-this.maxItems)),this.top[e]=o;let s=t.slice(o,o+this.maxItems);return{lines:s.map((a,c)=>n(a,o+c===i)),below:t.length-o-s.length}}dim(t){return this.color?`${ts}${t}${jr}`:t}bold(t){return this.color?`${es}${t}${jr}`:t}warn(t){return this.color?`${Lf}${t}\x1B[39m`:t}lit(t,e,n){if(e&&this.color&&t)return`${xe(t.cursor)}▌\x1B[39m ${Us(t.selection,t.foreground)} ${n} ${ar}`;return`${e?"▌ ":" "} ${n}`}status(t){return this.adds.has(t.source)?"Will add":this.removes.has(t.source)?"Will remove":this.busy.get(t.source)??(this.failed.has(t.source)||t.status.startsWith("update failed")?"Update failed":"")}marketLine(t,e){if(t.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(t.kind==="market"){let i=t.market,o=this.status(i),s=this.removes.has(i.source)?"○":"●",a=e?this.bold(i.id):i.id;return this.lit(i.entries.find((c)=>!c.default),e,`${s} ${a}${o?` ${this.dim(o)}`:""}`)}if(t.kind==="add"){let i=this.busy.get(t.source);return this.lit(void 0,e,`+ Add ${et(t.source)}${i?` ${this.dim(i)}`:""}`)}if(t.kind==="find"){let i=this.filters.markets.trim(),o=this.searching?"Searching GitHub…":i&&!sc(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,e,`⌕ ${o}`)}let n=this.busy.get(t.source),r=this.known(t.source)?"●":"○";return this.lit(void 0,e,`${r} ${t.source} ${this.dim(`★${t.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(t,e){return this.lit(void 0,e,`${this.warn("✗")} ${t.where} ${this.dim(t.message)}`)}body(){let t=this.list();if(t){let n=this.filters[this.tab];return{...t.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 e=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:e?`No problems match '${e}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}dirty(){let{picked:t}=this.result();return this.changes()>0||t.size!==this.installed.size||[...t].some((e)=>!this.installed.has(e))}leave(t){if(this.dirty()){this.leaving=t;return}this.goto=t,this.state="cancel"}counts(){let t=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",e=this.list();if(e)return`${t}${e.matched()}/${e.total()} · ${e.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((o)=>o.kind==="market").length,i=this.changes();return`${t}${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 t=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${t?` e.g. ${t}`:""}`)}tabBar(){return rs.map(({tab:t,title:e})=>{let n=t==="errors"?this.problemList().length:0,r=n>0?`${e} ${n}`:e;if(!this.color)return t===this.tab?`[${r}]`:` ${r} `;return t===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(t){let e=this.active().find((n)=>n.entries.some((r)=>r.name===t.name));if(!e)return"In no market you added";return e.source===J?"The ttheme catalog":e.shown}paletteState(t){let e=this.picked.has(t.name),n=this.installed.has(t.name),r=e&&n?"Installed":e?"Will install":n?"Will remove":"Not installed";return this.startup===t.name?`${r} · Default`:r}paletteDetail(t,e){if(!t||t.kind==="rule")return jf;if(t.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(t.kind==="group"){let u=this.entries().filter((d)=>d.group===t.name&&!d.default),l=this.sourceOf(t.lead),f=`${_t(u.length)} · ${u.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(t.name),lines:[...t.native?kt(t.native,e).map((d)=>this.dim(d)):[],...kt(l,e),f],brief:`${l} · ${f}`}}if(t.kind==="catalog"){let u=this.entries().filter((d)=>d.group===t.group&&d.catalog===t.name),l=this.sourceOf(t.lead),f=`${_t(u.length)} · ${u.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(t.name),lines:[t.group,...kt(l,e),f],brief:`${t.group} · ${f}`}}let n=t.entry,r=this.sourceOf(n),i=Ho(n),o=`Gate ${Dt.length-i.length}/${Dt.length}`,s=n.pictures?.length??0,a=[...s>0?[`${s} picture${s===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),c=rt(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${es}${xe(n.cursor)}${n.name}${jr}\x1B[39m`:n.name,lines:[...kt(r,e),...c,this.paletteState(n),"",i.length===0?`${o} · passes`:o,...i.flatMap((u)=>kt(u,e-2).map((l,f)=>`${f===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,o,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(t,e){if(!t||t.kind==="rule")return jf;if(t.kind==="market"){let i=t.market,o=i.source===J?"The ttheme catalog":i.shown,s=i.entries.filter((m)=>!m.default),a=s.filter((m)=>this.installed.has(m.name)).map((m)=>m.name),c=`${_t(s.length)} · ${a.length} installed`,u=ut(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??$O(i.status),f=this.failed.get(i.source),d=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:[...kt(o,e),c,"",ut(i.source)?u:`${u} ${this.dim("←→")}`,...ut(i.source)?[]:[l],...f?kt(f,e).map((m)=>this.warn(m)):[],...d.length>0?["",...d.flatMap((m)=>kt(m,e))]:[]],brief:[o,u,...d,...ut(i.source)?[]:[l]].join(" · ")}}if(t.kind==="add"){let i=this.busy.get(t.source)??this.failed.get(t.source)??"space fetches its index";return{title:this.bold(et(t.source)),lines:["Not added","",...kt(i,e)],brief:i}}if(t.kind==="find"){let i=this.filters.markets.trim(),o=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...kt(`Repositories with the ${Ei} topic`,e),...i&&!sc(i)?[`Matching "${i}"`]:[],"",...kt(o,e)],brief:o}}let r=this.known(t.source)?"Added":this.busy.get(t.source)??this.failed.get(t.source)??"space adds it";return{title:this.bold(t.source),lines:[`★ ${t.repo.stargazers_count}`,...kt(t.repo.description??"",e),"",...kt(r,e)],brief:r}}detail(t){let e=this.list();if(e)return this.paletteDetail(e.focusedRow(),t);if(this.tab==="markets")return this.marketDetail(this.marketRow(),t);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:kt(r.message,t),brief:r.message}:jf}footer(t,e){if(this.leaving!==void 0)return`${t("└")} Apply your changes before you leave? ${this.dim("y apply · n discard · esc stay")}`;if(this.asking)return`${t("└")} Update ${this.asking.id} on its own when its author changes it? ${this.dim("y yes · n no · esc back")}`;let n={catalog:["⇧←→ switch","↑↓ move","←→ fold","space pick",e?"type to filter":""],installed:["⇧←→ switch","↑↓ move","←→ fold","space pick",e?"type to filter":""],markets:["⇧←→ switch","space add/remove","←→ auto-update",e?"ctrl+r update":""],errors:["⇧←→ switch","↑↓ move","type to filter"]}[this.tab];return`${t("└")} ${this.dim([...n.filter(Boolean),"enter apply","esc cancel"].join(" · "))}`}columns(){return this.output.columns??100}rows(){return this.output.rows??24}fitItems(t){let e=Math.max(wO,this.rows()-4-(t>=e0?0:1)-(this.hub?1:0));this.maxItems=e,this.catalog.maxItems=e,this.mine.maxItems=e}screen(){if(this.state==="submit"||this.state==="cancel")return;let t=this.rows(),e=this.draw().split(`
470
+ `),r=`\x1B[?2026h${this.state==="initial"?"\x1B[?25l":""}`;for(let i=0;i<t;i++)r+=`\x1B[${i+1};1H${e[i]??""}\x1B[K`;if(this.output.write(`${r}\x1B[H\x1B[?2026l`),this.state==="initial")this.state="active"}draw(){let t=this.columns();if(t<n0||this.rows()<r0)return`Needs ${n0}×${r0} — now ${t}×${this.rows()}
471
+ ${this.dim("esc cancels")}`;let e=(f)=>this.color?`${xf}${f}${ar}`:f,n=t>=e0,r=n?Math.min(t-Cf-4,bO):t-1;this.fitItems(t);let{lines:i,below:o,empty:s}=this.body(),a=i.length>0?i.map((f)=>`${e("│")} ${f}`):[`${e("│")} ${this.dim(s)}`];while(a.length<this.maxItems)a.push(e("│"));let c=[`${e("◆")} ${this.tabBar()}`,be(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,o>0?`${e("│")} ${this.dim(`↓ ${o} more`)}`:e("│")],u=this.detail(n?Cf:r-2),l=n?c.map((f,d)=>`${Et(f,r)} ${this.dim("│")} ${Et(d===0?u.title:u.lines[d-1]??"",Cf,!1)}`):[...c.map((f)=>Et(f,r,!1)),Et(`${e("│")} ${this.dim(u.brief)}`,r,!1)];return[...this.hub?[Et(ob(this.hub,this.color),t-1,!1)]:[],...l,Et(this.footer(e,n),t-1,!1)].join(`
472
+ `)}}import{existsSync as hP}from"node:fs";import{existsSync as ys,mkdirSync as iP,readFileSync as Ed}from"node:fs";import{dirname as oP}from"node:path";class Pe extends Error{}import{execFile as kO}from"node:child_process";import{createHash as a0}from"node:crypto";import{existsSync as yO,mkdtempSync as vO,readFileSync as lc,rmSync as EO,statSync as c0,writeFileSync as u0}from"node:fs";import{homedir as SO,tmpdir as MO}from"node:os";import{join as ac}from"node:path";import{fileURLToPath as IO}from"node:url";import{promisify as OO}from"node:util";var De=OO(kO),cc=67108864,NO=4096,_f=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],RO=["text/uri-list","text/plain;charset=utf-8","text/plain"],Uf=[..._f,"text/uri-list","text/plain"];function PO(t){try{return c0(t).isFile()}catch{return!1}}function HO(t){let e=[],n="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else n+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))n+=t[++o];else n+=s;else if(s==="\\"&&o+1<t.length)n+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)e.push(n);n="",i=!1}else n+=s,i=!0}if(i)e.push(n);return e}function i0(t){if(/^file:\/\//i.test(t))try{return IO(t)}catch{return}if(t.startsWith("~/"))return ac(SO(),t.slice(2));return t.startsWith("/")?t:void 0}function Ui(t,e=PO){let n=[];for(let r of t.replace(/\r\n?/g,`
458
473
  `).split(`
459
- `)){let i=mw(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of kS(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=mw(s);if(o&&t(o))n.push(o)}}return n}function yS(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 pw(e){let t=fi(e)?Jn(e):yS(e);if(!t)return;return{ext:fi(e)?"png":"jpg",width:t.width,height:t.height}}async function du(e,t){let n=pw(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=fS(lu(gS(),"ttheme-attach-"));try{let i=lu(r,"in"),s=lu(r,"out.png");kw(i,e);let o=!n||n.width*n.height>$t?["--resampleHeightWidthMax",String(bS)]:[];await mn("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(hu(s)),u=pw(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{dS(r,{recursive:!0,force:!0})}}async function xf(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":Lc},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>fu)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 du(r,e)}if($w(e).size>fu)throw Error("that picture is over 64 MB");return du(new Uint8Array(hu(e)),e)}var yw=new Map,Kr={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)=>yw.get(e)??"",parse:()=>[],count:()=>0};function Ew(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function vw(e,t){yw.set(e,t)}function Mw(e){return Number.parseInt(ww("sha1").update(e).digest("hex").slice(0,8),16)%Qn}var ES=`ObjC.import('AppKit')
474
+ `)){let i=i0(r.trim());if(i&&e(i)){n.push(i);continue}for(let o of HO(r)){if(/^https?:\/\/\S+$/i.test(o)){n.push(o);continue}let s=i0(o);if(s&&e(s))n.push(s)}}return n}function o0(t){let e=Er(t)?Pn(t):xu(t);if(!e)return;return{ext:Er(t)?"png":"jpg",width:e.width,height:e.height}}async function uc(t,e){let n=o0(t);if(n&&n.width*n.height<=Vt)return{bytes:t,...n,source:e};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${Vt/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=vO(ac(MO(),"ttheme-attach-"));try{let i=ac(r,"in"),o=ac(r,"out.png");u0(i,t);let s=!n||n.width*n.height>Vt?["--resampleHeightWidthMax",String(NO)]:[];await De("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(lc(o)),c=o0(a);if(!c)throw Error("that is not a picture macOS can read");return{bytes:a,...c,source:e}}finally{EO(r,{recursive:!0,force:!0})}}async function Bf(t,e){if(/^https?:\/\//i.test(t)){let n=await fetch(t,{headers:{"User-Agent":Uu},signal:e});if(!n.ok)throw Error(`${new URL(t).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>cc)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return uc(r,t)}if(c0(t).size>cc)throw Error("that picture is over 64 MB");return uc(new Uint8Array(lc(t)),t)}var l0=new Map,Gr={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,ors:!1,vouched:!0,scored:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",narrow:()=>[],postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>l0.get(t)??"",parse:()=>[],count:()=>0};function f0(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function d0(t,e){l0.set(t,e)}function h0(t){return Number.parseInt(a0("sha1").update(t).digest("hex").slice(0,8),16)%Ln}var FO=`ObjC.import('AppKit')
460
475
  function run(argv) {
461
476
  const pb = $.NSPasteboard.generalPasteboard
462
477
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -481,16 +496,16 @@ function run(argv) {
481
496
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
482
497
  const text = pb.stringForType('public.utf8-plain-text')
483
498
  return text && !text.isNil() ? text.js : ''
484
- }`,vS=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
499
+ }`,xO=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
485
500
  $c = [Windows.Forms.Clipboard]
486
501
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
487
502
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
488
503
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
489
504
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
490
- $c::GetText()`;function Sw(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(hu("/proc/version","utf8"))}catch{return!1}}async function MS(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await mn(n[0],n[1])).stdout.split(`
491
- `).map((o)=>o.trim()),i=(o)=>t?mn("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:fu}):mn("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:fu});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Hf.find((o)=>r.includes(o));if(s)return kw(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 Af(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Iw(e){if(process.platform==="darwin"){let t=(await mn("osascript",["-l","JavaScript","-e",ES,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Sw()){let t=(await mn("powershell.exe",["-NoProfile","-STA","-Command",vS])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
492
- `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await mn("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
493
- `)}}if(process.platform==="linux")return MS(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var SS=`ObjC.import('AppKit')
505
+ $c::GetText()`;function m0(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(lc("/proc/version","utf8"))}catch{return!1}}async function LO(t){let e=Boolean(process.env.WAYLAND_DISPLAY),n=e?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await De(n[0],n[1])).stdout.split(`
506
+ `).map((s)=>s.trim()),i=(s)=>e?De("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:cc}):De("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:cc});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=_f.find((s)=>r.includes(s));if(o)return u0(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function zf(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function g0(t){if(process.platform==="darwin"){let e=(await De("osascript",["-l","JavaScript","-e",FO,t])).stdout.trim();return e===t?{image:t}:{text:e}}if(m0()){let e=(await De("powershell.exe",["-NoProfile","-STA","-Command",xO])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(e.split(`
507
+ `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await De("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
508
+ `)}}if(process.platform==="linux")return LO(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var TO=`ObjC.import('AppKit')
494
509
  function run() {
495
510
  const pb = $.NSPasteboard.generalPasteboard
496
511
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -502,51 +517,54 @@ function run() {
502
517
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
503
518
  }
504
519
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
505
- }`;async function Nw(){if(Af())return;if(process.platform==="darwin"){let[e="",t=""]=(await mn("osascript",["-l","JavaScript","-e",SS])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Sw()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await mn("wl-paste",["--list-types"])).stdout:(await mn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function gu(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((f)=>f!==-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:IS(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 IS(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 co=(e)=>Buffer.from(e).toString("base64"),Tf=(e)=>Buffer.from(e,"base64");function bw(e,t){return t.find((n)=>e.includes(n))}class Lf{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=co(ww("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;${Ff.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=${co("ttheme")}:pw=${this.pw};${co(".")}\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?Tf(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Tf(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=bw(s,[...Hf,...wS]);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=${co(u)}:pw=${a};${co(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=Ff.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=bw(a,Ff);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(Tf(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"?Ui(a).find((c)=>lS(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(hu(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}import{readFileSync as NS}from"node:fs";var qe={pitch:25,cols:22,rows:9,height:13},Jr={cols:25,rows:16},PS=2147483648,RS=-1073741826,OS=1600,Pw=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],FS=56,TS=4,Rw=20,HS=50,Ow=[["space","unfolds a set of ×N"],["o","opens the post page in a browser"],["c","switches between cutouts and every post"],["a","opens the advanced filters"],["ctrl+v","tries on a picture from the clipboard — or drop one on the window"]],xS="\x1B[0m",Ye="\x1B[1m",J="\x1B[2m",ho="\x1B[32m",pn="\x1B[33m",AS={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",Z:"shift-tab","1;2C":"shift-right","1;2D":"shift-left"};function bu(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(AS[`${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===`
506
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Ww="\x1B]1337;ReportCellSize\x07\x1B[16t\x1B[14t\x1B[18t",Fw="\x1B]1337;ReportCellSize=";function Uf(e){let t=e.indexOf(Fw);if(t!==-1){let o=e.slice(t+Fw.length),a=[o.indexOf("\x07"),o.indexOf("\x1B\\")].filter((l)=>l!==-1),u=a.length>0?Math.min(...a):-1,c=u===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(o.slice(0,u));if(c){let l=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*l),w:Math.round(Number(c[2])*l)},rest:e.slice(0,t)+o.slice(u+(o[u]==="\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{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)};let i=Tw(e,4),s=Tw(e,8);if(!i||!s||s.a===0||s.b===0)return null;return{cell:{h:Math.floor(i.a/s.a),w:Math.floor(i.b/s.b)},rest:e.replace(i.text,"").replace(s.text,"")}}function Tw(e,t){let n=e.indexOf(`\x1B[${t};`),r=n===-1?null:new RegExp(`^\\[${t};(\\d+);(\\d+)t`).exec(e.slice(n+1));return r?{a:Number(r[1]),b:Number(r[2]),text:`\x1B${r[0]}`}:null}function qr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/qe.pitch)),rowsVis:Math.max(1,Math.floor(n/qe.height)),height:n}}function Uw(e,t=!0){if(t)return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`;let n;try{n=NS(e.path).toString("base64")}catch{return}let r=n.match(/.{1,4096}/g)??[""];return r.map((i,s)=>{let o=s<r.length-1?1:0;return s===0?`\x1B_Ga=t,f=100,i=${e.id},m=${o},q=2;${i}\x1B\\`:`\x1B_Gm=${o},q=2;${i}\x1B\\`}).join("")}function jw(e,t){let n=e.crop===void 0?"":`,x=0,y=${e.crop*t.h},w=${e.cols*t.w},h=${e.rows*t.h}`;return`\x1B[${e.row+1};${e.col+1}H\x1B_Ga=p,i=${e.id},p=${e.id}${n},c=${e.cols},r=${e.rows},C=1,z=${e.z},q=2\x1B\\`}function jf(e){return`\x1B_Ga=d,d=i,i=${e},p=${e},q=2\x1B\\`}function Kw(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function ji(e){return`\x1B[38;2;${ve(e).join(";")}m`}function pu(e){return`\x1B[48;2;${ve(e).join(";")}m`}var Cf=!1;function wu(e){return Cf=!0,e.beat}function Ki(e){return Pw[wu(e)%Pw.length]}function _e(e){return $e(e)}function Bw(e,t){if($e(e)<=t)return e;let n="";for(let r of e){if($e(n+r)>t)break;n+=r}return n}function Bi(e){return`\x1B[${30+e}m`}function Ji(e,t,n,r){return n?[[`${ss} `,r],[e,t,n]]:[[e,t]]}function _f(e){return e.reduce((t,[n])=>t+_e(n),0)}function LS(e,t){let n=[],r=t;for(let[i,s,o]of e){let a=_e(i);if(a<=r){n.push([i,s,o]),r-=a;continue}n.push([`${Bw(i,r)}…`,s,o]);break}return n}class mu{parts=[];cols;constructor(e){this.cols=e}put(e,t,n="",r){return this.parts.push({col:e,text:t,sgr:n,...r?{link:r}:{}}),e+_e(t)}run(e,t){let n=e;for(let[r,i,s]of t)n=this.put(n,r,i,s);return n}right(e,t){this.run(e-t.reduce((n,[r])=>n+_e(r),0),t)}center(e,t){this.run(Math.floor((e-t.reduce((n,[r])=>n+_e(r),0))/2),t)}render(){let e="";for(let{col:t,text:n,sgr:r,link:i}of this.parts){if(t>=this.cols||t<0)continue;let s=Bw(n,this.cols-t);e+=`\x1B[${t+1}G${r}${jo(s,i)}${r?xS:""}`}return e}}function CS(e){return e.replace(/_\([^)]*\)?$/,"")}function Jw(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<OS?pn:J]}function go(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[_f(s)]:[],...i.map(([d,h])=>_e(d)+1+_e(h))];return(r.badge?_e(r.badge)+4:0)+l.reduce((d,h)=>d+h,0)+3*Math.max(0,l.length-1)+(o?3+_e(o[0])+1+_e(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)s=LS(s,Math.max(0,_f(s)-(a()-t)-1));let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[s]:[],...i.map(([l,f])=>[[l,Ye],[` ${f}`,J]])].forEach((l,f)=>{u=e.run(u+(f?3:0),l)}),o)e.right(t,[[o[0],Ye],[` ${o[1]}`,J]])}function _S(e,t){if(e==="d")return J;if(e==="b")return Ye;if(e==="s")return pu(t.colors.selection);if(e==="c")return pu(t.colors.cursor);let n=/^([BK]?)(\d+)$/.exec(e);if(!n)return"";let r=Number(n[2]),i=(s)=>r<8?s+r:s+52+r;if(n[1]==="K")return`\x1B[30;${i(40)}m`;return`\x1B[${n[1]==="B"?"1;":""}${i(30)}m`}function GS(e,t,n,r,i){let s=Gt.indexOf(Pa(r.scene)),o=Gt.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Ye+i:J]]),a=o.reduce((u,[c])=>u+_e(c),0)<=n;e?.run(t,a?o:[[Pa(r.scene).name,Ye+i],[` ${s+1}/${Gt.length}`,J]])}function WS(e,t,n,r,i,s,o){let{ansi:a,cursor:u}=s.colors;GS(e[t-2],n,r,s,o);let c=r<Np?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let d=0;d<8;d++)l=(e[t]?.put(l,"▀".repeat(c),ji(a[d]??u)+pu(a[d+8]??u))??l)+1;let f=t+2;for(let d of Pa(s.scene).lines){let h=Pp(d,r);if(!h)continue;if(f>i)return;e[f]?.run(n,h.map(([g,b])=>[g,_S(b,s)])),f++}}function US(e,t,n){let r=[[]];for(let o of e){let a=r[r.length-1];if(a.length===0||_e([...a,o].join(" "))<=t)a.push(o);else if(r.length<n)r.push([o]);else break}let i=r.reduce((o,a)=>o+a.length,0),s=r[r.length-1];while(i<e.length&&s.length>0&&_e([...s,`+${e.length-i}`].join(" "))>t)s.pop(),i--;if(i<e.length)s.push(`+${e.length-i}`);return r.filter((o)=>o.length>0).map((o)=>o.join(" "))}function Hw(e){return e.replace(/^https?:\/\/(?:www\.)?/,"")}function jS(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Bi(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?Ji(Hw(s.page),"",s.page,a):[["—",J]]],["Source",s?.source?Ji(Hw(s.source),"",s.link,i):[["—",J]]],["Artist",[o.length>0?[o.join(" "),""]:["—",J]]]].forEach(([c,l],f)=>{e[t+f]?.put(n,c,J),e[t+f]?.run(n+12,l)})}function KS(e,t,n,r,i,s){let o=s.info,a=s.tiles[s.focus];if(!o||!a)return;let u=s.shown?.id===a.key?s.shown:void 0,c=n+12,l=Math.max(12,r-12),f=[`${a.width}×${a.height}${o.ext?` ${o.ext.toUpperCase()}`:""}`,...u?[Xa(u.bytes)]:[]].join(" · "),d=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),h=(p,m)=>p.length>0?US(p,l,m).map((k)=>[[k,""]]):[[["—",J]]],g=[["Characters",h(o.characters,2)],["Series",h(o.series,1)],["Tags",h(o.tags,3)],["Rating",[[[d,d==="—"?J:""]]]],["File",[[[f,""],...u?[[" ",""]]:[],...u?qw(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",J]]]]],b=t;for(let[p,m]of g){if(b+m.length-1>i)return;e[b]?.put(n,p,J);for(let k of m)e[b]?.run(c,k),b++}}var BS=["Size","Position","Opacity"],JS=[0,3,6];function qS(e,t){let{tune:n,untuned:r}=e;return t===0?n.size!==r.size:t===1?n.at!==r.at:n.opacity!==r.opacity}function VS(e){return e.toFixed(2)}function zS(e,t,n,r,i,s){let o=i.tuning;if(!o)return;let a=i.tiles[i.focus];e[t-3]?.run(n,[[i.palette,Ye+s],[" Background",J],...a?[[" · ",J],...Ji(`${a.site} ${a.id}`,J,a.page||void 0,Bi(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[f,d]of BS.entries()){let h=t+JS[f],g=o.field===f,b=g?Ye:J;if(g)e[h]?.put(n,"▶",s);e[h]?.put(n+2,d,b);let p;if(f===1){for(let m=1;m<=9;m++){let k=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,k?"■":"·",k?Ye+s:J)}p=kt[i.tune.at-1]??"center"}else{let m;if(f===0){let{size:k}=i.tune;m=k==="fill"?u-1:Math.floor((k-c)*(u-1)/(l-c+1)),p=k==="fill"?"fill":`${k}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),p=VS(i.tune.opacity);m=Math.max(0,Math.min(u-1,m)),e[h]?.run(n+12,[["━".repeat(m),s],["●",Ye],["─".repeat(u-1-m),J]])}if(e[h]?.right(r-2,[[p,b]]),qS(i,f))e[h]?.put(r-1,"↺",g?Ye+s:J)}}function YS(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 Gf(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function fo(e){return`${X[Math.floor(e/Qn)]?.name??"local"} ${e%Qn}`}function lo(e,t,n){let r=X[Math.floor(t/Qn)],i=fo(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],...Ji(i,n,r.pageUrl(t%Qn),Bi(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function QS(e,t,n){let r=[{name:"all",moved:!1},...X].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Gf(n,a):[` ${a} `,J];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+_e(o),0)<=t;e.run(0,i?r:[Gf(n)])}function ZS(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"}`,J);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":J]]),s=Pr.filter((u)=>!n.block.includes(u)),o=X.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(" ")}`,J),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,J]);e.right(t,u)}}function qw(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,ho]];if(e.cut==="off")return[["Opaque · x cuts out",pn]];if(e.cut==="failed")return[["Opaque · no cut-out",pn]];return[e.clear>0?[`${e.clear}% transparent`,ho]:["Opaque",pn]]}function xw(e){return e.site==="all"?"any site":e.site}function Wf(e,t){if(e.installing!==void 0)return lo(`${Ki(e)} Installing ${e.palette} ← ${fo(e.installing)}`,e.installing,pn);if(e.hint)return[[e.hint,ho]];if(e.error)return[[e.error,pn]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,pn]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return lo(`${Ki(e)} Fetching ${fo(n)} · ${Da(r,i)}`,n,pn)}if(e.cutting!==void 0)return lo(`${Ki(e)} Cutting out ${fo(e.cutting)}`,e.cutting,pn);if(e.preparing!==void 0)return lo(`${Ki(e)} Preparing ${fo(e.preparing)}`,e.preparing,pn);if(t)return[t];if(e.saved)return lo(e.saved.text,e.saved.key,ho);if(e.note)return[[e.note,J]];return}function Vw(e){if(e.ranking)return"Ranking previews by palette colors";if(e.stage==="check")return e.preset==="cutouts"?"Checking PNG headers":"Loading previews";return"Fetching posts"}function zw(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function XS(e,t,n,r,i){let{background:s,cursor:o,selection:a}=r.colors,{ranking:u}=r,c=u?Math.round(n*u.done/u.total):-1,l=Math.max(6,Math.round(n*0.22)),f=wu(r)%(Rw*2)/Rw,d=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(f<1?f:2-f)))),h=it(s,o,i),g=it(s,it(a,s,0.15),i),b=Array.from({length:n},(m,k)=>{let v=(c>=0?k<c:k>=d&&k<d+l)?h:g;return k===0||k===n-1?it(v,s,0.55):v}),p=0;for(let m=1;m<=n;m++)if(m===n||b[m]!==b[p])e?.put(t+p," ".repeat(m-p),pu(b[p])),p=m}function DS(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(wu(i)-i.loaderFrom)/TS),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[Vw(i),Ye+ji(it(s,o,a))],[zw(i," "),ji(it(s,it(o,s,0.45),a))]]);let c=Math.min(FS,r-8);if(XS(e[u+(n>=3?2:1)],Math.floor((r-c)/2),c,i,a),n<5)return;e[u+4]?.center(r,i.sites.flatMap(({name:l,arrived:f},d)=>[...d?[[" · ",ji(it(s,o,0.25*a))]]:[],[l,ji(it(s,f?it(o,s,0.2):o,f?a:0.32*a))]]))}function eI(e,t,n,r,i,s){if(i<=r)return;let o=Math.max(1,Math.round(r*r/i)),a=Math.max(0,Math.min(r-o,Math.round(n.scroll*r/i)));for(let u=0;u<r;u++){let c=u>=a&&u<a+o;e[2+u]?.put(t-1,c?"┃":"│",c?s:J)}}function tI(e,t,n){if(t)return[`${Ki(e)} ${Vw(e)}${zw(e," · ")}`,J];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Ki(e)} Loading thumbnails · ${i}/${r.length}`,J]:void 0}function nI(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=qr(n,r);ZS(e[0],n,i,s),QS(e[1],n,i);let c=e.map(($,N)=>N>=2&&N<2+u?$:void 0),l=Math.floor(i.scroll/qe.height),f=Math.floor((i.scroll+u-1)/qe.height),d=[];for(let $=l;$<=f;$++){let N=2+$*qe.height-i.scroll;for(let R=0;R<o;R++){let F=$*o+R,x=R*qe.pitch,C=i.tiles[F];if(!C)continue;d.push(C);let W=F===i.focus;if(W)YS(c,N,x,qe.height,qe.pitch-1,s);let A=N+1,T=Math.max(A,2),q=Math.min(A+qe.rows,2+u);if(C.thumb&&q>T)t.push({id:C.key,path:C.thumb,row:T,col:x+1,cols:qe.cols,rows:q-T,...q-T<qe.rows?{crop:T-A}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",ho]]:[],...C.page||i.site!=="all"?Ji(String(C.id),W?Ye:"",C.page||void 0,Bi(C.siteAnsi)):[["● ",Bi(C.siteAnsi)],[String(C.id),W?Ye:""]],[" ",""],Jw(C)],be=qe.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(x+1,_f(Ee)>be?Ee.map(([Ae,he,ce])=>[Ae.replace(/^(\S) $/,"$1"),he,ce]):Ee),C.mates.length>0)c[N+10]?.put(x+qe.cols,"≈",s);c[N+11]?.put(x+1,C.artist?CS(C.artist).slice(0,qe.cols-8):"—",J);let Y=[];if(C.score>0)Y.push([`★${C.score}`,J]);if(C.variants>1)Y.push([` ×${C.variants}`,s]);if(Y.length>0)c[N+11]?.right(x+qe.cols+1,Y)}}let h=Math.ceil(i.tiles.length/o)*qe.height;eI(e,n,i,u,h,s);let g=Math.max(2,2+h-i.scroll),b=2+u-g,p=i.searching&&b>=2;if(p)DS(c,g,b,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[$,N]=Ow[Math.floor(wu(i)/HS)%Ow.length];e[r-2]?.run(0,[["Tip ",J],[$,Ye],[` ${N}`,J]])}let k=i.top*o,v=i.tiles.length-(i.top+a)*o,M=[...k>0?[`↑ ${k} above`]:[],...v>0?[`↓ ${v} more`]:[]];if(M.length>0)e[r-2]?.put(0,M.join(" "),J);if(!i.searching&&i.tiles.length===0&&!i.error&&i.tag)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${xw(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${xw(i)} — tab tries ${i.nextSite}`,J);let w=tI(i,p,d),I=Wf(i,w);return go(e[r-1],n,s,{badge:"IMAGE SEARCH",lead:I,keys:m&&I?.[0]===w?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),p}function rI(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=[Gf(i,o.site,o.siteAnsi),[" ",""],...Ji(String(o.id),Ye,o.page||void 0,Bi(o.siteAnsi)),[" ",""],Jw(o)];if(o.score>0)u.push([` · ★${o.score}`,J]);if(a)u.push([` · ${Xa(a.bytes)}`,J]);if(a)u.push([" ",""],...qw(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),J]]);if(jS(e,1,2,i,s),i.tuning)zS(e,8,2,2+Math.min(n-4,60),i,s);else if(i.details)KS(e,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else WS(e,7,2,n-4,r-2,i,s);if(i.shown)t.push({id:PS+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:RS});if(i.tuning){go(e[r-1],n,s,{badge:"IMAGE EDIT",lead:Wf(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["enter","keep"]],right:["esc","undo"]});return}let c=Wf(i);go(e[r-1],n,s,{badge:"IMAGE PREVIEW",lead:c,keys:i.installing===void 0?[["←→","browse"],["enter","install"],["t","tune"],["i","details"],...i.details?[]:[["⇧←→","example"]],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var iI=[["Field","↑↓ size, position, opacity"],["Step","←→ · ⇧←→ ×10"],["Place","1-9 the nine positions"],["Reset","= this field back to its default · + every field"],["Keep","enter back to try, installed with the picture"],["Undo","esc"],["Close","? esc"]],sI={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab shift+tab all, ${X.map((e)=>e.name).join(", ")}`],["Posts","c cutouts or every post"],["Search","/ a tag, a post URL or an id"],["Your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["Unfold","space a set of ×N"],["Open","o the post page in a browser"],["Settings","s rating, block, posts, solo, order, sets, remove bg"],["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"],["Tune","t size, position and opacity, installed with the picture"],["Details","i characters, series, tags, rating and file, under Post, Source and Artist"],["Example",`⇧←→ ${Gt.map((e)=>e.name.toLowerCase()).join(", ")}`],["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"]]},Kf=6,oI=24;function mo(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function aI(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function Aw(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>aI(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function Yw(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 Br(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&_e(r)+1+_e(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function uI(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 cI(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?"":J}];let o=s?[]:e.value.split(" "),a=(s?e.choices:uI(e)).map((u,c)=>{let l=o.includes(u),f=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${f}7;${30+r}m`:"":f?`\x1B[4m${J}`:J}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function Lw(e){if(e.entry==="text")return[{text:" ".repeat(oI),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Kf)}█ `,sgr:""}]:t}function lI(e){return e.reduce((t,n)=>t+_e(n.text)+1,0)-1}function Cw(e,t){let n=[[]],r=0;for(let i of e){let s=_e(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+_e(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=_e(s.text)+1}return n}function _w(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 Gw(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 fI(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 dI(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((A)=>_e(A.label))),c=Math.max(...r.settings.map((A)=>_e(_w(A)))),l=u+Math.max(...r.settings.map((A)=>lI(Lw(A))))+c+5,f=Math.min(t-2,Math.max(48,l)),d=f-u-c-5,h=f-7,g=[!1,!0].map((A)=>({advanced:A,rows:mo({settings:r.settings,advanced:A}).slice(0,-1)})),b=r.settings.map((A)=>Cw(Lw(A),d).length),p=Math.max(...g.map((A)=>A.rows.reduce((T,q)=>T+b[q],0))),m=Math.max(...g.map((A)=>Br(Aw({settings:r.settings,advanced:A.advanced}),h).length),...r.settings.map((A)=>Br(A.about,h).length)),k=`${r.tag}: ${X.map((A)=>`${A.name} 0,000,000`).join(" · ")}`,v=r.tag?Math.max(Br(k,h).length,Br(Gw(r),h).length):0,M=p+m+v+8,w=Math.floor((t-f)/2),I=Math.max(1,Math.floor((n-1-M)/2)),$=`\x1B[7;${30+r.siteAnsi}m`;e[I]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let A=I+1;A<I+M-1;A++)e[A]?.put(w,`│${" ".repeat(f-2)}│`);let N=I+2;for(let A of mo(r).slice(0,-1)){let T=r.settings[A],q=A===s;if(q)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,T.label,q?Ye:""),T.value!==T.default)e[N]?.right(w+f-3,[[_w(T),J]]);Cw(cI(T,q,r.typing,r.siteAnsi),d).forEach((Ee,be)=>{let Y=w+u;for(let Ae of Ee)Y=e[N+be].put(Y,Ae.text,Ae.sgr)+1}),N+=b[A]}let R=g.find((A)=>A.advanced!==r.advanced)?.rows??[],F=e[I+3+p];if(s===o)F.put(w+2,"▶",i);let x=F.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?$:Ye);if(R.some((A)=>r.settings[A]?.value!==r.settings[A]?.default))F.put(x+1,"•",J);e[I+5+p]?.put(w+2,"─".repeat(f-4),J),Br(r.settings[s]?.about??Aw(r),h).forEach((A,T)=>{e[I+6+p+T]?.put(w+4,A)}),Br(Gw(r),h).forEach((A,T)=>{e[I+6+p+m+T]?.put(w+4,A,J)}),e[I+M-1]?.put(w,`╰${"─".repeat(f-2)}╯`);let{keys:C,right:W}=fI(r,r.settings[s]);go(e[n-1],t,i,{keys:C,right:W})}function hI(e,t,n,r,i){let s=r.tuning?iI:sI[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,d])=>_e(d)+16))),a=s.map(([d,h])=>({label:d,parts:Br(h,o-16)})),u=a.reduce((d,{parts:h})=>d+h.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Help ${"─".repeat(o-9)}╮`);for(let d=l+1;d<l+u-1;d++)e[d]?.put(c,`│${" ".repeat(o-2)}│`);let f=l+2;for(let{label:d,parts:h}of a){e[f]?.put(c+3,d,Ye);for(let g of h)e[f]?.put(c+13,g),f++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),go(e[n-1],t,i,{badge:"HELP",right:["? esc","close"]})}function gI(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)=>_e(a.value))),o=Math.max(7,...i.map(_e));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?Ye+n:""]]),l?.right(2+s+2+o,[[i[u],J]])})}function Bf(e,t,n){let r=Array.from({length:n},()=>new mu(t)),i=[],s=ji(e.colors.cursor);if(Cf=!1,t<Jr.cols||n<Jr.rows)return r[0]?.put(0,"ttheme find",Ye+s),r[1]?.put(0,`Needs ${Jr.cols}×${Jr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",J),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")rI(r,i,t,n,e,s);else o=nI(r,i,t,n,e,s);if(e.mode==="grid"&&e.editing!==void 0&&e.suggest?.length){for(let a=1;a<n-1;a++)r[a]=new mu(t);return gI(r,e,s),{lines:r.map((a)=>a.render()),images:[],loader:!1,tick:!1}}if(e.help||e.panel!==void 0){let a=e.mode==="try"?i:[];for(let u=0;u<n;u++)r[u]=new mu(t);if(e.help)hI(r,t,n,e,s);else dI(r,t,n,e,s);return{lines:r.map((u)=>u.render()),images:a,loader:!1,tick:!1}}return{lines:r.map((a)=>a.render()),images:i,loader:o,tick:Cf}}var Jf=5,mI=6,Qw=0.05,pI=[1,2,3,4,5,6,9,10,11,12,13,14],Zw=(e,t)=>(t-e+360)%360<=180?1:-1;function po(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 f=Math.min(1,Math.max(0,l));return Math.round(255*(f<=0.0031308?12.92*f:1.055*f**0.4166666666666667-0.055))})}function Wt(e,t,n){let r=0,i=t;if(po(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(po(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(po(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function bI(e,t){let{l:n,c:r}=Je(e);return Wt(n,r,(t+360)%360)}function wI(e,t,n){let{l:r,c:i,h:s}=Je(e),o=ze(t)<0.18,a=(l)=>Wt(o?r+(1-r)*l:r*(1-l),i,s);if(Be(a(1),t)<n+Qw)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let f=(u+c)/2;if(Be(a(f),t)>=n+Qw)c=f;else u=f}return a(c)}function $I(e,t){let{l:n,c:r,h:i}=Je(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(ze(Wt(u,r,i))<=t-0.005)s=u;else o=u}return Wt(s,r,i)}function kI(e,t,n){let r=kn[t],[i,s]=[Je(e[t]),Je(e[t+8])],o=(l,f)=>n.has(l)?[f]:Array.from({length:2*r.width+1},(d,h)=>(r.center-r.width+h+360)%360),a=(l,f,d)=>Cn.every((h)=>{let g=(l>8?8:0)+h;if(g===l)return!0;let b=Je(e[g]);return b.c<as||Dt(b.h,f)>=ri+1||Math.abs(b.l-d)>=ii}),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 f of o(t+8,s.h)){if(Dt(l,f)>jt-Jf||!n.has(t+8)&&!a(t+8,f,s.l))continue;let d=Dt(l,i.h)+Dt(f,s.h);if(d<c)c=d,u=[l,f]}}return u}class Xw{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,bI(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of ni(this.theme)){let i=kn[_n(n)];this.rehue(n,"ansi-role",i.center+Zw(i.center,r)*(i.width-Jf))}for(let{normal:n,gap:r}of Mr(this.theme)){if(r<=jt)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Je(this.theme.ansi[i]).h,a=Je(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+Zw(o,a)*(jt-Jf))}let t=si(this.theme);for(let[n,r]of Sr(this.theme)){let i=_n(t.has(r)?n:r),s=kI(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(Be(this.get(a),o)<s)this.set(a,r,wI(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",pI.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&ze(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",$I(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 $u(e){let t=new Xw(e);for(let n=0;n<mI;n++)if(t.readability(),t.roles(),Ir(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Ir(t.theme)}}var bo=[{key:"background",label:"Background",min:0,max:0.5,step:0.01,digits:2},{key:"foreground",label:"Foreground",min:0.5,max:1,step:0.01,digits:2},{key:"hue",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0},{key:"tint",label:"Tint",min:0,max:0.1,step:0.005,digits:3},{key:"lightness",label:"Accent lightness",min:0.4,max:0.95,step:0.01,digits:2},{key:"chroma",label:"Accent chroma",min:0,max:0.3,step:0.005,digits:3},{key:"brights",label:"Brights",min:-0.2,max:0.2,step:0.01,digits:2}],ku={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},Dw=(e,t,n)=>Math.min(n,Math.max(t,e));function e0(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:Dw(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function Vr(e){let t=(r,i,s)=>Wt(Dw(r,0,1),i,s),n=Array.from({length:16},()=>"#000000");n[0]=t(e.background+0.06,e.tint,e.hue),n[8]=t(e.background+0.25,e.tint,e.hue),n[7]=t(e.foreground-0.06,e.tint/2,e.hue),n[15]=t(e.foreground+0.06,e.tint/2,e.hue);for(let r of Cn){let i=kn[r].center;n[r]=t(e.lightness,e.chroma,i),n[r+8]=t(e.lightness+e.brights,e.chroma,i)}return{background:t(e.background,e.tint,e.hue),foreground:t(e.foreground,e.tint/2,e.hue),cursor:t(e.lightness+e.brights,Math.max(e.chroma,0.08),e.hue),selection:t(e.background+0.1,e.tint*2,e.hue),ansi:n}}var ko=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],Pt=["Background","Foreground","Cursor","Selection"],Su=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],wo=Pt.length+Su.length,zr=[{key:"l",label:"Lightness",min:0,max:1,step:0.01,digits:2},{key:"c",label:"Chroma",min:0,max:0.37,step:0.005,digits:3},{key:"h",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0}],t0=5;function yI(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Ui(t).length>0}function yu(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function Tn(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function Eu(e){if(e<Pt.length)return{name:Pt[e],about:ko[e]};let t=e-Pt.length,n=Su[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var vu=(e,t,n)=>Math.min(n,Math.max(t,e));function EI(e){return vu(Math.round(e),0,255).toString(16).padStart(2,"0")}function n0(e){let t=e.trim().toLowerCase(),n=/^#?([0-9a-f]{6}|[0-9a-f]{3})$/.exec(t);if(n){let s=n[1];return`#${s.length===3?[...s].map((o)=>o+o).join(""):s}`}let r=/^rgb\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)\s*\)$/.exec(t);if(r)return`#${r.slice(1,4).map((s)=>EI(Number(s))).join("")}`;let i=/^oklch\(\s*([\d.]+)(%?)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:deg|°)?\s*\)$/.exec(t);if(i){let s=Number(i[1])/(i[2]?100:1);return Wt(vu(s,0,1),Number(i[3]),Number(i[4])%360)}return}function Mu(e){let t=bt.find((n)=>n.rule===e);return t?.min??t?.max??0}function $o(e,t,n){let r=Tn(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function vI(e,t,n){let r=$o(e,t,n),i=(f)=>!n.includes(f),{background:s,foreground:o,selection:a,ansi:u}=Tn(e),c=new Set,l=(f,d,h,g)=>{if(i(g)&&Be(d,h)<Mu(g))c.add(f)};l(1,o,s,"foreground"),l(3,o,a,"selection");for(let f of[1,2,3,4,5,6,9,10,11,12,13,14])l(4+f,u[f],s,"accents");for(let f of[7,15])l(4+f,u[f],s,"light-ansi");if(l(12,u[8],s,"ansi8-visible"),i("ansi0-dark")&&ze(u[0])>Mu("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:f}of ni(r))c.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of Mr(r))if(d>jt)c.add(4+f+8)}if(i("distinct"))for(let[f,d]of Sr(r))c.add(4+f).add(4+d);return c}function Fn(e,t,n,r,i){let s=Be(e,t),o=Mu(n);if(i.includes(n))return{ok:void 0,text:`${r} ${s.toFixed(2)}:1 · waived`};return{ok:s>=o,text:`${r} ${s.toFixed(2)}:1 · ≥ ${o}`}}function r0(e,t,n,r){let i=Tn(e),s=$o(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce((k,v)=>Be(i.ansi[k],i.background)<=Be(i.ansi[v],i.background)?k:v);return[Fn(i.foreground,i.background,"foreground","Foreground on it",n),Fn(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),Fn(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[Fn(i.foreground,i.background,"foreground","On background",n),Fn(i.foreground,i.selection,"selection","On the selection",n)];if(r===2)return[{ok:void 0,text:`On background ${Be(i.cursor,i.background).toFixed(2)}:1`}];if(r===3)return[Fn(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-Pt.length,a=i.ansi[o];if(o===0){let p=ze(a),m=Mu("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${p.toFixed(3)} · waived`}:{ok:p<=m,text:`Luminance ${p.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[Fn(a,i.background,"light-ansi","On background",n)];if(o===8)return[Fn(a,i.background,"ansi8-visible","On background",n)];let u=[Fn(a,i.background,"accents","On background",n)],c=Je(a),l=_n(o),f=kn[l],d=`${f.name} ${f.center}±${f.width}°`;if(c.c<as)u.push({ok:void 0,text:"Too grey to have a hue"});else if(si(s).has(o))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · a signature, free of ${d}`});else if(n.includes("ansi-role"))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · ${d} waived`});else{let p=Dt(c.h,f.center)-f.width;u.push(p>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${p.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${d}`})}let h=o<8?o+8:o-8,g=Mr(s).find((p)=>p.normal===l);if(g)u.push(n.includes("bright-follows")?{ok:void 0,text:`${g.gap.toFixed(0)}° from ANSI ${h} · waived`}:{ok:g.gap<=jt,text:`${g.gap.toFixed(0)}° from ANSI ${h} · ≤ ${jt}°`});let b=Sr(s).flatMap(([p,m])=>p===o?[m]:m===o?[p]:[]);if(b.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${b.join(", ")} · within ${ri}° and ${ii} lightness`});return u}function i0(e,t,n){let r=Gn($o(e,t,n));return bt.map((i,s)=>{let o=r[s],a=n.includes(i.rule);return{ok:a||Number.isNaN(o)?void 0:(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),label:i.label,value:Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2),bound:a?"waived":i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:""}})}var MI=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class qf{mode;seeds=ku;field=0;list;lch;start;signature;row=0;col=0;channel=0;typing;overlay;quitting=!1;compare=!1;notice;filter="";pick=0;result;wants;pictures;startPictures;options;fresh;startSignature;seeded=!1;seedsBack=!1;tuneFrom;clip;history=[];future=[];lastEdit;constructor(e){this.options=e,this.fresh=e.colors===void 0,this.mode=this.fresh?"seeds":"list",this.list=yu(e.colors??Vr(this.seeds)),this.lch=this.list.map(Je),this.start=[...this.list],this.signature=[...e.signature],this.startSignature=[...e.signature],this.pictures=e.pictures??0,this.startPictures=this.pictures}get added(){return Math.max(0,this.pictures-this.startPictures)}found(e){this.pictures=e.count,this.notice=e.note}get waive(){return this.options.waive??[]}get tuned(){return this.tuneFrom?.hex}colors(){return Tn(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<Pt.length?this.row:this.row+(this.col===1?8:0)}dirty(){return this.seeded||this.pictures!==this.startPictures||this.list.some((e,t)=>e!==this.start[t])||this.signature.join()!==this.startSignature.join()}misses(){return vI(this.list,this.signature,this.waive)}failing(){return Ir($o(this.list,this.signature,this.waive))}choices(){let e=this.filter.toLowerCase();return(this.options.palettes??[]).filter((t)=>t.name.toLowerCase().includes(e))}paste(e){if(this.notice=void 0,this.overlay==="open"){this.filter+=e.replace(/\s+/g,"").toLowerCase(),this.pick=0;return}if(this.overlay)return;if(e.trim()===""){this.findPictures({clipboard:!0});return}if(yI(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=n0(e);if(!t){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=t,this.lch[this.slot()]=Je(t);else this.set(this.slot(),t,"paste")}press(e){if(this.notice=void 0,e==="ctrl-c"){this.result="cancelled";return}if(this.quitting){if(this.quitting=!1,e==="y"||e==="Y")this.result="cancelled";return}if(this.typing!==void 0){this.type(e);return}if(this.overlay==="keys"){this.overlay=void 0;return}if(this.overlay==="open"){this.openKey(e);return}if(e==="?"){this.overlay="keys";return}if(e==="ctrl-v"||e==="alt-v"){this.findPictures({clipboard:!0});return}if(e==="p"&&this.mode!=="tune"){this.findPictures();return}if(e===" "&&this.mode!=="seeds"){this.compare=!this.compare;return}if(this.compare&&e==="esc"){this.compare=!1;return}if(this.mode==="seeds")this.seedKey(e);else if(this.mode==="tune")this.tuneKey(e);else this.listKey(e)}seedKey(e){let t=bo.length;if(e==="up"||e==="down")this.field=(this.field+(e==="up"?t-1:1))%t;else if(e==="home"||e==="end")this.field=e==="home"?0:t-1;else if(e==="left"||e==="right"||e==="shift-left"||e==="shift-right"){let n=bo[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:t0:1);this.seeds=e0(this.seeds,n,r),this.list=yu(Vr(this.seeds)),this.lch=this.list.map(Je)}else if(e==="enter")this.leaveSeeds();else if(e==="o")this.openPalettes();else if(e==="esc")if(this.seedsBack){let n=this.history.pop();if(n)this.restore(n);this.mode="list",this.seedsBack=!1}else this.result="cancelled"}leaveSeeds(){if(this.fresh&&!this.seeded)this.start=[...this.list];this.seeded=!0,this.seedsBack=!1,this.mode="list"}findPictures(e){if(!this.options.find){this.notice="Pictures need Ghostty, iTerm2 or kitty, outside tmux";return}this.wants=e?{start:e}:{}}openPalettes(){if((this.options.palettes??[]).length>0)this.overlay="open",this.pick=0;else this.notice="No other palettes to take colors from"}listKey(e){if(e==="up"||e==="down")this.row=(this.row+(e==="up"?wo-1:1))%wo,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:wo-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:Pt.length;else if(e==="left"||e==="right")this.col=e==="left"?0:1,this.lastEdit=void 0;else if(e==="tab")this.tune();else if(e==="#")this.typing="";else if(e==="c")this.clip=this.list[this.slot()],this.notice=`Copied ${this.clip}`;else if(e==="v")if(this.clip)this.set(this.slot(),this.clip,"paste");else this.notice="Nothing copied yet — c copies a slot";else if(e==="r")this.set(this.slot(),this.start[this.slot()],"reset");else if(e==="=")this.follow();else if(e==="*")this.mark();else if(e==="f")this.fix();else if(e==="s")this.remember("seeds"),this.mode="seeds",this.seedsBack=!0;else if(e==="o")this.openPalettes();else if(e==="u")this.undo();else if(e==="\x12")this.redo();else if(e==="enter"||e==="\x13")this.save();else if(e==="esc")if(this.dirty())this.quitting=!0;else this.result="cancelled"}tune(){let e=this.slot();this.remember("tune"),this.tuneFrom={hex:this.list[e],lch:this.lch[e]},this.mode="tune"}tuneKey(e){let t=zr.length;if(e==="up"||e==="down"||e==="tab"||e==="shift-tab")this.channel=(this.channel+(e==="up"||e==="shift-tab"?t-1:1))%t;else if(e==="left"||e==="right"||e==="shift-left"||e==="shift-right"){let n=zr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:t0:1))}else if(/^[0-9]$/.test(e)){let n=zr[this.channel];this.put(n.min+(n.max-n.min)*Number(e)/10)}else if(e==="#")this.typing="";else if(e==="enter"){if(this.tuneFrom&&this.list[this.slot()]===this.tuneFrom.hex)this.history.pop();this.tuneFrom=void 0,this.mode="list"}else if(e==="esc"){let n=this.slot();if(this.tuneFrom)this.list[n]=this.tuneFrom.hex,this.lch[n]=this.tuneFrom.lch,this.history.pop();this.tuneFrom=void 0,this.mode="list"}}step(e){let t=zr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=zr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:vu(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=Wt(i.l,i.c,i.h)}type(e){let t=this.typing??"";if(e==="esc")this.typing=void 0;else if(e==="enter"){let n=n0(t);if(!n){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=n,this.lch[this.slot()]=Je(n);else this.set(this.slot(),n,"hex")}else if(e==="backspace")this.typing=t.slice(0,-1);else if(e==="\x15")this.typing="";else if(e.length===1&&/^[0-9a-z#(),.% ]$/i.test(e)&&t.length<28)this.typing=t+e.toLowerCase()}openKey(e){let t=this.choices();if(e==="esc")this.overlay=void 0,this.filter="";else if(e==="up"||e==="down"){let n=Math.max(1,t.length);this.pick=(this.pick+(e==="up"?n-1:1))%n}else if(e==="home"||e==="end")this.pick=e==="home"?0:Math.max(0,t.length-1);else if(e==="backspace")this.filter=this.filter.slice(0,-1),this.pick=0;else if(e==="\x15")this.filter="",this.pick=0;else if(e==="enter"){let n=t[this.pick];if(!n)return;if(this.remember("open"),this.list=yu(n.colors),this.lch=this.list.map(Je),this.overlay=void 0,this.filter="",this.notice=`Took the colors of ${n.name}`,this.mode==="seeds")this.leaveSeeds()}else if(e.length===1&&/^[a-z0-9@/-]$/i.test(e))this.filter+=e.toLowerCase(),this.pick=0}remember(e){if(e!==this.lastEdit||MI.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Ht(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Je(t)}follow(){if(this.row<Pt.length){this.notice="= works on an ANSI row — the bright takes its normal";return}let e=this.row,t=this.row+8,n=this.lch[e],r={l:vu(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=Wt(r.l,r.c,r.h),this.col=1,this.notice=`${Eu(t).name} follows ${Eu(e).name.toLowerCase()}`}mark(){let e=ko[this.slot()];this.remember("sig"),this.signature=this.signature.includes(e)?this.signature.filter((t)=>t!==e):[...this.signature,e].slice(-3),this.notice=this.signature.length===3?`Signature: ${this.signature.join(", ")}`:`The signature needs three slots — ${this.signature.length} marked`}fix(){let e=$o(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=$u({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=Ir(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=yu({...this.colors(),foreground:t.foreground,selection:t.selectionBackground,ansi:t.ansi});this.lch=i.map((s,o)=>s===this.list[o]?this.lch[o]:Je(s)),this.list=i,this.notice=`Moved ${n.length} ${n.length===1?"color":"colors"}${r.length===0?" — passes the gate":" closer to the gate"}`}save(){let e=this.options.check(this.edited());if(e){this.notice=e;return}this.result="saved"}undo(){let e=this.history.pop();if(!e){this.notice="Nothing to undo";return}this.future.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(e)}redo(){let e=this.future.pop();if(!e){this.notice="Nothing to redo";return}this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(e)}restore(e){this.list=[...e.list],this.lch=[...e.lch],this.signature=[...e.signature],this.lastEdit=void 0}}var zf=80,Yf=24,Iu=48,Vf=11;function SI(e){return{color:e,dim:(t)=>e?`\x1B[2m${t}\x1B[22m`:t,bold:(t)=>e?`\x1B[1m${t}\x1B[22m`:t,fg:(t)=>e?Xt(t):"",bg:(t)=>e?`\x1B[48;2;${ve(t).join(";")}m`:""}}function II(e){return ze(e)>0.35?"#000000":"#ffffff"}function o0(e,t,n,r){let i=Math.max(0,Math.min(t.length-1,n));if(!e.color)return t.map((s,o)=>o===i?"●":r?"━":"─").join("");return t.map((s,o)=>{let a=s??"#000000";if(o===i)return`${e.bg(a)}${e.fg(II(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function NI(e,t,n){return Array.from({length:n},(r,i)=>{let s=t.min+(t.max-t.min)*i/(n-1),o={...e,[t.key]:s};return po(o.l,o.c,o.h)?Wt(o.l,o.c,o.h):void 0})}function a0(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var s0={background:(e)=>e.background,foreground:(e)=>e.foreground,hue:(e)=>e.cursor,tint:(e)=>e.background,lightness:(e)=>e.ansi[4],chroma:(e)=>e.ansi[1],brights:(e)=>e.ansi[12]};function u0(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function c0(e,t,n){let r=i0(t.list,t.signature,t.waive).sort((a,u)=>Number(a.ok!==!1)-Number(u.ok!==!1)),i=r.filter((a)=>a.ok===!1).length,s=` ${e.dim("Gate")} ${i===0?e.dim("passes"):e.bold(`${i} ${i===1?"miss":"misses"}`)}`,o=Iu-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${u0(e,a.ok)} ${wn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function PI(e,t,n){let r=t.misses(),i=Tn(t.list),s=t.slot(),o=(l)=>e.color?`${e.bg(i.selection)}${e.fg(i.foreground)}${l}\x1B[39;49m`:`[${l}]`,a=(l)=>{let f=t.list[l],d=l===s,h=t.signature.includes(ko[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Be(i.foreground,i.selection):Be(f,i.background),b=g===void 0?"":g.toFixed(1),p=r.has(l)?"✗":" ",k=`${e.color?`${e.fg(f)}${h}${d?e.fg(i.foreground):"\x1B[39m"} `:`${h} `}${f} ${b.padStart(4)}${p}`;return d?o(` ${k} `):` ${k} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<Pt.length;l++){let f=l===t.row,d=Pt[l].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}`)}c.push("",` ${e.dim(`${"ANSI".padEnd(10)} Normal${" ".repeat(11)}Bright`)}`);for(let l=Pt.length;l<wo;l++){let f=l===t.row,d=Su[l-Pt.length].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...c0(e,t,n-c.length)]}function RI(e,t,n){let r=Tn(t.list),i=[` ${e.dim("Seeds")}`];bo.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:Vf},(b,p)=>{let m=s.min+(s.max-s.min)*p/(Vf-1);return s0[s.key](Vr({...t.seeds,[s.key]:m}))}),l=o0(e,c,a0(u,s.min,s.max,Vf),a),f=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),d=s0[s.key](r),h=a?e.color?`${e.fg(r.cursor)}▌\x1B[39m `:"▌ ":" ",g=s.label.padEnd(17);i.push(`${h}${a?e.bold(g):g}${l} ${f} ${e.color?`${e.fg(d)}■\x1B[39m `:""}${e.dim(d)}`)}),i.push("");for(let s of Qe("Seven seeds grow all twenty colors, each accent on the hue its ANSI role reads as — whatever the seeds, they pass the gate. enter moves on to tune each slot.",Iu-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...c0(e,t,n-i.length)]}function l0(e,t,n){let r=(f)=>e.fg(t.ansi[f]),i=e.fg(t.foreground),s=`${e.bg(t.background)}${i}`,o=(f)=>e.color?`\x1B[1m${f}\x1B[22m`:f,a=`${r(2)}❯${i} `,u=Math.max(2,Math.min(4,Math.floor((n-9)/8)));return[Array.from({length:8},(f,d)=>`${e.fg(t.ansi[d])}${e.bg(t.ansi[d+8])}${(e.color?"▀":"#").repeat(u)}${s} `).join(""),"",`${o(`${r(4)}~/code/demo`)}${i} on ${r(5)}main${r(2)} +2${r(3)} ~1${i}`,`${a}git status -sb`,`## ${r(2)}main${i}...${r(1)}origin/main${r(3)} [ahead 1]${i}`,`${r(1)} M${i} src/main.rs ${r(1)}??${i} notes.md`,`${a}git diff`,`${r(6)}@@ -12,2 +12,2 @@${i}`,`${r(1)}- let size = 12;${i}`,`${r(2)}+ let size = 14;${i}`,`${a}cargo test`,`${r(2)} ✓${i} parses config`,`${r(1)} ✗${i} renders frame ${r(8)}expected 3, received 2${i}`,`${r(11)} ⚠ 1 warning${i} ${r(12)}ℹ 2 notes${i} ${r(13)}λ${i} ${r(14)}~${i} ${r(9)}✗${i} ${r(10)}✓${i}`,`${a}ls`,`${o(`${r(4)}docs`)} ${o(`${r(4)}src`)} ${r(2)}run.sh${i} ${r(6)}link${i} Cargo.toml`,`${a}echo ${e.bg(t.selection)}selected text${s} ${e.bg(t.cursor)} ${s}`,`${r(7)}ansi 7 text${i} ${r(15)}ansi 15 text${i} ${r(8)}# ansi 8 comment${i}`].map((f)=>`${s} ${rt(f,n-2)} ${e.color?"\x1B[0m":""}`)}function OI(e,t,n,r){let i=t.slot(),s=t.list[i],o=t.lch[i],a=Je(s),u=t.start[i],{name:c,about:l}=Eu(i),f=t.signature.includes(ko[i]),d=[wn(`${e.bold(c)} ${e.dim(l)}`,f?e.dim("◆ signature"):"",n),""],h=e.color?`${e.fg(s)}${"█".repeat(8)}\x1B[39m `:"",g=t.typing!==void 0?`${e.bold(`${t.typing}▏`)}`:void 0,[b,p,m]=ve(s),k=g??`${e.bold(s)}${u!==s?e.dim(` was ${e.color?`${e.fg(u)}■\x1B[39m `:""}${u}`):""}`;d.push(`${h}${k}`),d.push(`${h}${e.dim(`rgb ${b} ${p} ${m}`)}`),d.push(`${h}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let v=Math.max(8,Math.min(64,n-12));zr.forEach((I,$)=>{let N=t.mode==="tune"&&$===t.channel,R=o[I.key],F=`${R.toFixed(I.digits)}${I.wraps?"°":""}`.padStart(6),x=o0(e,NI(o,I,v),a0(R,I.min,I.max,v),N),C=I.key.toUpperCase();d.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${x} ${N?e.bold(F):e.dim(F)}`)}),d.push("");let M=r0(t.list,t.signature,t.waive,i);if(a.c<o.c-0.005)M.push({ok:void 0,text:`Chroma held at the sRGB edge — ${a.c.toFixed(3)} of ${o.c.toFixed(3)}`});for(let I of M)Qe(I.text,n-2).forEach(($,N)=>{d.push(`${N===0?u0(e,I.ok):" "} ${I.ok===!1?$:e.dim($)}`)});let w=r-d.length-1;if(w>=3)d.push("",...l0(e,Tn(t.shown()),n).slice(0,w));return d}function FI(e,t,n,r){return[wn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...l0(e,Tn(t.list),n).slice(0,r-2)]}var TI=[["Slots","↑↓ slot · ←→ normal or bright · home end · pgup the base colors · pgdn the ANSI ones"],["Tune","tab · ↑↓ lightness, chroma or hue · ←→ step · ⇧←→ ×5, hue ×10 · 0-9 jump · enter keeps · esc undoes"],["Type","# then #rrggbb, rgb(r g b) or oklch(l c h) — a paste works too"],["Slot","c copies · v pastes · r puts it back · = the bright follows its normal · * marks it a signature color"],["Palette","f moves the colors the gate misses · o takes another palette’s colors · s goes back to the seeds"],["History","u undo · ctrl+r redo"],["Pictures","p finds one on the boorus, tried on in these colors · drop a picture on the window, or paste one, its path or its link · ctrl+v takes the clipboard’s"],["Compare","space shows the colors you started from, on the terminal too"],["Save","enter saves · esc cancels, asking first when something changed"]];function HI(e,t,n){let r=[` ${e.bold("Help")}`,""];for(let[i,s]of TI.filter(([o])=>o!=="Pictures"||t.options.find))Qe(s,n-16).forEach((o,a)=>{r.push(` ${e.bold((a===0?i:"").padEnd(11))} ${o}`)});return r}function xI(e,t,n,r){let i=t.choices(),s=t.options.palettes?.length??0,o=t.filter?`${e.bold(t.filter)}▏`:e.dim("type to filter"),a=[wn(` ${e.bold("Take colors from")} ${o}`,e.dim(`${i.length}/${s}`),n),""],u=r-2,c=Math.max(0,Math.min(t.pick-Math.floor(u/2),i.length-u)),l=Math.min(40,Math.max(12,...i.map((f)=>$e(f.name))));if(i.slice(c,c+u).forEach((f,d)=>{let h=c+d===t.pick,g=f.colors,b=e.color?`${e.bg(g.background)} ${[...g.ansi].map((k)=>`${e.fg(k)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",p=h?"▌ ":" ",m=f.name.padEnd(l);a.push(`${p}${h?e.bold(m):m} ${b}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function AI(e,t,n){let r=e.fg(t.list[2]),i="",s="",o=[],a="";if(t.quitting)i="QUIT",s=t.added>0?`Discard changes and ${t.added} ${t.added===1?"picture":"pictures"}?`:"Discard changes?",o=[["y","discard"],["n","keep editing"]];else if(t.typing!==void 0)i="TYPE",s=e.dim("#rrggbb, rgb(r g b) or oklch(l c h)"),o=[["enter","set"],["ctrl+u","clear"]],a="esc back";else if(t.overlay==="keys")i="HELP",a="any key closes";else if(t.overlay==="open")i="OPEN",o=[["↑↓","palette"],["a-z","filter"],["enter","take its colors"]],a="esc close";else if(t.compare)i="BEFORE",s="The colors you started from",o=[["space","back to yours"]],a="esc back";else if(t.mode==="seeds")i="SEEDS",o=[["↑↓","seed"],["←→","step"],["⇧←→","×5"],["enter","tune slots"],["o","open a palette"],["p","picture"],["?","keys"]],a=t.fresh&&!t.dirty()?"esc cancel":"esc back";else if(t.mode==="tune")i="IMAGE EDIT",o=[["↑↓","L C H"],["←→","step"],["⇧←→","faster"],["0-9","jump"],["#","type"],["enter","keep"]],a="esc undo";else o=[["↑↓","slot"],["←→","normal or bright"],["tab","tune"],["#","type"],["f","fix"],["p","picture"],["u","undo"],["enter","save"],["?","keys"]],a="esc cancel";if(!t.options.find)o=o.filter(([l])=>l!=="p");if(t.notice)s=e.color?`\x1B[33m${t.notice}\x1B[39m`:t.notice,o=[];let u=i?e.color?`\x1B[7;1m${r} ${i} \x1B[0m `:`[${i}] `:"",c=a?`${e.bold(a.split(" ")[0])} ${e.dim(a.split(" ").slice(1).join(" "))}`:"";for(;;){let l=[s,...o.map(([d,h])=>`${e.bold(d)} ${e.dim(h)}`)].filter(Boolean),f=`${u}${l.join(" ")}`;if($e(f)+$e(a)+3<=n||o.length<=1)return a?wn(f,c,n):rt(f,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function LI(e,t,n,r){let i=SI(r);if(t<zf||n<Yf){let g=[i.bold("ttheme palette editor"),`Needs ${zf}×${Yf} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(b,p)=>rt(g[p]??"",t))}let s=e.failing().length,o=s===0?"✓ Passes the gate":`✗ ${s} ${s===1?"miss":"misses"} in the gate`,a=e.pictures>0?i.dim(`▣ ${e.pictures} ${e.pictures===1?"picture":"pictures"} `):"",u=`${e.dirty()?`${i.color?"\x1B[33m●\x1B[39m":"●"} unsaved `:""}${a}${i.dim(o)}`,l=`${i.fg(e.list[2])}◆${i.color?"\x1B[39m":""} ${i.bold(e.options.title)} ${i.dim(`· ${e.options.name}`)}`,f=n-4,d;if(e.overlay==="keys")d=HI(i,e,t);else if(e.overlay==="open")d=xI(i,e,t,f);else{let g=t-Iu-2,b=e.mode==="seeds"?RI(i,e,f):PI(i,e,f),p=e.mode==="seeds"?FI(i,e,g,f):OI(i,e,g,f);d=Array.from({length:f},(m,k)=>`${rt(b[k]??"",Iu)}${i.dim("│")} ${rt(p[k]??"",g)}`)}let h=[wn(l,u,t),""];for(let g=0;g<f;g++)h.push(rt(d[g]??"",t));return h.push("",AI(i,e,t)),h}async function f0(e,t){let n=new qf(e),{stdin:r,stdout:i}=process,s=i.columns||zf,o=i.rows||Yf,a=[],u=[],c="",l="",f,d=(M)=>i.write(M),h=()=>{if(f=void 0,t.look){let w=n.shown();if(w.join(" ")!==c)c=w.join(" "),t.look(w);return}let M="";if(n.shown().forEach((w,I)=>{if(u[I]!==w&&t.only?.includes(I))M+=vl(I,w),u[I]=w}),M)d(M)},g=()=>{let M=LI(n,s,o,t.color),w="";if(M.forEach((I,$)=>{if(a[$]!==I)w+=`\x1B[${$+1};1H\x1B[0m\x1B[2K${I}`}),a=M,w)d(`\x1B[?2026h${w}\x1B[0m\x1B[?2026l`);if(t.only||t.look)f??=setTimeout(h,33)},b,p,m=!1,k=()=>{d(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${Pi}`),r.setRawMode(!0),r.resume()},v=(M)=>{if(b&&p)r[M?"on":"off"]("data",b),i[M?"on":"off"]("resize",p)};k();try{return await new Promise((M)=>{let w=async(I)=>{let $=e.find;if(!$)return;m=!0,v(!1),clearTimeout(f),f=void 0;try{n.found(await $(n.edited(),I))}catch(N){n.notice=N instanceof Error?N.message:String(N)}m=!1,k(),v(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,c="",g()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],d(Pi),g()},b=(I)=>{l+=I.toString("utf8");let $=gu(l);l=$.pending;for(let R of $.events)if(R.kind==="paste")n.paste(R.text);if($.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test($.keys)&&n.typing===void 0)n.paste($.keys);else for(let R of bu($.keys))if(n.press(R),n.result||n.wants)break;if(n.result){M(n.result==="saved"?n.edited():void 0);return}let N=n.wants;if(N&&!m){n.wants=void 0,w(N.start);return}g()},v(!0),g()})}finally{clearTimeout(f),v(!1),r.setRawMode(!1),r.pause(),d("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as tN}from"node:child_process";import{createHash as T0}from"node:crypto";import{existsSync as qi,mkdirSync as nN,mkdtempSync as rN,readFileSync as H0,rmSync as yo,statSync as iN}from"node:fs";import{homedir as sN,tmpdir as oN}from"node:os";import{dirname as aN,join as Qt}from"node:path";import{pathToFileURL as y0}from"node:url";var CI=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),_I=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),GI=0.04,WI=0.1,UI=0.05,jI=4096;function KI(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function BI(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...KI(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)+([...CI].some((l)=>o.has(l))?-3:0)+([..._I].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 Nu(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:BI(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 h0(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 Qf(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function d0(e,t,n){let[r,i,s]=[Qf(e),Qf(t),Qf(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 g0(e,t){let n=t.map((o)=>d0(...ve(o))).filter(([,o,a])=>Math.hypot(o,a)>=GI);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/jI))),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,f]=d0(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([d,h,g],b)=>{if(Math.hypot(c-d,l-h,f-g)<WI)i[b]=i[b]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/UI),0)/n.length}import{mkdirSync as zI,readFileSync as Xf,writeFileSync as $0}from"node:fs";import{dirname as YI}from"node:path";import{isMainThread as QI,parentPort as k0,Worker as ZI}from"node:worker_threads";var JI=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,qI=[[/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 Zf(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 m0(e,t){let n=JI.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...qI.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function p0(e,t){let n=e.owner||e.named.artist[0]||"";return n!==""&&n===(t.owner||t.named.artist[0]||"")&&e.width===t.width&&e.height===t.height}function b0(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)),f=0;for(let d=o;d<a;d++)for(let h=c;h<l;h++){let g=(d*e.width+h)*4,b=e.data[g+3]/255,p=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=p*b+255*(1-b)}r.push(f/((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 VI(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function w0(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&&VI(e.hash,t.hash)<=2}var XI={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},Pu;async function DI(e){if(e.job==="redraw")return nu(e.home,e.name,e.key,e.paint,e.blur,e.aligns,e.user);if(e.job==="show"){if(Pu?.from!==e.from){let o=Kn(new Uint8Array(Xf(e.from)),$t);Pu={from:e.from,clear:yn(o),inked:Dc(o)}}let{image:r,fill:i,opacity:s}=Um(Pu.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune,e.coloring);return zI(YI(e.to),{recursive:!0}),$0(e.to,Bn(r)),{clear:Pu.clear,fill:i,opacity:s}}let t=Kn(new Uint8Array(Xf(e.from)),$t);if(e.job==="backdrop"){ba(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(Xf(e.source)),cut:e.from!==e.source},e,e.blur,e.coloring);let r=e.tune&&_t(e.home,e.colors.name).find((i)=>i.key===ft(e.origin));if(e.tune&&r)Fs(Se(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:g0(t,e.colors),hash:b0(t)};if(e.job==="thumb")return K(e.to,Bn(Fg(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return $0(e.to,Bn({width:t.width,height:e.height,data:n})),0}function eN(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await DI(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Df{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 ZI(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 ed{lines=new Map;run(e){let t=XI[e.job],n=this.lines.get(t);if(!n)n=new Df,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class td{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Df)}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(!QI&&k0)eN(k0);var Yr=[{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:di,multi:{read:Or}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Pr,multi:{read:gi,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"]},...xi()?[{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:Xg,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:Dg,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:X.map((e)=>e.name),multi:{read:$s},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:Ac,multi:{read:Do,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 E0(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 ks(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var uN=["fit","newest","score"];function nd(e){return uN.find((t)=>t===e)??"fit"}var cN={left:-1,right:1,"shift-left":-10,"shift-right":10};function lN(e){let t=/^(\d+) (\d+)$/.exec(e??"");return t&&(Number(t[1])>0||Number(t[2])>0)?{x:Number(t[1]),y:Number(t[2])}:void 0}var rd=lN(process.env.TTHEME_BG_MARGIN);function fN(e,t,n){if(t<0){if(e!=="fill")return Math.max(N0,e+t);if(!n)return e;return Math.max(N0,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function x0(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function dN(e,t){if(x0(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:kt[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function hN(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var v0=12,gN=4,mN=150,pN=300,M0=12,bN=2,wN=150,$N=30,kN=4000,yN=8000,S0=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,EN=process.platform==="win32"?"alt+v":"ctrl+v",I0=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",vN=1280,MN=16,SN=kt.indexOf("top-right")+1,N0=20,Vi=2147483645,Eo=2147483646,P0=-1073741827,IN=-1073741828,R0=2,NN=80,PN=16,RN=0.4,ON=3221225472,FN=256,TN=3,HN=8;function Ru(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,stage:"fetch",arrived:new Set}}function vo(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return vo(e.errors[0]);if(e.cause)return vo(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 id(e,t){return`${e}: ${vo(t)}`}function O0(e){return e.width*e.height}function F0(e,t){return`${e}-${T0("sha1").update(t).digest("hex").slice(0,8)}`}function xN(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function AN(e,t){try{return JSON.parse(H0(Qt(rn(e),t),"utf8"))}catch{return{}}}function LN(e,t,n){K(Qt(rn(e),t),`${JSON.stringify(n)}
507
- `)}class sd{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(Yr.map((e)=>[e.name,E0(e,process.env[e.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;kept=new Map;unsaved=new Set;crediting=new Map;thumbQueue=[];thumbing=0;clarity=new Map;tunedFiles=[];presenting=!1;again=!1;covered="";renders=new ed;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=xp(process.env);files=Ap(process.env);moves=Cp(process.env);layers=Lp(process.env);bandFiles=new Map;nextBand=ON;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Lf((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=rN(Qt(oN(),"ttheme-find-"));home;catalog;entry;blurring;coloring;start;constructor(e,t,n,r,i){this.start=i,this.home=e,this.catalog=t,this.entry=n,this.tone=ki(n,n.signatureSlots),this.blurring=Lr(e),this.coloring=Fa(e);let s={size:"fill",at:SN,opacity:this.tone.opacity};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:nd(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Or(this.setting("TTHEME_FIND_RATING")),block:gi(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:$s(this.setting("TTHEME_FIND_SITES")),hide:Do(this.setting("TTHEME_FIND_HIDE")),hideTags:ks(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Yr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:E0(o,Us(o.name)),multi:o.multi&&{none:o.multi.none},about:o.about,entry:o.entry,advanced:o.advanced,cursor:0})),colors:{cursor:n.cursor,selection:n.selection,background:n.background,foreground:n.foreground,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",stage:"fetch",sites:[],focus:0,top:0,scroll:0,beat:0,mode:"grid",help:!1,scene:Math.max(0,Gt.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=Ru(this.boardKey,r!==""),this.boards.set(this.board.key,this.board)}get signal(){return this.session.signal}get site(){return this.tab===0?void 0:X[this.tab-1]}get sites(){return this.site?[this.site]:X.filter((e)=>this.view.enabled.includes(e.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??gN}get nextTabName(){let e=(this.tab+1)%(X.length+1);return e===0?"all":X[e-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(e){return this.values.get(e)}narrowed(){return Cc(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 Qt(rn(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=ta(e.site,e.post);return Qt(rn(e.site),"thumb",`${F0(e.post.id,t)}.${Yn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Ct(n,r.id),s=nn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,page:n===Kr?"":n.pageUrl(r.id),artist:n===Kr?Ew(r.source):r.named.artist[0]??"",score:r.score,variants:t,mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i),missing:this.thumbless.has(i)}}show(){let e=this.view,t=this.board;if(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,this.stageOf(t),e.note=t.note,e.focus=Math.max(0,Math.min(t.focus,e.tiles.length-1)),e.top=t.top,this.showing!==t)this.showing=t,this.snap()}stageOf(e){let t=this.view;t.stage=e.stage,t.ranking=e.ranking,t.sites=this.sites.map((n)=>({name:n.name,arrived:e.arrived.has(n.name)}))}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${Pi}`);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";if(await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.start&&"paste"in this.start)this.pasted(this.start.paste);else if(this.start)this.fromClipboard();else this.peek();this.draw();let s=await n;return this.session.abort(),this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),this.quietCount(),clearInterval(r),clearInterval(this.ticking),clearTimeout(this.gliding),e.off("data",this.onData),t.off("resize",this.onResize),this.write(`\x1B_Ga=d,d=A,q=2\x1B\\${Pi}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),yo(this.scratch,{recursive:!0,force:!0}),dm(),s}write(e){process.stdout.write(e)}get saved(){return this.view.saved?.text}get installs(){return this.view.installed.length}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(Ww)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=Uf(this.input);n;n=Uf(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=gu(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),xN(this.typed)){this.partial=setTimeout(this.flushKeys,$N);return}this.flushKeys()};flushKeys=()=>{let e=bu(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!ea(t,this.site??X[0]);return Ui(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 — ${I0}`);return}this.pasted(e.text);return}await this.bring(()=>du(e.bytes,e.source))}notice(e,t=kN){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 Nw()}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 · ${EN} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},yN),this.draw()}async fromClipboard(){let e=this.view;if(Af()){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 Iw(Qt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${vo(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await xf(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${I0}`);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=ea(t,this.site??X[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ui(t).sort((i,s)=>Number(!S0.test(i))-Number(!S0.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)=>xf(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(d){if(!r.signal.aborted)n.note=void 0,this.notice(vo(d),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=Mw(i.bytes);vw(s,i.source);let o=this.origPath(Kr,s,i.ext);K(o,i.bytes);let a=y0(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:T0("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Kr,post:u},l=this.previewPath(c);K(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=Ru(`local|post:${s}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,c)}single(e,t){e.searching=!1,this.posts.set(Ct(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)=>zn(i)>zn(r)?i:r),t=Math.ceil((zn(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.screen=[],this.scroll(),this.snap(),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<Jr.cols||this.rows<Jr.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}=qr(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"||e==="shift-tab"){let o=X.length+1;this.tab=(this.tab+(e==="tab"?1:o-1))%o,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=mo(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[(s+i.length)%i.length]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=mo(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=Yw(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(Yr[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":ks(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<Kf:/^[\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),pN)}pending(){let e=(t)=>this.view.settings[Yr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:nd(e("TTHEME_FIND_ORDER")),rating:Or(e("TTHEME_FIND_RATING")),narrow:Cc(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:$s(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:X.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 Uc(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=Yr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Yr[i];if(s)this.values.set(s.name,r.value)});let n=Yr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=Or(this.setting("TTHEME_FIND_RATING")),e.block=gi(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=nd(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=$s(this.setting("TTHEME_FIND_SITES")),e.hide=Do(this.setting("TTHEME_FIND_HIDE")),e.hideTags=ks(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=Qt(this.home,"ttheme","config.zsh");try{let n=qi(t)?H0(t,"utf8"):"";return K(t,e.reduce((r,[i,s])=>Ta(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 s=((t.pick??r.length)+(e==="down"?1:r.length))%(r.length+1);t.pick=s===r.length?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(!hN(t)){e.suggest=void 0;return}let n=[...new Map(kp(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,TN);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await gm(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,HN),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},mN)}async commit(e){let t=ea(e,this.site??X[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=X.indexOf(e)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Ru(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await ys(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(Ct(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.glide(),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{tN(n,[t.site.pageUrl(t.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(e){let t=this.view;if(t.tuning){this.tuneKey(e);return}if(e==="left"||e==="right"){this.direction=e==="left"?-1:1,this.focus(t.focus+this.direction);return}if(e==="shift-left"||e==="shift-right"){t.scene+=e==="shift-left"?-1:1,t.details=!1,this.draw();return}if(e==="i"){t.details=!t.details,this.inform(),this.draw();return}if(e==="t"){t.tuning={field:0,held:{...t.tune},fill:this.current?.fill??0},this.draw();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()}tuneKey(e){let t=this.view,n=t.tuning,r=t.tune;if(e==="up"||e==="down"){n.field=(n.field+(e==="up"?2:1))%3,this.draw();return}let i=cN[e];if(i!==void 0){if(n.field===0)r.size=fN(r.size,i,n.fill);else if(n.field===1)r.at=(r.at-1+Math.sign(i)+9)%9+1;else r.opacity=Math.max(0,Math.min(100,Math.round(r.opacity*100)+i))/100;this.retune();return}if(/^[1-9]$/.test(e)){n.field=1,r.at=Number(e),this.retune();return}if(e==="="){let s=t.untuned;if(n.field===0)r.size=s.size;else if(n.field===1)r.at=s.at;else r.opacity=s.opacity;this.retune();return}if(e==="+"){t.tune={...t.untuned},this.retune();return}if(e==="enter"){t.tuning=void 0,this.draw();return}if(e==="esc")t.tune={...n.held},t.tuning=void 0,this.retune()}retune(){if(this.draw(),this.current&&this.view.shown?.id===this.current.key)this.reveal()}inform(){let e=this.view,t=e.tiles[e.focus],n=t&&this.posts.get(t.key);e.info=n?this.infoOf(n):void 0}infoOf(e){let{site:t,post:n}=e,r=n.named,i=lm(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=Es(n.source),a=/^https?:\/\//i.test(o)?o:t===Kr&&o.startsWith("/")?y0(o).href:void 0;return{page:t===Kr?"":t.pageUrl(n.id),source:o,...a?{link:a}:{},artists:r.artist,characters:r.character,series:r.copyright,tags:n.tags.filter((u)=>!s.has(u)),...i?{rating:i}:{},...n.posted?{posted:n.posted}:{},ext:(nn(n)??n).ext,uploader:n.owner}}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.glide(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=qr(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}glide(){if(this.bands)this.prebake();if(this.gliding)return;let e=qr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*qe.height,i=r-n.scroll;if(i===0||n.mode!=="grid"){n.scroll=r;let s=this.gliding!==void 0;if(this.gliding=void 0,s)this.draw();return}if(Math.abs(i)>2*e)n.scroll=r-Math.sign(i)*e,i=r-n.scroll;n.scroll+=Math.sign(i)*Math.max(1,Math.round(Math.abs(i)*RN)),this.draw(),this.gliding=setTimeout(t,PN)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*qe.height}prebake(){let e=this.view;for(let t of Bf({...e,scroll:e.top*qe.height},this.cols,this.rows).images)if(t.crop!==void 0)this.band(t.path,t.crop,t.rows)}query(e,t=this.view){let n=t.tag===this.entry.booru?yp(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(Wc([...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=Ru(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})=>{let c=Wc(a)+1<=o.tagBudget?o.uploadedBy:void 0;return[...c?[...u.keys()].map((l)=>({site:o,tags:`${a} ${c(l)}`,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})=>Uc(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=id(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,id(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=qr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+R0)*e}need(){let{perRow:e,rowsVis:t}=qr(this.cols,this.rows);return(t+R0)*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=hm(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===Lt?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{aa(n,await ua(n.map((r)=>r.md5),this.signal))}catch{}return t}staged(e){if(e===this.board)this.stageOf(e),this.draw()}async round(e){e.stage="fetch",this.staged(e);let t=X.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{let u=await this.page(a.site,a.tags,a.page);return e.arrived.add(a.site.name),this.staged(e),{source:a,posts:u}}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 f=c&&p0(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:f};let d=Ct(a.site,l.id);if(e.seen.has(d))continue;e.seen.add(d);let h={site:a.site,post:l};if(this.eligible(h))e.kin.set(h,[f,...m0(a.site,l)]),r.push(h);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?h0(i):i;else{let a=Nu(i,this.frame(),this.matched),u=a.slice(0,this.need()),c={done:0,total:u.length};if(e.ranking=c,this.staged(e),await this.looks(u,()=>{c.done++,this.staged(e)}),e.ranking=void 0,!this.live(e))return;o=[...Nu(u,this.frame(),this.matched),...a.slice(u.length)]}e.stage="check",this.staged(e);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(Ct(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=Nu(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=Zf(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++,O0(r.post)<=O0(s.post))continue;for(let a of[...i,...Zf(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(Ct(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e,t){let n=0;await Promise.all(Array.from({length:M0},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Ct(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=ta(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<v0&&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<v0&&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.saveKept(),this.pumping===e)this.pumping=0}}eligible({site:e,post:t}){let n=nn(t);if(!ra(e,t,this.view.rating)||na(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"||cm(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)}keep(e,t){let n=`${e.key}/${t}`,r=this.kept.get(n);if(!r)r=AN(e,t),this.kept.set(n,r);return r}async transparent(e,t){let n=this.keep(e,"probes.json"),r=n[t.id];if(r!==void 0)return r;try{let i=await ca(e,t,this.signal),s=mi(e,t),o=(i===void 0?await mm(s.site,s.url,this.signal):i)?.alpha===!0;return n[t.id]=o,this.unsaved.add(`${e.key}/probes.json`),o}catch{return!1}}saveKept(){for(let e of this.unsaved){let[t,n]=e.split("/"),r=X.find((i)=>i.key===t);if(r)LN(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Ct(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)=>w0(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})}credit(e,t){let{site:n,post:r}=e;if(!oa(n,r))return Promise.resolve();let i=Ct(n,r.id),s=this.crediting.get(i);if(!s)s=this.credits(e,t).finally(()=>this.crediting.delete(i)),this.crediting.set(i,s);return s}async credits({site:e,post:t},n){let r=this.keep(e,"credits.json"),i=r[t.id];if(!i){try{i=await sa(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}vs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=Ym(this.home),r=this.keep(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 ys(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);this.unsaved.add(`${e.key}/owners.json`);let a=fm(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(qi(t))return iN(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await la(e,n,this.signal,r);return K(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(!this.signal.aborted&&this.thumbing<M0&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Ct(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=qe.cols*this.cell.w,i=qe.rows*this.cell.h,s=ta(t,n),o=Qt(rn(t),"tile",`${F0(n.id,s.url)}-${r}x${i}.png`);if(!qi(o)){let a=this.previewPath(e);if(await this.cached(s.site,a,s.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(Ct(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,this.inform(),!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),wN),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n)return;let r=new AbortController;if(this.fetch=r,this.credit(n,r.signal),!nn(n.post))return;let{site:i}=n,s=this.board;try{await ca(i,n.post,r.signal);let o=nn(n.post),a=this.origPath(i,e.id,o.ext);if(!qi(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=mi(i,n.post,o),c=await this.cached(u.site,a,u.url,(d,h)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:d,size:h},this.draw()});if(r.signal.aborted)return;if(t.fetching=void 0,s!==this.board)return;let l={site:i,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let f=await this.render(l,"plain");if(r.signal.aborted||s!==this.board)return;if(f.clear===0&&xi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(i,e.id,a,r.signal),r.signal.aborted||s!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let d=await this.render(l,"cut").catch(()=>{return});if(r.signal.aborted||s!==this.board)return;if(d&&eu(d.clear))l.using="cut";else yo(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(!r.signal.aborted&&!this.signal.aborted)t.error=id(i.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=Qt(rn(e),"cut",`${t}.png`);if(qi(i))return i;try{return nN(aN(i),{recursive:!0}),await Zs(n,i,r),i}catch{yo(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]){let n=e.tiles[t],r=n&&this.posts.get(n.key);if(r)this.credit(r,this.signal);if(this.prefetching>=bN||!r||!nn(r.post))continue;let{site:i,post:s}=r;this.prefetching++,ca(i,s,this.signal).then(async()=>{let o=nn(s),a=this.origPath(i,s.id,o.ext),u=mi(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,vN),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!x0(o,this.view.untuned),u=o.opacity!==this.view.untuned.opacity,c=a?`-${o.size}-${o.at}${u?`-${Math.round(o.opacity*100)}`:""}`:"",l=Qt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}${c}.png`),f=`${e.site.key}:${e.id}:${t}:${i}x${s}`,d=this.clarity.get(f);if(d&&qi(l))return e.fill=d.fill,{clear:d.clear,path:l,opacity:d.opacity,touched:u};let h=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:l,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/Zc(n,r).width,coloring:this.coloring,...a?{tune:{size:o.size,at:o.at,...u?{opacity:o.opacity}:{}}}:{}});if(this.clarity.set(f,h),e.fill=h.fill,a)this.keepTuned(l);return{clear:h.clear,path:l,opacity:h.opacity,touched:u}}keepTuned(e){this.tunedFiles.push(e);while(this.tunedFiles.length>MN){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;yo(this.tunedFiles.splice(t,1)[0],{force:!0})}}async present(){let e=this.current;if(!e)return;let t=e.using,n=this.view.tune.opacity,{clear:r,path:i,opacity:s,touched:o}=await this.render(e,t);if(this.current!==e||e.using!==t)return;if(!o&&this.view.tune.opacity===n)this.view.untuned.opacity=s,this.view.tune.opacity=s;if(this.view.tuning&&e.fill)this.view.tuning.fill=e.fill;this.view.shown={id:e.key,clear:r,bytes:e.size,path:i,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;if(this.presenting){this.again=!0;return}this.presenting=!0,e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(this.presenting=!1,this.again){this.again=!1,this.reveal();return}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();let r=dN(e.tune,e.untuned),i=this.posts.get(n.key)?.post;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)}`,artist:i?.named.artist??[],source:Es(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,coloring:this.coloring,...r?{tune:r,aligns:Wr(ne(this.home).terminals),user:sN()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),Nt(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${kt[o-1]} · ${a.toFixed(2)}`:"",c=i?.named.artist.length?`${i.named.artist.join(", ")} · `:"";e.saved={text:`Background · ${this.entry.name} ← ${c}${n.site.name} ${n.id}${u}`,key:t.key},e.installed.push(t.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(s){e.error=s instanceof Error?s.message:String(s)}e.installing=void 0,this.draw()}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let e=Bf(this.view,this.cols,this.rows);this.view.loaderFrom=e.loader?this.view.loaderFrom??this.view.beat:void 0;let t="";e.lines.forEach((i,s)=>{if(this.screen[s]!==i)t+=`\x1B[${s+1};1H\x1B[K${i}`,this.screen[s]=i});let n=new Set;for(let i of e.images){let s=this.bands?this.banded(i):i;if(!s)continue;if(n.add(s.id),this.sent.get(s.id)!==s.path){let a=Uw(s,this.files);if(a===void 0)continue;t+=a,this.sent.set(s.id,s.path),this.placed.delete(s.id)}let o=`${s.row};${s.col};${s.cols};${s.rows};${s.crop};${s.z}`;if(this.placed.get(s.id)!==o){if(!this.moves&&this.placed.has(s.id))t+=jf(s.id);t+=jw(s,this.cell),this.placed.set(s.id,o)}}for(let i of this.sent.keys())if(!n.has(i))t+=Kw(i),this.sent.delete(i),this.placed.delete(i);t+=this.cover();let r=this.view.mode==="grid"&&this.view.editing!==void 0?this.caret():"";if(t||r)this.write(`\x1B[?2026h${t}${r}\x1B[?2026l`);this.pace(e.tick)}cover(){let e=`${this.cols};${this.rows}`;if(!this.layers||this.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(ve(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${Vi},q=2;${n}\x1B\\`,rd)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${Eo},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${Eo},p=${Eo},c=1,r=1,C=1,z=${IN},q=2\x1B\\`}else if(!this.moves)t+=jf(Vi);if(this.covered=e,rd){let{x:n,y:r}=rd;return`${t}\x1B_Ga=p,i=${Vi},p=${Vi},P=${Eo},Q=${Eo},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${P0},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${Vi},p=${Vi},c=${this.cols},r=${this.rows},C=1,z=${P0},q=2\x1B\\`}caret(){return`\x1B[1;${Math.min(this.cols,$e(`⌕ ${this.view.editing??""}`)+1)}H`}pace(e){if(e)this.ticking??=setInterval(()=>{this.view.beat++,this.draw()},NN);else if(this.ticking)clearInterval(this.ticking),this.ticking=void 0}banded(e){if(e.crop===void 0)return e;let t=this.band(e.path,e.crop,e.rows,!this.gliding);return t?.ready?{...e,id:t.id,path:t.path,crop:void 0}:void 0}band(e,t,n,r=!0){let i=`${e}|${t}|${n}`,s=this.bandFiles.get(i);if(s||!r)return s;let o=this.nextBand++,a={id:o,path:Qt(this.scratch,`band-${o}.png`),ready:!1};return this.bandFiles.set(i,a),this.renders.run({job:"band",from:e,to:a.path,y:t*this.cell.h,height:n*this.cell.h}).then(()=>{a.ready=!0,this.draw()}).catch(()=>{}),this.trimBands(),a}trimBands(){for(let[e,t]of this.bandFiles){if(this.bandFiles.size<=FN)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),yo(t.path,{force:!0})}}}async function A0(e,t,n){let r=new sd(e,ln(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function L0(e){let t=ue(),n=ln(t),r=Ar(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new sd(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
508
- `),0;return s}import{existsSync as Fu,readdirSync as CN,readFileSync as od,rmSync as C0,statSync as _0}from"node:fs";import{homedir as _N}from"node:os";import{join as Mo}from"node:path";var GN=150,WN=260;function Ou(e){return e?.includes(`path = "${_("")}`)===!0}function UN(e){try{return ne(e).terminals.includes("warp")}catch{return!1}}function jN(e,t){let n=_(t);if(!Fu(e))return;return CN(e).filter((i)=>i.startsWith(`${n}.`)&&/^[0-9a-f]{8}\.yaml$/.test(i.slice(n.length+1))).map((i)=>({file:i,at:_0(Mo(e,i)).mtimeMs})).sort((i,s)=>s.at-i.at)[0]?.file??(Fu(Mo(e,`${n}.yaml`))?`${n}.yaml`:void 0)}function kr(e,t,n,r=_N()){if(!t||gt(e)||e.TMUX||Mt(e)!=="warp")return;let i=mr(r,n);if(!Fu(i)||!UN(n))return;let s=_r(r),o=Ba(n),a=[],u,c,l=(g)=>{let b=od(i,"utf8"),p=pr(b);if(p===g)return;if(Ou(g)&&!Ou(p)&&!Fu(o))K(o,p??"");if(en(i,Ja(b,g)),!Ou(g))C0(o,{force:!0})},f=(g)=>{for(let b of a.splice(0))if(b===g)a.push(b);else C0(Mo(s,b),{force:!0})},d=()=>{clearTimeout(u),clearTimeout(c)},h=(g,b)=>{d(),u=setTimeout(()=>{let p=b;if(!p)p=`${_(g.name)}.view-${process.pid}-${a.length+1}.yaml`,K(Mo(s,p),Ks(g)),a.push(p);let m=p,k=Date.now()-_0(Mo(s,m)).mtimeMs;c=setTimeout(()=>{l(Ql(g.name,m)),f(m)},Math.max(0,WN-k))},GN)};return{slots:[],paint:(g)=>{return h(g,jN(s,g.name)),""},look:(g,b)=>{let[p="",m="",k="",,...v]=b;h({name:g,background:p,foreground:m,cursor:k,ansi:v})},wear:(g,b)=>b.includes("warp")?"":void 0,saved:async()=>new Map([["theme",pr(od(i,"utf8"))??""]]),restore:(g)=>{d();let b=g.get("theme");if(b)l(b);else if(Ou(pr(od(i,"utf8"))))l(Ka);return f(),""}}}function G0(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function W0(e,t){if(e.includes("/"))return e;let n=xr(t,!1),r=n.filter((s)=>ir(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function JN(e,t,n){let r=ne(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)gn(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))mt(e,t,r);return{state:r,fresh:i}}function qN(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 U0(e,t,n){let r=dp(t),i=Jt(vt(r.name,dl(r),n.palettes)),s=Ke(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)Sa(e,[...Nn(e),i]);return i.name}var VN=["background","foreground","cursor"];function j0(e){try{e();return}catch(t){return t.message}}function K0(e,t,n){return Ke(e,t,!1).palettes.filter((r)=>r.name!==n).map((r)=>({name:r.name,colors:{background:r.background,foreground:r.foreground,cursor:r.cursor,selection:r.selection,ansi:r.ansi}}))}function B0(e,t){let n=new Set(_t(e,t).map((r)=>r.key));return{count:()=>_t(e,t).length,added:()=>_t(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(tu(e,t)??[]).filter((r)=>!n.has(ft(r))),discard:()=>{let r=_t(e,t).filter((i)=>!n.has(i.key));for(let i of r)Ei(e,t,i.key),pa(e,t);if(r.length>0)Nt(e)}}}function zN(...e){let t=new Map;for(let n of e.flatMap((r)=>r??[]))t.set(ft(n),n);return t.size>0?[...t.values()]:void 0}function J0(e,t,n,r){if(!Hp(process.env))return;return async(i,s)=>{let o=Jt(vt(t,r(i),n.palettes)),{saved:a}=await A0(e,o,s);return{...a?{note:a}:{},count:_t(e,t).length}}}async function q0(e){let t=process.stdout.isTTY===!0,n=cr(process.env,t)??kr(process.env,t,ue()),r=n?await n.saved():new Map,i=n?.look?{look:(s)=>n.look?.(e.name,s)}:n?{only:n.slots}:{};try{return await f0(e,{color:!gt(),...i})}finally{if(n)process.stdout.write(n.restore(r))}}async function V0(e,t,n){let r=ue(),i=We(r),s=await uw(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=on(o);if(a)throw Error(`${o} ${a}`);if(Me(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=ll(r,o);if(So(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?Ar(Ke(r,i).palettes,t):void 0;if(!G0())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(Me(c.name)?c.base:c.default?void 0:c.name),f=c?fl(c,o,`kept from ${c.name}`):void 0,d=c?tu(r,c.name)??c.pictures:void 0,{base:h,ansiSource:g,group:b,...p}=f??{name:o,signature:VN,...Vr(ku)},m=B0(r,o),k=({colors:w,signature:I})=>{let $=zN(d,m.fresh());return dl({...p,...w,signature:I,...l?{base:l}:{},...$?{pictures:$}:{}})},v=await q0({title:"New palette",name:o,...f?{colors:f}:{},signature:p.signature,...p.waive?{waive:p.waive}:{},palettes:K0(r,i,o),pictures:m.count(),find:J0(r,o,i,k),check:(w)=>j0(()=>vt(o,k(w),i.palettes))});if(!v){m.discard(),console.log("Nothing made");return}KN(BN(u),{recursive:!0}),K(u,k(v));let{state:M}=JN(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
509
- ${u}`),await Rn(r,Ke(r,i).palettes.filter((w)=>w.name===o),M.terminals),console.log(`
510
- \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function YN(e,t,n){let r=Jt(vt(e,t,n.palettes));return Cs(r).length>0?As(r).filter((i)=>i.startsWith(" ✗")):[]}async function z0(e){let t=ue(),n=We(t),r=ne(t),i=Ke(t,n,!1),s=W0(e,t),o=Tu(t,s),a=o&&So(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=Tu(t,a);if(!u||!So(u)){let m=i.palettes.some((k)=>k.name===a);throw Error(m?`${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(!G0())throw Error("edit opens the palette editor — run it in a terminal");let c=ad(u,"utf8"),l;try{l=vt(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let f=B0(t,a),d=new Set((l.pictures??[]).map((m)=>ft(m))),h=({colors:m,signature:k})=>up(hp(gl(c,m),k),f.fresh().filter((v)=>!d.has(ft(v)))),g=await q0({title:"Edit palette",name:a,colors:hl(l),signature:l.signatureSlots,waive:l.waive,palettes:K0(t,n,a),pictures:f.count(),find:J0(t,a,n,h),check:(m)=>j0(()=>vt(a,h(m),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let b=h(g);if(b===c){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(K(u,b),r.palettes.includes(a))mt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let p=YN(a,b,n);if(p.length>0)console.log(`
520
+ }`;async function p0(){if(zf())return;if(process.platform==="darwin"){let[t="",e=""]=(await De("osascript",["-l","JavaScript","-e",TO])).stdout.trim().split("\t");return{stamp:t,picture:e==="picture"}}if(process.platform==="linux"&&!m0()){let e=Boolean(process.env.WAYLAND_DISPLAY)?(await De("wl-paste",["--list-types"])).stdout:(await De("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:e,picture:/^image\//m.test(e)}}return}function fc(t){let e=[],n="",r=0;while(r<t.length){if(t[r]!=="\x1B"){n+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:e,keys:n,pending:t.slice(r)};e.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((f)=>f!==-1);if(o.length===0)return{events:e,keys:n,pending:t.slice(r)};let s=Math.min(...o),a=t.slice(r+2,s),[c="",u="",...l]=a.split(";");e.push({kind:"osc",code:c,meta:AO(u),payload:l.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")e.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");e.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:e,keys:n,pending:t.slice(r)};n+=t[r],r++}return{events:e,keys:n,pending:""}}function AO(t){let e={};for(let n of t.split(":")){let r=n.indexOf("=");if(r>0)e[n.slice(0,r)]=n.slice(r+1)}return e}var is=(t)=>Buffer.from(t).toString("base64"),Wf=(t)=>Buffer.from(t,"base64");function s0(t,e){return e.find((n)=>t.includes(n))}class Kf{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=is(a0("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,e){this.send=t,this.deliver=e}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${Uf.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${is("ttheme")}:pw=${this.pw};${is(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,e){if(t.type!=="read")return;let n=t.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=t.mime?Wf(t.mime).toString("utf8"):r.mime,e)r.chunks.push(Wf(e));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"The clipboard read was not allowed":`The terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=s0(o,[..._f,...RO]);if(!s){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,c=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${is(c)}:pw=${a};${is(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,e){let n=t.t??"";if(n==="m"){if(t.x==="-1"){this.offered=[];return}if(e){this.offered=e.split(" ").filter(Boolean);let a=Uf.filter((c)=>this.offered.includes(c));this.send(`\x1B]72;t=m:o=${a.length>0?1:0};${a.join(" ")}\x1B\\`)}return}if(n==="M"){let a=e?e.split(" ").filter(Boolean):this.offered,c=s0(a,Uf);if(!c){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:a,index:a.indexOf(c)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`The drop failed: ${e.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(e)r.chunks.push(Wf(e));if(t.m==="1"||e)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),c=o==="text/uri-list"?Ui(a).find((u)=>yO(u)):void 0;s=c?{kind:"bytes",bytes:new Uint8Array(lc(c)),source:c}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{readFileSync as CO}from"node:fs";var gt={pitch:25,cols:22,rows:9,height:13},Wr={cols:25,rows:16},He=3,jO=2147483648,GO=-1073741826,UO=1600,b0=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],WO=56,_O=4,w0=20,BO=50,$0=[["space","unfolds a set of ×N"],["o","opens the post page in a browser"],["c","switches between cutouts and every post"],["a","opens the advanced filters"],["1-9","turn a tag of the tags row on or off"],["ctrl+v","tries on a picture from the clipboard — or drop one on the window"]],zO="\x1B[0m",vt="\x1B[1m",C="\x1B[2m",as="\x1B[32m",Ve="\x1B[33m",KO={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",Z:"shift-tab","1;2C":"shift-right","1;2D":"shift-left"};function mc(t){let e=[],n=0;while(n<t.length){let r=t[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(n+1));if(i){e.push(KO[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let o=t[n+1]??"";if(/^[a-z]$/.test(o)){e.push(`alt-${o}`),n+=2;continue}e.push("esc"),n++;continue}e.push(r==="\r"||r===`
521
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return e}var R0="\x1B]1337;ReportCellSize\x07\x1B[16t\x1B[14t\x1B[18t",k0="\x1B]1337;ReportCellSize=";function Vf(t){let e=t.indexOf(k0);if(e!==-1){let s=t.slice(e+k0.length),a=[s.indexOf("\x07"),s.indexOf("\x1B\\")].filter((l)=>l!==-1),c=a.length>0?Math.min(...a):-1,u=c===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(s.slice(0,c));if(u){let l=Number(u[3]);return{cell:{h:Math.round(Number(u[1])*l),w:Math.round(Number(u[2])*l)},rest:t.slice(0,e)+s.slice(c+(s[c]==="\x07"?1:2))}}}let n=t.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(n+1));if(r)return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,n)+t.slice(n+1+r[0].length)};let i=y0(t,4),o=y0(t,8);if(!i||!o||o.a===0||o.b===0)return null;return{cell:{h:Math.floor(i.a/o.a),w:Math.floor(i.b/o.b)},rest:t.replace(i.text,"").replace(o.text,"")}}function y0(t,e){let n=t.indexOf(`\x1B[${e};`),r=n===-1?null:new RegExp(`^\\[${e};(\\d+);(\\d+)t`).exec(t.slice(n+1));return r?{a:Number(r[1]),b:Number(r[2]),text:`\x1B${r[0]}`}:null}function cr(t,e){let n=e-He-2;return{perRow:Math.max(1,Math.floor((t-1)/gt.pitch)),rowsVis:Math.max(1,Math.floor(n/gt.height)),height:n}}function P0(t,e=!0){if(e)return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`;let n;try{n=CO(t.path).toString("base64")}catch{return}let r=n.match(/.{1,4096}/g)??[""];return r.map((i,o)=>{let s=o<r.length-1?1:0;return o===0?`\x1B_Ga=t,f=100,i=${t.id},m=${s},q=2;${i}\x1B\\`:`\x1B_Gm=${s},q=2;${i}\x1B\\`}).join("")}function H0(t,e){let n=t.crop===void 0?"":`,x=0,y=${t.crop*e.h},w=${t.cols*e.w},h=${t.rows*e.h}`;return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id}${n},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function Zf(t){return`\x1B_Ga=d,d=i,i=${t},p=${t},q=2\x1B\\`}function F0(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Wi(t){return`\x1B[38;2;${nt(t).join(";")}m`}function hc(t){return`\x1B[48;2;${nt(t).join(";")}m`}var qf=!1;function gc(t){return qf=!0,t.beat}function _i(t){return b0[gc(t)%b0.length]}function st(t){return tt(t)}function x0(t,e){if(tt(t)<=e)return t;let n="";for(let r of t){if(tt(n+r)>e)break;n+=r}return n}function Bi(t){return`\x1B[${30+t}m`}function zi(t,e,n,r){return n?[[`${Qi} `,r],[t,e,n]]:[[t,e]]}function Jf(t){return t.reduce((e,[n])=>e+st(n),0)}function qO(t,e){let n=[],r=e;for(let[i,o,s]of t){let a=st(i);if(a<=r){n.push([i,o,s]),r-=a;continue}n.push([`${x0(i,r)}…`,o,s]);break}return n}class dc{parts=[];cols;constructor(t){this.cols=t}put(t,e,n="",r){return this.parts.push({col:t,text:e,sgr:n,...r?{link:r}:{}}),t+st(e)}run(t,e){let n=t;for(let[r,i,o]of e)n=this.put(n,r,i,o);return n}right(t,e){this.run(t-e.reduce((n,[r])=>n+st(r),0),e)}center(t,e){this.run(Math.floor((t-e.reduce((n,[r])=>n+st(r),0))/2),e)}render(){let t="";for(let{col:e,text:n,sgr:r,link:i}of this.parts){if(e>=this.cols||e<0)continue;let o=x0(n,this.cols-e);t+=`\x1B[${e+1}G${r}${Ws(o,i)}${r?zO:""}`}return t}}function JO(t){return t.replace(/_\([^)]*\)?$/,"")}function L0(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<UO?Ve:C]}function cs(t,e,n,r){let i=[...r.keys??[]],o=r.lead,s=r.right,a=()=>{let l=[...o?[Jf(o)]:[],...i.map(([d,m])=>st(d)+1+st(m))];return(r.badge?st(r.badge)+4:0)+l.reduce((d,m)=>d+m,0)+3*Math.max(0,l.length-1)+(s?3+st(s[0])+1+st(s[1]):0)};while(a()>e)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&a()>e)o=qO(o,Math.max(0,Jf(o)-(a()-e)-1));let c=0;if(r.badge)c=t.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...o?[o]:[],...i.map(([l,f])=>[[l,vt],[` ${f}`,C]])].forEach((l,f)=>{c=t.run(c+(f?3:0),l)}),s)t.right(e,[[s[0],vt],[` ${s[1]}`,C]])}function YO(t,e){if(t==="d")return C;if(t==="b")return vt;if(t==="s")return hc(e.colors.selection);if(t==="c")return hc(e.colors.cursor);let n=/^([BK]?)(\d+)$/.exec(t);if(!n)return"";let r=Number(n[2]),i=(o)=>r<8?o+r:o+52+r;if(n[1]==="K")return`\x1B[30;${i(40)}m`;return`\x1B[${n[1]==="B"?"1;":""}${i(30)}m`}function DO(t,e,n,r,i){let o=he.indexOf(Ma(r.scene)),s=he.flatMap((c,u)=>[...u?[[" ",""]]:[],[c.name,u===o?vt+i:C]]),a=s.reduce((c,[u])=>c+st(u),0)<=n;t?.run(e,a?s:[[Ma(r.scene).name,vt+i],[` ${o+1}/${he.length}`,C]])}function VO(t,e,n,r,i,o,s){let{ansi:a,cursor:c}=o.colors;DO(t[e-2],n,r,o,s);let u=r<sb?3:4;if(r>=56)u=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let d=0;d<8;d++)l=(t[e]?.put(l,"▀".repeat(u),Wi(a[d]??c)+hc(a[d+8]??c))??l)+1;let f=e+2;for(let d of Ma(o.scene).lines){let m=ab(d,r);if(!m)continue;if(f>i)return;t[f]?.run(n,m.map(([g,$])=>[g,YO($,o)])),f++}}function ZO(t,e,n){let r=[[]];for(let s of t){let a=r[r.length-1];if(a.length===0||st([...a,s].join(" "))<=e)a.push(s);else if(r.length<n)r.push([s]);else break}let i=r.reduce((s,a)=>s+a.length,0),o=r[r.length-1];while(i<t.length&&o.length>0&&st([...o,`+${t.length-i}`].join(" "))>e)o.pop(),i--;if(i<t.length)o.push(`+${t.length-i}`);return r.filter((s)=>s.length>0).map((s)=>s.join(" "))}function v0(t){return t.replace(/^https?:\/\/(?:www\.)?/,"")}function QO(t,e,n,r,i){let o=r.info,s=o?.artists??[],a=Bi(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",o?.page?zi(v0(o.page),"",o.page,a):[["—",C]]],["Source",o?.source?zi(v0(o.source),"",o.link,i):[["—",C]]],["Artist",[s.length>0?[s.join(" "),""]:["—",C]]]].forEach(([u,l],f)=>{t[e+f]?.put(n,u,C),t[e+f]?.run(n+12,l)})}function XO(t,e,n,r,i,o){let s=o.info,a=o.tiles[o.focus];if(!s||!a)return;let c=o.shown?.id===a.key?o.shown:void 0,u=n+12,l=Math.max(12,r-12),f=[`${a.width}×${a.height}${s.ext?` ${s.ext.toUpperCase()}`:""}`,...c?[Da(c.bytes)]:[]].join(" · "),d=[s.rating??"—",a.score>0?`★${a.score}`:"",s.posted??""].filter(Boolean).join(" · "),m=(w,b)=>w.length>0?ZO(w,l,b).map((v)=>[[v,""]]):[[["—",C]]],g=[["Characters",m(s.characters,2)],["Series",m(s.series,1)],["Tags",m(s.tags,3)],["Rating",[[[d,d==="—"?C:""]]]],["File",[[[f,""],...c?[[" ",""]]:[],...c?T0(c):[]]]],["Uploader",[[s.uploader?[s.uploader,""]:["—",C]]]]],$=e;for(let[w,b]of g){if($+b.length-1>i)return;t[$]?.put(n,w,C);for(let v of b)t[$]?.run(u,v),$++}}var tN=["Size","Position","Opacity"],eN=[0,3,6];function nN(t,e){let{tune:n,untuned:r}=t;return e===0?n.size!==r.size:e===1?n.at!==r.at:n.opacity!==r.opacity}function rN(t){return t.toFixed(2)}function iN(t,e,n,r,i,o){let s=i.tuning;if(!s)return;let a=i.tiles[i.focus];t[e-3]?.run(n,[[i.palette,vt+o],[" Background",C],...a?[[" · ",C],...zi(`${a.site} ${a.id}`,C,a.page||void 0,Bi(a.siteAnsi))]:[]]);let c=Math.max(8,r-n-21),u=20,l=Math.max(100,s.fill);for(let[f,d]of tN.entries()){let m=e+eN[f],g=s.field===f,$=g?vt:C;if(g)t[m]?.put(n,"▶",o);t[m]?.put(n+2,d,$);let w;if(f===1){for(let b=1;b<=9;b++){let v=b===i.tune.at;t[e+2+Math.floor((b-1)/3)]?.put(n+12+(b-1)%3*3,v?"■":"·",v?vt+o:C)}w=Xt[i.tune.at-1]??"center"}else{let b;if(f===0){let{size:v}=i.tune;b=v==="fill"?c-1:Math.floor((v-u)*(c-1)/(l-u+1)),w=v==="fill"?"fill":`${v}%`}else b=Math.floor(Math.round(i.tune.opacity*100)*(c-1)/100),w=rN(i.tune.opacity);b=Math.max(0,Math.min(c-1,b)),t[m]?.run(n+12,[["━".repeat(b),o],["●",vt],["─".repeat(c-1-b),C]])}if(t[m]?.right(r-2,[[w,$]]),nN(i,f))t[m]?.put(r-1,"↺",g?vt+o:C)}}function oN(t,e,n,r,i,o){t[e]?.put(n,`╭${"─".repeat(i-2)}╮`,o);for(let s=e+1;s<e+r-1;s++)t[s]?.put(n,"│",o),t[s]?.put(n+i-1,"│",o);t[e+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,o)}function Yf(t,e=t.site,n=t.siteAnsi){return[` ${e} `,`\x1B[7;${30+n}m`]}function ss(t){return`${q[Math.floor(t/Ln)]?.name??"local"} ${t%Ln}`}function os(t,e,n){let r=q[Math.floor(e/Ln)],i=ss(e),o=t.indexOf(i);if(!r||o===-1)return[[t,n]];return[[t.slice(0,o),n],...zi(i,n,r.pageUrl(e%Ln),Bi(r.ansi)),[t.slice(o+i.length),n]].filter(([a])=>a!=="")}function sN(t,e,n){let r=[{name:"all",moved:!1},...q].flatMap((o,s)=>{let a=`${o.name}${o.moved?"*":""}`,c=o.name===n.site?Yf(n,a):[` ${a} `,C];return s?[[" ",""],c]:[c]}),i=r.reduce((o,[s])=>o+st(s),0)<=e;t.run(0,i?r:[Yf(n)])}function aN(t,e,n,r){if(n.chips.length===0)return;let i=[["tags ",C]],o=st("tags "),s=n.chips.length;for(let[a,c]of n.chips.entries()){let u=` ${a+1} ${c.name} `;if(o+st(u)+1>e-2)break;i.push([u,c.on?`\x1B[7m${r}`:C],[" ",""]),o+=st(u)+1,s--}if(s>0)i.push([`+${s}`,C]);t.run(0,i)}function cN(t,e,n,r){if(n.editing!==void 0){let c=t.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),u=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,n.editing?u:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,C);return}let i=t.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":C]]),o=Sr.filter((c)=>!n.block.includes(c)),s=q.filter((c)=>!n.enabled.includes(c.name)).map((c)=>c.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...o.length>0?[`allows ${o.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("+")}`]:[],...s.length>0?[`all skips ${s.join("+")}`]:[]];if(t.put(i,` ${a.join(" ")}`,C),n.total>0||!n.searching){let c=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)c.push([` of ${n.total}`,C]);t.right(e,c)}}function T0(t){if(t.cut==="on")return[[`Cut out · ${t.clear}% transparent`,as]];if(t.cut==="off")return[["Opaque · x cuts out",Ve]];if(t.cut==="failed")return[["Opaque · no cut-out",Ve]];return[t.clear>0?[`${t.clear}% transparent`,as]:["Opaque",Ve]]}function E0(t){return t.site==="all"?"any site":t.site}function Df(t,e){if(t.installing!==void 0)return os(`${_i(t)} Installing ${t.palette} ← ${ss(t.installing)}`,t.installing,Ve);if(t.hint)return[[t.hint,as]];if(t.error)return[[t.error,Ve]];if(t.waiting!==void 0)return[[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Ve]];if(t.fetching){let{id:n,got:r,size:i}=t.fetching;return os(`${_i(t)} Fetching ${ss(n)} · ${Va(r,i)}`,n,Ve)}if(t.cutting!==void 0)return os(`${_i(t)} Cutting out ${ss(t.cutting)}`,t.cutting,Ve);if(t.preparing!==void 0)return os(`${_i(t)} Preparing ${ss(t.preparing)}`,t.preparing,Ve);if(e)return[e];if(t.saved)return os(t.saved.text,t.saved.key,as);if(t.note)return[[t.note,C]];return}function A0(t){if(t.ranking)return"Ranking previews by palette colors";if(t.stage==="check")return t.preset==="cutouts"?"Checking PNG headers":"Loading previews";return"Fetching posts"}function C0(t,e){return t.ranking?`${e}${t.ranking.done}/${t.ranking.total}`:""}function uN(t,e,n,r,i){let{background:o,cursor:s,selection:a}=r.colors,{ranking:c}=r,u=c?Math.round(n*c.done/c.total):-1,l=Math.max(6,Math.round(n*0.22)),f=gc(r)%(w0*2)/w0,d=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(f<1?f:2-f)))),m=Ht(o,s,i),g=Ht(o,Ht(a,o,0.15),i),$=Array.from({length:n},(b,v)=>{let R=(u>=0?v<u:v>=d&&v<d+l)?m:g;return v===0||v===n-1?Ht(R,o,0.55):R}),w=0;for(let b=1;b<=n;b++)if(b===n||$[b]!==$[w])t?.put(e+w," ".repeat(b-w),hc($[w])),w=b}function lN(t,e,n,r,i){let{background:o,foreground:s}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(gc(i)-i.loaderFrom)/_O),c=e+(n>=5?Math.floor((n-5)/2):0);t[c]?.center(r,[[A0(i),vt+Wi(Ht(o,s,a))],[C0(i," "),Wi(Ht(o,Ht(s,o,0.45),a))]]);let u=Math.min(WO,r-8);if(uN(t[c+(n>=3?2:1)],Math.floor((r-u)/2),u,i,a),n<5)return;t[c+4]?.center(r,i.sites.flatMap(({name:l,arrived:f},d)=>[...d?[[" · ",Wi(Ht(o,s,0.25*a))]]:[],[l,Wi(Ht(o,f?Ht(s,o,0.2):s,f?a:0.32*a))]]))}function fN(t,e,n,r,i,o){if(i<=r)return;let s=Math.max(1,Math.round(r*r/i)),a=Math.max(0,Math.min(r-s,Math.round(n.scroll*r/i)));for(let c=0;c<r;c++){let u=c>=a&&c<a+s;t[He+c]?.put(e-1,u?"┃":"│",u?o:C)}}function dN(t,e,n){if(e)return[`${_i(t)} ${A0(t)}${C0(t," · ")}`,C];let r=n.filter((o)=>!o.missing),i=r.filter((o)=>o.thumb).length;return i<r.length?[`${_i(t)} Loading thumbnails · ${i}/${r.length}`,C]:void 0}function hN(t,e,n,r,i,o){let{perRow:s,rowsVis:a,height:c}=cr(n,r);cN(t[0],n,i,o),sN(t[1],n,i),aN(t[2],n,i,o);let u=t.map((O,F)=>F>=He&&F<He+c?O:void 0),l=Math.floor(i.scroll/gt.height),f=Math.floor((i.scroll+c-1)/gt.height),d=[];for(let O=l;O<=f;O++){let F=He+O*gt.height-i.scroll;for(let j=0;j<s;j++){let W=O*s+j,D=j*gt.pitch,_=i.tiles[W];if(!_)continue;d.push(_);let ge=W===i.focus;if(ge)oN(u,F,D,gt.height,gt.pitch-1,o);let z=F+1,ht=Math.max(z,He),V=Math.min(z+gt.rows,He+c);if(_.thumb&&V>ht)e.push({id:_.key,path:_.thumb,row:ht,col:D+1,cols:gt.cols,rows:V-ht,...V-ht<gt.rows?{crop:ht-z}:{},z:-1});let $n=[...i.installed.includes(_.key)?[["✓ ",as]]:[],..._.page||i.site!=="all"?zi(String(_.id),ge?vt:"",_.page||void 0,Bi(_.siteAnsi)):[["● ",Bi(_.siteAnsi)],[String(_.id),ge?vt:""]],[" ",""],L0(_)],qr=gt.cols-(_.mates.length>0?1:0);if(u[F+10]?.run(D+1,Jf($n)>qr?$n.map(([dr,Ms,Is])=>[dr.replace(/^(\S) $/,"$1"),Ms,Is]):$n),_.mates.length>0)u[F+10]?.put(D+gt.cols,"≈",o);u[F+11]?.put(D+1,_.artist?JO(_.artist).slice(0,gt.cols-8):"—",C);let Fe=[];if(_.score>0)Fe.push([`★${_.score}`,C]);if(_.variants>1)Fe.push([` ×${_.variants}`,o]);if(Fe.length>0)u[F+11]?.right(D+gt.cols+1,Fe)}}let m=Math.ceil(i.tiles.length/s)*gt.height;fN(t,n,i,c,m,o);let g=Math.max(He,He+m-i.scroll),$=He+c-g,w=i.searching&&$>=2;if(w)lN(u,g,$,n-1,i);let b=i.searching&&i.tiles.length===0;if(b&&!i.error){let[O,F]=$0[Math.floor(gc(i)/BO)%$0.length];t[r-2]?.run(0,[["Tip ",C],[O,vt],[` ${F}`,C]])}let v=i.top*s,R=i.tiles.length-(i.top+a)*s,S=[...v>0?[`↑ ${v} above`]:[],...R>0?[`↓ ${R} more`]:[]];if(S.length>0)t[r-2]?.put(0,S.join(" "),C);if(!i.searching&&i.tiles.length===0&&!i.error&&i.tag)t[He+1]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${E0(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${E0(i)} — tab tries ${i.nextSite}`,C);let I=dN(i,w,d),P=Df(i,I);return cs(t[r-1],n,o,{badge:"IMAGE SEARCH",lead:P,keys:b&&P?.[0]===I?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),w}function mN(t,e,n,r,i,o){let s=i.tiles[i.focus];if(!s)return;let a=i.shown?.id===s.key?i.shown:void 0,c=[Yf(i,s.site,s.siteAnsi),[" ",""],...zi(String(s.id),vt,s.page||void 0,Bi(s.siteAnsi)),[" ",""],L0(s)];if(s.score>0)c.push([` · ★${s.score}`,C]);if(a)c.push([` · ${Da(a.bytes)}`,C]);if(a){if(c.push([" ",""],...T0(a)),i.coloring==="original")c.push([" · own colors",C])}if(t[0]?.run(0,c),s.mates.length>0)t[0]?.right(n,[["≈ ",o],[s.mates.join(" "),C]]);if(QO(t,1,2,i,o),i.tuning)iN(t,8,2,2+Math.min(n-4,60),i,o);else if(i.details)XO(t,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else VO(t,7,2,n-4,r-2,i,o);if(i.shown)e.push({id:jO+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:GO});if(i.tuning){cs(t[r-1],n,o,{badge:"IMAGE EDIT",lead:Df(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["c","colors"],["enter","keep"]],right:["esc","undo"]});return}let u=Df(i);cs(t[r-1],n,o,{badge:"IMAGE PREVIEW",lead:u,keys:i.installing===void 0?[["←→","browse"],["enter","install"],["t","tune"],["c","colors"],["i","details"],...i.details?[]:[["⇧←→","example"]],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var gN=[["Field","↑↓ size, position, opacity"],["Step","←→ · ⇧←→ ×10"],["Place","1-9 the nine positions"],["Reset","= this field back to its default · + every field"],["Colors","c the palette's tone or its own colors, opacity back to its default"],["Keep","enter back to try, installed with the picture"],["Undo","esc"],["Close","? esc"]],pN={grid:[["Move","←↑↓→ j k home end pgup pgdn"],["Try on","enter"],["Site",`tab shift+tab all, ${q.map((t)=>t.name).join(", ")}`],["Posts","c cutouts or every post"],["Search","/ a tag, a post URL or an id"],["Tags","1-9 turn a tag of the tags row on or off — the palette's own, then danbooru's related characters"],["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"],["Tune","t size, position and opacity, installed with the picture"],["Colors","c the palette's tone or its own colors, installed with the picture"],["Details","i characters, series, tags, rating and file, under Post, Source and Artist"],["Example",`⇧←→ ${he.map((t)=>t.name.toLowerCase()).join(", ")}`],["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"]]},Qf=6,bN=24;function us(t){return[...t.settings.flatMap((e,n)=>Boolean(e.advanced)===t.advanced?[n]:[]),t.settings.length]}function wN(t){return t.replace(/^[A-Z](?=[a-z])/,(e)=>e.toLowerCase())}function S0(t){let e=t.settings.filter((n)=>Boolean(n.advanced)!==t.advanced).map((n)=>wN(n.label));return`${t.advanced?"Back to":"More filters:"} ${e.join(", ")} — enter opens the page, or a from any row`}function j0(t,e,n){let r=t.indexOf(e);if(r!==-1)return t[(r+n+t.length)%t.length];let i=Number(e)||0;return(n>0?t.find((s)=>(Number(s)||0)>i):[...t].reverse().find((s)=>(Number(s)||0)<i))??t[n>0?0:t.length-1]}function Ur(t,e){let n=[],r="";for(let i of t.split(" "))if(r&&st(r)+1+st(i)>e)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function $N(t){if(t.entry!=="number"||t.choices.includes(t.value))return t.choices;let e=t.choices.findIndex((n)=>(Number(n)||0)>Number(t.value));return e===-1?[...t.choices,t.value]:[...t.choices.slice(0,e),t.value,...t.choices.slice(e)]}function kN(t,e,n,r){let i=`\x1B[7;${30+r}m`,o=e&&n!==void 0;if(t.entry==="text")return[{text:` ${o?`${n}█`:t.value||"none"} `,sgr:o||e&&t.value?i:t.value?"":C}];let s=o?[]:t.value.split(" "),a=(o?t.choices:$N(t)).map((c,u)=>{let l=s.includes(c),f=t.multi&&e&&u===t.cursor?"4;":"";return{text:t.multi?` ${l?"[x]":"[ ]"} ${c} `:` ${c} `,sgr:l?e?`\x1B[${f}7;${30+r}m`:"":f?`\x1B[4m${C}`:C}});return o?[...a,{text:` ${n}█ `,sgr:i}]:a}function M0(t){if(t.entry==="text")return[{text:" ".repeat(bN),sgr:""}];let e=t.choices.map((n)=>({text:t.multi?` [x] ${n} `:` ${n} `,sgr:""}));return t.entry==="number"?[...e,{text:` ${"0".repeat(Qf)}█ `,sgr:""}]:e}function yN(t){return t.reduce((e,n)=>e+st(n.text)+1,0)-1}function I0(t,e){let n=[[]],r=0;for(let i of t){let o=st(i.text)>e?{...i,text:` …${Array.from(i.text).slice(-(e-2)).join("")}`}:i;if(r>0&&r+st(o.text)>e)n.push([]),r=0;n[n.length-1]?.push(o),r+=st(o.text)+1}return n}function O0(t){if(t.multi&&t.choices.every((e)=>t.default.split(" ").includes(e)))return"Default all";return`Default ${t.default&&t.default!==t.multi?.none?t.default:"none"}`}function N0(t){if(!t.tag)return"";if(!t.counts)return`${t.tag}: counting…`;let e=t.counts.map(({site:n,count:r})=>`${n} ${r===void 0?"no count":r.toLocaleString("en-US")}`);return`${t.tag}: ${e.join(" · ")}`}function vN(t,e){let n=t.advanced?"basic":"advanced";if(!e)return{keys:[["↑↓","setting"],["enter",n],["s","save"]],right:["esc","undo"]};if(t.typing!==void 0)return{keys:[["⌫","erase"],["enter","done"]],right:["esc","cancel"]};if(e.entry)return{keys:[["↑↓","setting"],...e.entry==="number"?[["←→","step"]]:[],["a",n],["enter","type"],["s","save"]],right:["esc","undo"]};return{keys:[["↑↓","setting"],["←→","value"],["a",n],...e.multi?[["space","toggle"]]:[],["enter","save"]],right:["esc","undo"]}}function EN(t,e,n,r,i){let o=r.panel??0,s=r.settings.length,c=6+Math.max(...r.settings.map((z)=>st(z.label))),u=Math.max(...r.settings.map((z)=>st(O0(z)))),l=c+Math.max(...r.settings.map((z)=>yN(M0(z))))+u+5,f=Math.min(e-2,Math.max(48,l)),d=f-c-u-5,m=f-7,g=[!1,!0].map((z)=>({advanced:z,rows:us({settings:r.settings,advanced:z}).slice(0,-1)})),$=r.settings.map((z)=>I0(M0(z),d).length),w=Math.max(...g.map((z)=>z.rows.reduce((ht,V)=>ht+$[V],0))),b=Math.max(...g.map((z)=>Ur(S0({settings:r.settings,advanced:z.advanced}),m).length),...r.settings.map((z)=>Ur(z.about,m).length)),v=`${r.tag}: ${q.map((z)=>`${z.name} 0,000,000`).join(" · ")}`,R=r.tag?Math.max(Ur(v,m).length,Ur(N0(r),m).length):0,S=w+b+R+8,I=Math.floor((e-f)/2),P=Math.max(1,Math.floor((n-1-S)/2)),O=`\x1B[7;${30+r.siteAnsi}m`;t[P]?.put(I,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let z=P+1;z<P+S-1;z++)t[z]?.put(I,`│${" ".repeat(f-2)}│`);let F=P+2;for(let z of us(r).slice(0,-1)){let ht=r.settings[z],V=z===o;if(V)t[F]?.put(I+2,"▶",i);if(t[F]?.put(I+4,ht.label,V?vt:""),ht.value!==ht.default)t[F]?.right(I+f-3,[[O0(ht),C]]);I0(kN(ht,V,r.typing,r.siteAnsi),d).forEach(($n,qr)=>{let Fe=I+c;for(let dr of $n)Fe=t[F+qr].put(Fe,dr.text,dr.sgr)+1}),F+=$[z]}let j=g.find((z)=>z.advanced!==r.advanced)?.rows??[],W=t[P+3+w];if(o===s)W.put(I+2,"▶",i);let D=W.put(I+3,r.advanced?" ‹ Basic ":" Advanced › ",o===s?O:vt);if(j.some((z)=>r.settings[z]?.value!==r.settings[z]?.default))W.put(D+1,"•",C);t[P+5+w]?.put(I+2,"─".repeat(f-4),C),Ur(r.settings[o]?.about??S0(r),m).forEach((z,ht)=>{t[P+6+w+ht]?.put(I+4,z)}),Ur(N0(r),m).forEach((z,ht)=>{t[P+6+w+b+ht]?.put(I+4,z,C)}),t[P+S-1]?.put(I,`╰${"─".repeat(f-2)}╯`);let{keys:_,right:ge}=vN(r,r.settings[o]);cs(t[n-1],e,i,{keys:_,right:ge})}function SN(t,e,n,r,i){let o=r.tuning?gN:pN[r.mode],s=Math.min(e-2,Math.max(50,...o.map(([,d])=>st(d)+16))),a=o.map(([d,m])=>({label:d,parts:Ur(m,s-16)})),c=a.reduce((d,{parts:m})=>d+m.length,0)+4,u=Math.floor((e-s)/2),l=Math.max(2,Math.floor((n-c)/2));t[l]?.put(u,`╭─ Help ${"─".repeat(s-9)}╮`);for(let d=l+1;d<l+c-1;d++)t[d]?.put(u,`│${" ".repeat(s-2)}│`);let f=l+2;for(let{label:d,parts:m}of a){t[f]?.put(u+3,d,vt);for(let g of m)t[f]?.put(u+13,g),f++}t[l+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),cs(t[n-1],e,i,{badge:"HELP",right:["? esc","close"]})}function MN(t,e,n){let r=e.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),o=Math.max(...r.map((a)=>st(a.value))),s=Math.max(7,...i.map(st));r.forEach((a,c)=>{let u=c===e.pick,l=t[1+c];l?.run(0,[[u?"▸ ":" ",n],[a.value,u?vt+n:""]]),l?.right(2+o+2+s,[[i[c],C]])})}function Xf(t,e,n){let r=Array.from({length:n},()=>new dc(e)),i=[],o=Wi(t.colors.cursor);if(qf=!1,e<Wr.cols||n<Wr.rows)return r[0]?.put(0,"ttheme find",vt+o),r[1]?.put(0,`Needs ${Wr.cols}×${Wr.rows} — now ${e}×${n}`),r[2]?.put(0,"esc quits",C),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let s=!1;if(t.mode==="try")mN(r,i,e,n,t,o);else s=hN(r,i,e,n,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let a=1;a<n-1;a++)r[a]=new dc(e);return MN(r,t,o),{lines:r.map((a)=>a.render()),images:[],loader:!1,tick:!1}}if(t.help||t.panel!==void 0){let a=t.mode==="try"?i:[];for(let c=0;c<n;c++)r[c]=new dc(e);if(t.help)SN(r,e,n,t,o);else EN(r,e,n,t,o);return{lines:r.map((c)=>c.render()),images:a,loader:!1,tick:!1}}return{lines:r.map((a)=>a.render()),images:i,loader:s,tick:qf}}var td=5,IN=6,G0=0.05,ON=[1,2,3,4,5,6,9,10,11,12,13,14],U0=(t,e)=>(e-t+360)%360<=180?1:-1;function ls(t,e,n){let r=e*Math.cos(n*Math.PI/180),i=e*Math.sin(n*Math.PI/180),o=[t+0.3963377774*r+0.2158037573*i,t-0.1055613458*r-0.0638541728*i,t-0.0894841775*r-1.291485548*i].map((l)=>l**3),[s,a,c]=o,u=[4.0767416621*s-3.3077115913*a+0.2309699292*c,-1.2684380046*s+2.6097574011*a-0.3413193965*c,-0.0041960863*s-0.7034186147*a+1.707614701*c];if(u.some((l)=>l<-0.0001||l>1.0001))return;return u.map((l)=>{let f=Math.min(1,Math.max(0,l));return Math.round(255*(f<=0.0031308?12.92*f:1.055*f**0.4166666666666667-0.055))})}function me(t,e,n){let r=0,i=e;if(ls(t,e,n)===void 0)for(let s=0;s<24;s++){let a=(r+i)/2;if(ls(t,a,n)===void 0)i=a;else r=a}else r=e;return`#${(ls(t,r,n)??[0,0,0]).map((s)=>s.toString(16).padStart(2,"0")).join("")}`}function NN(t,e){let{l:n,c:r}=dt(t);return me(n,r,(e+360)%360)}function RN(t,e,n){let{l:r,c:i,h:o}=dt(t),s=yt(e)<0.18,a=(l)=>me(s?r+(1-r)*l:r*(1-l),i,o);if(pt(a(1),e)<n+G0)return a(1);let c=0,u=1;for(let l=0;l<30;l++){let f=(c+u)/2;if(pt(a(f),e)>=n+G0)u=f;else c=f}return a(u)}function PN(t,e){let{l:n,c:r,h:i}=dt(t),o=0,s=n;for(let a=0;a<30;a++){let c=(o+s)/2;if(yt(me(c,r,i))<=e-0.005)o=c;else s=c}return me(o,r,i)}function HN(t,e,n){let r=on[e],[i,o]=[dt(t[e]),dt(t[e+8])],s=(l,f)=>n.has(l)?[f]:Array.from({length:2*r.width+1},(d,m)=>(r.center-r.width+m+360)%360),a=(l,f,d)=>Sn.every((m)=>{let g=(l>8?8:0)+m;if(g===l)return!0;let $=dt(t[g]);return $.c<to||Le($.h,f)>=ti+1||Math.abs($.l-d)>=ei}),c,u=Number.POSITIVE_INFINITY;for(let l of s(e,i.h)){if(!n.has(e)&&!a(e,l,i.l))continue;for(let f of s(e+8,o.h)){if(Le(l,f)>we-td||!n.has(e+8)&&!a(e+8,f,o.l))continue;let d=Le(l,i.h)+Le(f,o.h);if(d<u)u=d,c=[l,f]}}return c}class W0{theme;moves=[];constructor(t){this.theme={...t,ansi:[...t.ansi]}}set(t,e,n){let r=this.get(t);if(n===r)return;if(this.moves.push({slot:t,rule:e,from:r,to:n}),t==="foreground")this.theme.foreground=n;else if(t==="selection")this.theme.selectionBackground=n;else this.theme.ansi[Number(t.slice(4))]=n}get(t){if(t==="foreground")return this.theme.foreground;if(t==="selection")return this.theme.selectionBackground;return this.theme.ansi[Number(t.slice(4))]}rehue(t,e,n){this.set(`ansi${t}`,e,NN(this.theme.ansi[t],n))}roles(){let t=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Xr(this.theme)){let i=on[Mn(n)];this.rehue(n,"ansi-role",i.center+U0(i.center,r)*(i.width-td))}for(let{normal:n,gap:r}of $r(this.theme)){if(r<=we)continue;let[i,o]=t.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],s=dt(this.theme.ansi[i]).h,a=dt(this.theme.ansi[o]).h;this.rehue(o,"bright-follows",s+U0(s,a)*(we-td))}let e=ni(this.theme);for(let[n,r]of kr(this.theme)){let i=Mn(e.has(r)?n:r),o=HN(this.theme.ansi,i,e);if(o===void 0)continue;this.rehue(i,"distinct",o[0]),this.rehue(i+8,"distinct",o[1])}}readability(){let t=new Set(this.theme.waive),{background:e}=this.theme,n=(r,i,o,s=e)=>{if(t.has(r))return;for(let a of i)if(pt(this.get(a),s)<o)this.set(a,r,RN(this.get(a),s,o))};if(n("foreground",["foreground"],7),n("accents",ON.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!t.has("ansi0-dark")&&yt(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",PN(this.get("ansi0"),0.15));n("selection",["selection"],7,this.theme.foreground)}net(){return[...new Set(this.moves.map((t)=>t.slot))].flatMap((t)=>{let e=this.moves.filter((i)=>i.slot===t),n=e[0].from,r=this.get(t);return n===r?[]:[{slot:t,rule:[...new Set(e.map((i)=>i.rule))].join(", "),from:n,to:r}]})}}function pc(t){let e=new W0(t);for(let n=0;n<IN;n++)if(e.readability(),e.roles(),yr(e.theme).length===0)break;return{theme:e.theme,moves:e.net(),left:yr(e.theme)}}var fs=[{key:"background",label:"Background",min:0,max:0.5,step:0.01,digits:2},{key:"foreground",label:"Foreground",min:0.5,max:1,step:0.01,digits:2},{key:"hue",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0},{key:"tint",label:"Tint",min:0,max:0.1,step:0.005,digits:3},{key:"lightness",label:"Accent lightness",min:0.4,max:0.95,step:0.01,digits:2},{key:"chroma",label:"Accent chroma",min:0,max:0.3,step:0.005,digits:3},{key:"brights",label:"Brights",min:-0.2,max:0.2,step:0.01,digits:2}],bc={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},_0=(t,e,n)=>Math.min(n,Math.max(e,t));function B0(t,e,n){let r=t[e.key]+e.step*n,i=e.wraps?(r%e.max+e.max)%e.max:_0(r,e.min,e.max);return{...t,[e.key]:Math.round(i*1e4)/1e4}}function _r(t){let e=(r,i,o)=>me(_0(r,0,1),i,o),n=Array.from({length:16},()=>"#000000");n[0]=e(t.background+0.06,t.tint,t.hue),n[8]=e(t.background+0.25,t.tint,t.hue),n[7]=e(t.foreground-0.06,t.tint/2,t.hue),n[15]=e(t.foreground+0.06,t.tint/2,t.hue);for(let r of Sn){let i=on[r].center;n[r]=e(t.lightness,t.chroma,i),n[r+8]=e(t.lightness+t.brights,t.chroma,i)}return{background:e(t.background,t.tint,t.hue),foreground:e(t.foreground,t.tint/2,t.hue),cursor:e(t.lightness+t.brights,Math.max(t.chroma,0.08),t.hue),selection:e(t.background+0.1,t.tint*2,t.hue),ansi:n}}var qi=["background","foreground","cursor","selection",...Array.from({length:16},(t,e)=>`ansi${e}`)],Kt=["Background","Foreground","Cursor","Selection"],kc=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],Ki=Kt.length+kc.length,ur=[{key:"l",label:"Lightness",min:0,max:1,step:0.01,digits:2},{key:"c",label:"Chroma",min:0,max:0.37,step:0.005,digits:3},{key:"h",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0}],z0=5;function FN(t){let e=t.trim();return/^https?:\/\/\S+$/i.test(e)||Ui(e).length>0}function ds(t){return[t.background,t.foreground,t.cursor,t.selection,...t.ansi]}function wn(t){let[e,n,r,i,...o]=t;return{background:e,foreground:n,cursor:r,selection:i,ansi:o}}function hs(t){if(t<Kt.length)return{name:Kt[t],about:qi[t]};let e=t-Kt.length,n=kc[e%8];return e<8?{name:n,about:`ansi ${e}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${e}`}}var wc=(t,e,n)=>Math.min(n,Math.max(e,t));function xN(t){return wc(Math.round(t),0,255).toString(16).padStart(2,"0")}function K0(t){let e=t.trim().toLowerCase(),n=/^#?([0-9a-f]{6}|[0-9a-f]{3})$/.exec(e);if(n){let o=n[1];return`#${o.length===3?[...o].map((s)=>s+s).join(""):o}`}let r=/^rgb\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)\s*\)$/.exec(e);if(r)return`#${r.slice(1,4).map((o)=>xN(Number(o))).join("")}`;let i=/^oklch\(\s*([\d.]+)(%?)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:deg|°)?\s*\)$/.exec(e);if(i){let o=Number(i[1])/(i[2]?100:1);return me(wc(o,0,1),Number(i[3]),Number(i[4])%360)}return}function $c(t){let e=Dt.find((n)=>n.rule===t);return e?.min??e?.max??0}function ms(t,e,n){let r=wn(t);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:e}}function LN(t,e,n){let r=ms(t,e,n),i=(f)=>!n.includes(f),{background:o,foreground:s,selection:a,ansi:c}=wn(t),u=new Set,l=(f,d,m,g)=>{if(i(g)&&pt(d,m)<$c(g))u.add(f)};l(1,s,o,"foreground"),l(3,s,a,"selection");for(let f of[1,2,3,4,5,6,9,10,11,12,13,14])l(4+f,c[f],o,"accents");for(let f of[7,15])l(4+f,c[f],o,"light-ansi");if(l(12,c[8],o,"ansi8-visible"),i("ansi0-dark")&&yt(c[0])>$c("ansi0-dark"))u.add(4);if(i("ansi-role"))for(let{slot:f}of Xr(r))u.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of $r(r))if(d>we)u.add(4+f+8)}if(i("distinct"))for(let[f,d]of kr(r))u.add(4+f).add(4+d);return u}function bn(t,e,n,r,i){let o=pt(t,e),s=$c(n);if(i.includes(n))return{ok:void 0,text:`${r} ${o.toFixed(2)}:1 · waived`};return{ok:o>=s,text:`${r} ${o.toFixed(2)}:1 · ≥ ${s}`}}function ed(t,e,n,r){let i=wn(t),o=ms(t,e,n);if(r===0){let b=[1,2,3,4,5,6,9,10,11,12,13,14].reduce((v,R)=>pt(i.ansi[v],i.background)<=pt(i.ansi[R],i.background)?v:R);return[bn(i.foreground,i.background,"foreground","Foreground on it",n),bn(i.ansi[b],i.background,"accents",`Weakest, ANSI ${b},`,n),bn(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[bn(i.foreground,i.background,"foreground","On background",n),bn(i.foreground,i.selection,"selection","On the selection",n)];if(r===2)return[{ok:void 0,text:`On background ${pt(i.cursor,i.background).toFixed(2)}:1`}];if(r===3)return[bn(i.foreground,i.selection,"selection","Foreground on it",n)];let s=r-Kt.length,a=i.ansi[s];if(s===0){let w=yt(a),b=$c("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${w.toFixed(3)} · waived`}:{ok:w<=b,text:`Luminance ${w.toFixed(3)} · ≤ ${b}`}]}if(s===7||s===15)return[bn(a,i.background,"light-ansi","On background",n)];if(s===8)return[bn(a,i.background,"ansi8-visible","On background",n)];let c=[bn(a,i.background,"accents","On background",n)],u=dt(a),l=Mn(s),f=on[l],d=`${f.name} ${f.center}±${f.width}°`;if(u.c<to)c.push({ok:void 0,text:"Too grey to have a hue"});else if(ni(o).has(s))c.push({ok:void 0,text:`Hue ${u.h.toFixed(0)}° · a signature, free of ${d}`});else if(n.includes("ansi-role"))c.push({ok:void 0,text:`Hue ${u.h.toFixed(0)}° · ${d} waived`});else{let w=Le(u.h,f.center)-f.width;c.push(w>0?{ok:!1,text:`Hue ${u.h.toFixed(0)}° · ${w.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${u.h.toFixed(0)}° · in ${d}`})}let m=s<8?s+8:s-8,g=$r(o).find((w)=>w.normal===l);if(g)c.push(n.includes("bright-follows")?{ok:void 0,text:`${g.gap.toFixed(0)}° from ANSI ${m} · waived`}:{ok:g.gap<=we,text:`${g.gap.toFixed(0)}° from ANSI ${m} · ≤ ${we}°`});let $=kr(o).flatMap(([w,b])=>w===s?[b]:b===s?[w]:[]);if($.length>0&&!n.includes("distinct"))c.push({ok:!1,text:`Reads as ANSI ${$.join(", ")} · within ${ti}° and ${ei} lightness`});return c}function q0(t,e,n){let r=Te(ms(t,e,n));return Dt.map((i,o)=>{let s=r[o],a=n.includes(i.rule);return{ok:a||Number.isNaN(s)?void 0:(i.min===void 0||s>=i.min)&&(i.max===void 0||s<=i.max),label:i.label,value:Number.isNaN(s)?"—":Number.isInteger(s)?String(s):s.toFixed(2),bound:a?"waived":i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:""}})}var TN=new Set(["reset","reset-all","hex","paste","fix","open","seeds","tune","sig","follow"]);class gs{mode;seeds=bc;field=0;list;lch;start;signature;row=0;col=0;channel=0;typing;overlay;quitting=!1;compare=!1;notice;filter="";pick=0;result;act;wants;pictures;startPictures;options;fresh;theme;original;startSignature;seeded=!1;seedsBack=!1;tuneFrom;clip;history=[];future=[];lastEdit;constructor(t){this.options=t,this.theme=t.variant==="theme",this.fresh=t.colors===void 0,this.mode=this.fresh?"seeds":"list",this.list=ds(t.colors??_r(this.seeds)),this.lch=this.list.map(dt),this.start=[...this.list],this.original=t.original?ds(t.original):[...this.list],this.signature=[...t.signature],this.startSignature=[...t.signature],this.pictures=t.pictures??0,this.startPictures=this.pictures}markSaved(){this.start=[...this.list],this.history=[],this.future=[],this.lastEdit=void 0}offDefault(t){return this.list[t]!==this.original[t]}get added(){return Math.max(0,this.pictures-this.startPictures)}found(t){this.pictures=t.count,this.notice=t.note}get waive(){return this.options.waive??[]}get tuned(){return this.tuneFrom?.hex}colors(){return wn(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<Kt.length?this.row:this.row+(this.col===1?8:0)}dirty(){return this.seeded||this.pictures!==this.startPictures||this.list.some((t,e)=>t!==this.start[e])||this.signature.join()!==this.startSignature.join()}misses(){return LN(this.list,this.signature,this.waive)}failing(){return yr(ms(this.list,this.signature,this.waive))}choices(){let t=this.filter.toLowerCase();return(this.options.palettes??[]).filter((e)=>e.name.toLowerCase().includes(t))}paste(t){if(this.notice=void 0,this.overlay==="open"){this.filter+=t.replace(/\s+/g,"").toLowerCase(),this.pick=0;return}if(this.overlay)return;if(t.trim()===""){this.findPictures({clipboard:!0});return}if(FN(t)){this.findPictures({paste:t});return}if(this.mode==="seeds")return;let e=K0(t);if(!e){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=e,this.lch[this.slot()]=dt(e);else this.set(this.slot(),e,"paste")}press(t){if(this.notice=void 0,t==="ctrl-c"){if(this.theme)this.act="cancel";else this.result="cancelled";return}if(this.quitting){if(this.quitting=!1,t==="y"||t==="Y")this.result="cancelled";return}if(this.typing!==void 0){this.type(t);return}if(this.overlay==="keys"){this.overlay=void 0;return}if(this.overlay==="open"){this.openKey(t);return}if(t==="?"){this.overlay="keys";return}if(this.theme&&(t==="ctrl-v"||t==="alt-v"||t==="p"))return;if(t==="ctrl-v"||t==="alt-v"){this.findPictures({clipboard:!0});return}if(t==="p"&&this.mode!=="tune"){this.findPictures();return}if(t===" "&&this.mode!=="seeds"){this.compare=!this.compare;return}if(this.compare&&t==="esc"){this.compare=!1;return}let e=t==="j"?"down":t==="k"?"up":t;if(this.mode==="seeds")this.seedKey(e);else if(this.mode==="tune")this.tuneKey(e);else this.listKey(e)}seedKey(t){let e=fs.length;if(t==="up"||t==="down")this.field=(this.field+(t==="up"?e-1:1))%e;else if(t==="home"||t==="end")this.field=t==="home"?0:e-1;else if(t==="left"||t==="right"||t==="shift-left"||t==="shift-right"){let n=fs[this.field],r=(t.endsWith("left")?-1:1)*(t.startsWith("shift")?n.wraps?10:z0:1);this.seeds=B0(this.seeds,n,r),this.list=ds(_r(this.seeds)),this.lch=this.list.map(dt)}else if(t==="enter")this.leaveSeeds();else if(t==="o")this.openPalettes();else if(t==="esc")if(this.seedsBack){let n=this.history.pop();if(n)this.restore(n);this.mode="list",this.seedsBack=!1}else this.result="cancelled"}leaveSeeds(){if(this.fresh&&!this.seeded)this.start=[...this.list];this.seeded=!0,this.seedsBack=!1,this.mode="list"}findPictures(t){if(!this.options.find){this.notice="Pictures need Ghostty, iTerm2 or kitty, outside tmux";return}this.wants=t?{start:t}:{}}openPalettes(){if((this.options.palettes??[]).length>0)this.overlay="open",this.pick=0;else this.notice="No other palettes to take colors from"}themeKey(t){if(t==="s"||t==="\x13")this.act="save";else if(t==="enter")this.tune();else if(t==="esc")this.act="cancel";else if(t==="r")this.set(this.slot(),this.original[this.slot()],"reset");else if(t==="R")this.remember("reset-all"),this.list=[...this.original],this.lch=this.list.map(dt);else if(t==="*"||t==="o"||t==="?")return!0;else return!1;return!0}listKey(t){if(this.theme&&this.themeKey(t))return;if(t==="up"||t==="down"){if(this.theme&&this.row===(t==="up"?0:Ki-1))this.act=t==="up"?"above":"below";else this.row=(this.row+(t==="up"?Ki-1:1))%Ki;this.lastEdit=void 0}else if(t==="home"||t==="end")this.row=t==="home"?0:Ki-1;else if(t==="pgup"||t==="pgdn")this.row=t==="pgup"?0:Kt.length;else if(t==="left"||t==="right")this.col=t==="left"?0:1,this.lastEdit=void 0;else if(t==="tab")this.tune();else if(t==="#")this.typing="";else if(t==="c")this.clip=this.list[this.slot()],this.notice=`Copied ${this.clip}`;else if(t==="v")if(this.clip)this.set(this.slot(),this.clip,"paste");else this.notice="Nothing copied yet — c copies a slot";else if(t==="r")this.set(this.slot(),this.start[this.slot()],"reset");else if(t==="=")this.follow();else if(t==="*")this.mark();else if(t==="f")this.fix();else if(t==="s")this.remember("seeds"),this.mode="seeds",this.seedsBack=!0;else if(t==="o")this.openPalettes();else if(t==="u")this.undo();else if(t==="\x12")this.redo();else if(t==="enter"||t==="\x13")this.save();else if(t==="esc")if(this.dirty())this.quitting=!0;else this.result="cancelled"}tune(){let t=this.slot();this.remember("tune"),this.tuneFrom={hex:this.list[t],lch:this.lch[t]},this.mode="tune"}tuneKey(t){let e=ur.length;if(t==="up"||t==="down"||t==="tab"||t==="shift-tab")this.channel=(this.channel+(t==="up"||t==="shift-tab"?e-1:1))%e;else if(t==="left"||t==="right"||t==="shift-left"||t==="shift-right"){let n=ur[this.channel];this.step((t.endsWith("left")?-1:1)*(t.startsWith("shift")?n.wraps?10:z0:1))}else if(/^[0-9]$/.test(t)){let n=ur[this.channel];this.put(n.min+(n.max-n.min)*Number(t)/10)}else if(t==="#")this.typing="";else if(t==="enter"){if(this.tuneFrom&&this.list[this.slot()]===this.tuneFrom.hex)this.history.pop();this.tuneFrom=void 0,this.mode="list"}else if(t==="esc"){let n=this.slot();if(this.tuneFrom)this.list[n]=this.tuneFrom.hex,this.lch[n]=this.tuneFrom.lch,this.history.pop();this.tuneFrom=void 0,this.mode="list"}}step(t){let e=ur[this.channel],n=this.lch[this.slot()][e.key];this.put(n+e.step*t)}put(t){let e=this.slot(),n=ur[this.channel],r=n.wraps?(t%n.max+n.max)%n.max:wc(t,n.min,n.max),i={...this.lch[e],[n.key]:Math.round(r*1e4)/1e4};this.lch[e]=i,this.list[e]=me(i.l,i.c,i.h)}type(t){let e=this.typing??"";if(t==="esc")this.typing=void 0;else if(t==="enter"){let n=K0(e);if(!n){this.notice="Not a color — #rrggbb, rgb(r g b) or oklch(l c h)";return}if(this.typing=void 0,this.mode==="tune")this.list[this.slot()]=n,this.lch[this.slot()]=dt(n);else this.set(this.slot(),n,"hex")}else if(t==="backspace")this.typing=e.slice(0,-1);else if(t==="\x15")this.typing="";else if(t.length===1&&/^[0-9a-z#(),.% ]$/i.test(t)&&e.length<28)this.typing=e+t.toLowerCase()}openKey(t){let e=this.choices();if(t==="esc")this.overlay=void 0,this.filter="";else if(t==="up"||t==="down"){let n=Math.max(1,e.length);this.pick=(this.pick+(t==="up"?n-1:1))%n}else if(t==="home"||t==="end")this.pick=t==="home"?0:Math.max(0,e.length-1);else if(t==="backspace")this.filter=this.filter.slice(0,-1),this.pick=0;else if(t==="\x15")this.filter="",this.pick=0;else if(t==="enter"){let n=e[this.pick];if(!n)return;if(this.remember("open"),this.list=ds(n.colors),this.lch=this.list.map(dt),this.overlay=void 0,this.filter="",this.notice=`Took the colors of ${n.name}`,this.mode==="seeds")this.leaveSeeds()}else if(t.length===1&&/^[a-z0-9@/-]$/i.test(t))this.filter+=t.toLowerCase(),this.pick=0}remember(t){if(t!==this.lastEdit||TN.has(t))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=t}set(t,e,n){if(!Bt(e)||this.list[t]===e)return;this.remember(n),this.list[t]=e,this.lch[t]=dt(e)}follow(){if(this.row<Kt.length){this.notice="= works on an ANSI row — the bright takes its normal";return}let t=this.row,e=this.row+8,n=this.lch[t],r={l:wc(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[e]=r,this.list[e]=me(r.l,r.c,r.h),this.col=1,this.notice=`${hs(e).name} follows ${hs(t).name.toLowerCase()}`}mark(){let t=qi[this.slot()];this.remember("sig"),this.signature=this.signature.includes(t)?this.signature.filter((e)=>e!==t):[...this.signature,t].slice(-3),this.notice=this.signature.length===3?`Signature: ${this.signature.join(", ")}`:`The signature needs three slots — ${this.signature.length} marked`}fix(){let t=ms(this.list,this.signature,this.waive),{theme:e,moves:n,left:r}=pc({...t,selectionBackground:t.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=yr(t).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=ds({...this.colors(),foreground:e.foreground,selection:e.selectionBackground,ansi:e.ansi});this.lch=i.map((o,s)=>o===this.list[s]?this.lch[s]:dt(o)),this.list=i,this.notice=`Moved ${n.length} ${n.length===1?"color":"colors"}${r.length===0?" — passes the gate":" closer to the gate"}`}save(){let t=this.options.check(this.edited());if(t){this.notice=t;return}this.result="saved"}undo(){let t=this.history.pop();if(!t){this.notice="Nothing to undo";return}this.future.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(t)}redo(){let t=this.future.pop();if(!t){this.notice="Nothing to redo";return}this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.restore(t)}restore(t){this.list=[...t.list],this.lch=[...t.lch],this.signature=[...t.signature],this.lastEdit=void 0}}var rd=80,id=24,ps=48,nd=11;function Y0(t){return{color:t,dim:(e)=>t?`\x1B[2m${e}\x1B[22m`:e,bold:(e)=>t?`\x1B[1m${e}\x1B[22m`:e,fg:(e)=>t?xe(e):"",bg:(e)=>t?`\x1B[48;2;${nt(e).join(";")}m`:""}}function AN(t){return yt(t)>0.35?"#000000":"#ffffff"}function od(t,e,n,r){let i=Math.max(0,Math.min(e.length-1,n));if(!t.color)return e.map((o,s)=>s===i?"●":r?"━":"─").join("");return e.map((o,s)=>{let a=o??"#000000";if(s===i)return`${t.bg(a)}${t.fg(AN(a))}●\x1B[39;49m`;return o?`${t.fg(o)}█`:`${t.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function D0(t,e,n){return Array.from({length:n},(r,i)=>{let o=e.min+(e.max-e.min)*i/(n-1),s={...t,[e.key]:o};return ls(s.l,s.c,s.h)?me(s.l,s.c,s.h):void 0})}function sd(t,e,n,r){return Math.round((t-e)/(n-e)*(r-1))}var J0={background:(t)=>t.background,foreground:(t)=>t.foreground,hue:(t)=>t.cursor,tint:(t)=>t.background,lightness:(t)=>t.ansi[4],chroma:(t)=>t.ansi[1],brights:(t)=>t.ansi[12]};function ad(t,e){return e===void 0?t.dim("·"):e?t.dim("✓"):t.bold("✗")}function V0(t,e,n,r=ps){let i=q0(e.list,e.signature,e.waive).sort((c,u)=>Number(c.ok!==!1)-Number(u.ok!==!1)),o=i.filter((c)=>c.ok===!1).length,s=` ${t.dim("Gate")} ${o===0?t.dim("passes"):t.bold(`${o} ${o===1?"miss":"misses"}`)}`,a=r-4;return[s,...i.slice(0,Math.max(0,n-1)).map((c)=>{let u=`${c.value} ${c.bound}`;return` ${ad(t,c.ok)} ${be(c.ok===!1?c.label:t.dim(c.label),t.dim(u),a-2)}`})]}function Z0(t,e,n,r=ps,i=!0){let o=e.misses(),s=wn(e.list),a=i?e.slot():-1,c=(d)=>t.color?`${t.bg(s.selection)}${t.fg(s.foreground)}${d}\x1B[39;49m`:`[${d}]`,u=(d)=>{let m=e.list[d],g=d===a,$=e.signature.includes(qi[d])?"◆":t.color?"■":" ",w=d===0?void 0:d===3?pt(s.foreground,s.selection):pt(m,s.background),b=w===void 0?"":w.toFixed(1),v=o.has(d)?"✗":e.theme&&e.offDefault(d)?"↺":" ",S=`${t.color?`${t.fg(m)}${$}${g?t.fg(s.foreground):"\x1B[39m"} `:`${$} `}${m} ${b.padStart(4)}${v}`;return g?c(` ${S} `):` ${S} `},l=(d)=>d?t.color?`${t.fg(s.cursor)}▌\x1B[39m `:"▌ ":" ",f=[` ${t.dim("Base")}`];for(let d=0;d<Kt.length;d++){let m=i&&d===e.row,g=Kt[d].padEnd(10);f.push(`${l(m)}${m?t.bold(g):g}${u(d)}`)}f.push("",` ${t.dim(`${"ANSI".padEnd(10)} Normal${" ".repeat(11)}Bright`)}`);for(let d=Kt.length;d<Ki;d++){let m=i&&d===e.row,g=kc[d-Kt.length].padEnd(10);f.push(`${l(m)}${m?t.bold(g):g}${u(d)}${u(d+8)}`)}return f.push(""),[...f,...V0(t,e,n-f.length,r)]}function CN(t,e,n){let r=wn(e.list),i=[` ${t.dim("Seeds")}`];fs.forEach((o,s)=>{let a=s===e.field,c=e.seeds[o.key],u=Array.from({length:nd},($,w)=>{let b=o.min+(o.max-o.min)*w/(nd-1);return J0[o.key](_r({...e.seeds,[o.key]:b}))}),l=od(t,u,sd(c,o.min,o.max,nd),a),f=`${c.toFixed(o.digits)}${o.wraps?"°":""}`.padStart(6),d=J0[o.key](r),m=a?t.color?`${t.fg(r.cursor)}▌\x1B[39m `:"▌ ":" ",g=o.label.padEnd(17);i.push(`${m}${a?t.bold(g):g}${l} ${f} ${t.color?`${t.fg(d)}■\x1B[39m `:""}${t.dim(d)}`)}),i.push("");for(let o of kt("Seven seeds grow all twenty colors, each accent on the hue its ANSI role reads as — whatever the seeds, they pass the gate. enter moves on to tune each slot.",ps-4))i.push(` ${t.dim(o)}`);return i.push(""),[...i,...V0(t,e,n-i.length)]}function Q0(t,e,n){let r=(f)=>t.fg(e.ansi[f]),i=t.fg(e.foreground),o=`${t.bg(e.background)}${i}`,s=(f)=>t.color?`\x1B[1m${f}\x1B[22m`:f,a=`${r(2)}❯${i} `,c=Math.max(2,Math.min(4,Math.floor((n-9)/8)));return[Array.from({length:8},(f,d)=>`${t.fg(e.ansi[d])}${t.bg(e.ansi[d+8])}${(t.color?"▀":"#").repeat(c)}${o} `).join(""),"",`${s(`${r(4)}~/code/demo`)}${i} on ${r(5)}main${r(2)} +2${r(3)} ~1${i}`,`${a}git status -sb`,`## ${r(2)}main${i}...${r(1)}origin/main${r(3)} [ahead 1]${i}`,`${r(1)} M${i} src/main.rs ${r(1)}??${i} notes.md`,`${a}git diff`,`${r(6)}@@ -12,2 +12,2 @@${i}`,`${r(1)}- let size = 12;${i}`,`${r(2)}+ let size = 14;${i}`,`${a}cargo test`,`${r(2)} ✓${i} parses config`,`${r(1)} ✗${i} renders frame ${r(8)}expected 3, received 2${i}`,`${r(11)} ⚠ 1 warning${i} ${r(12)}ℹ 2 notes${i} ${r(13)}λ${i} ${r(14)}~${i} ${r(9)}✗${i} ${r(10)}✓${i}`,`${a}ls`,`${s(`${r(4)}docs`)} ${s(`${r(4)}src`)} ${r(2)}run.sh${i} ${r(6)}link${i} Cargo.toml`,`${a}echo ${t.bg(e.selection)}selected text${o} ${t.bg(e.cursor)} ${o}`,`${r(7)}ansi 7 text${i} ${r(15)}ansi 15 text${i} ${r(8)}# ansi 8 comment${i}`].map((f)=>`${o} ${Et(f,n-2)} ${t.color?"\x1B[0m":""}`)}function jN(t,e,n,r){let i=e.slot(),o=e.list[i],s=e.lch[i],a=dt(o),c=e.start[i],{name:u,about:l}=hs(i),f=e.signature.includes(qi[i]),d=[be(`${t.bold(u)} ${t.dim(l)}`,f?t.dim("◆ signature"):"",n),""],m=t.color?`${t.fg(o)}${"█".repeat(8)}\x1B[39m `:"",g=e.typing!==void 0?`${t.bold(`${e.typing}▏`)}`:void 0,[$,w,b]=nt(o),v=g??`${t.bold(o)}${c!==o?t.dim(` was ${t.color?`${t.fg(c)}■\x1B[39m `:""}${c}`):""}`;d.push(`${m}${v}`),d.push(`${m}${t.dim(`rgb ${$} ${w} ${b}`)}`),d.push(`${m}${t.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let R=Math.max(8,Math.min(64,n-12));ur.forEach((P,O)=>{let F=e.mode==="tune"&&O===e.channel,j=s[P.key],W=`${j.toFixed(P.digits)}${P.wraps?"°":""}`.padStart(6),D=od(t,D0(s,P,R),sd(j,P.min,P.max,R),F),_=P.key.toUpperCase();d.push(`${F?t.bold(`▸${_}`):t.dim(` ${_}`)} ${D} ${F?t.bold(W):t.dim(W)}`)}),d.push("");let S=ed(e.list,e.signature,e.waive,i);if(a.c<s.c-0.005)S.push({ok:void 0,text:`Chroma held at the sRGB edge — ${a.c.toFixed(3)} of ${s.c.toFixed(3)}`});for(let P of S)kt(P.text,n-2).forEach((O,F)=>{d.push(`${F===0?ad(t,P.ok):" "} ${P.ok===!1?O:t.dim(O)}`)});let I=r-d.length-1;if(I>=3)d.push("",...Q0(t,wn(e.shown()),n).slice(0,I));return d}function GN(t,e,n,r){return[be(`${t.bold("Specimen")} ${t.dim("what the seeds grow")}`,"",n),"",...Q0(t,wn(e.list),n).slice(0,r-2)]}var UN=[["Slots","↑↓ slot · ←→ normal or bright · home end · pgup the base colors · pgdn the ANSI ones"],["Tune","tab · ↑↓ lightness, chroma or hue · ←→ step · ⇧←→ ×5, hue ×10 · 0-9 jump · enter keeps · esc undoes"],["Type","# then #rrggbb, rgb(r g b) or oklch(l c h) — a paste works too"],["Slot","c copies · v pastes · r puts it back · = the bright follows its normal · * marks it a signature color"],["Palette","f moves the colors the gate misses · o takes another palette’s colors · s goes back to the seeds"],["History","u undo · ctrl+r redo"],["Pictures","p finds one on the boorus, tried on in these colors · drop a picture on the window, or paste one, its path or its link · ctrl+v takes the clipboard’s"],["Compare","space shows the colors you started from, on the terminal too"],["Save","enter saves · esc cancels, asking first when something changed"]];function WN(t,e,n){let r=[` ${t.bold("Help")}`,""];for(let[i,o]of UN.filter(([s])=>s!=="Pictures"||e.options.find))kt(o,n-16).forEach((s,a)=>{r.push(` ${t.bold((a===0?i:"").padEnd(11))} ${s}`)});return r}function _N(t,e,n,r){let i=e.choices(),o=e.options.palettes?.length??0,s=e.filter?`${t.bold(e.filter)}▏`:t.dim("type to filter"),a=[be(` ${t.bold("Take colors from")} ${s}`,t.dim(`${i.length}/${o}`),n),""],c=r-2,u=Math.max(0,Math.min(e.pick-Math.floor(c/2),i.length-c)),l=Math.min(40,Math.max(12,...i.map((f)=>tt(f.name))));if(i.slice(u,u+c).forEach((f,d)=>{let m=u+d===e.pick,g=f.colors,$=t.color?`${t.bg(g.background)} ${[...g.ansi].map((v)=>`${t.fg(v)}■`).join("")} ${t.fg(g.foreground)}Aa \x1B[0m`:"",w=m?"▌ ":" ",b=f.name.padEnd(l);a.push(`${w}${m?t.bold(b):b} ${$}`)}),i.length===0)a.push(` ${t.dim(`No palettes match '${e.filter}'`)}`);return a}function BN(t,e,n){let r=t.fg(e.list[2]),i="",o="",s=[],a="";if(e.quitting)i="QUIT",o=e.added>0?`Discard changes and ${e.added} ${e.added===1?"picture":"pictures"}?`:"Discard changes?",s=[["y","discard"],["n","keep editing"]];else if(e.typing!==void 0)i="TYPE",o=t.dim("#rrggbb, rgb(r g b) or oklch(l c h)"),s=[["enter","set"],["ctrl+u","clear"]],a="esc back";else if(e.overlay==="keys")i="HELP",a="any key closes";else if(e.overlay==="open")i="OPEN",s=[["↑↓","palette"],["a-z","filter"],["enter","take its colors"]],a="esc close";else if(e.compare)i="BEFORE",o="The colors you started from",s=[["space","back to yours"]],a="esc back";else if(e.mode==="seeds")i="SEEDS",s=[["↑↓","seed"],["←→","step"],["⇧←→","×5"],["enter","tune slots"],["o","open a palette"],["p","picture"],["?","keys"]],a=e.fresh&&!e.dirty()?"esc cancel":"esc back";else if(e.mode==="tune")i="IMAGE EDIT",s=[["↑↓","L C H"],["←→","step"],["⇧←→","faster"],["0-9","jump"],["#","type"],["enter","keep"]],a="esc undo";else s=[["↑↓","slot"],["←→","normal or bright"],["tab","tune"],["#","type"],["f","fix"],["p","picture"],["u","undo"],["enter","save"],["?","keys"]],a="esc cancel";if(!e.options.find)s=s.filter(([l])=>l!=="p");if(e.notice)o=t.color?`\x1B[33m${e.notice}\x1B[39m`:e.notice,s=[];let c=i?t.color?`\x1B[7;1m${r} ${i} \x1B[0m `:`[${i}] `:"",u=a?`${t.bold(a.split(" ")[0])} ${t.dim(a.split(" ").slice(1).join(" "))}`:"";for(;;){let l=[o,...s.map(([d,m])=>`${t.bold(d)} ${t.dim(m)}`)].filter(Boolean),f=`${c}${l.join(" ")}`;if(tt(f)+tt(a)+3<=n||s.length<=1)return a?be(f,u,n):Et(f,n);s=[...s.slice(0,-2),...s.slice(-1)]}}var cd=50,ud=22;function X0(t){let e=t.notice??"";if(t.typing!==void 0)return{mode:"type",keys:[["enter","set"],["ctrl+u","clear"],["esc","back"]],note:e};if(t.compare)return{mode:"compare",keys:[["space","back to yours"],["esc","back"]],note:e};if(t.mode==="tune")return{mode:"tune",keys:[["↑↓","lightness, chroma, hue"],["←→","step"],["⇧←→","×5"],["0-9","jump"],["enter","keep"],["esc","undo"]],note:e};return{mode:"list",keys:[["↑↓←→","slot"],["enter","tune"],["r","reset slot"],["R","reset all"],["#","type a color"],["space","before"]],note:e}}function zN(t,e,n,r){let i=e.slot(),o=e.list[i],s=e.lch[i],a=dt(o),c=e.start[i],u=e.original[i],{name:l,about:f}=hs(i),d=e.signature.includes(qi[i]),m=t.color?`${t.fg(o)}${"█".repeat(4)}\x1B[39m `:"",g=e.typing!==void 0?t.bold(`${e.typing}▏`):void 0,$=[c!==o?`was ${t.color?`${t.fg(c)}■\x1B[39m `:""}${c}`:"",u!==o?`default ${t.color?`${t.fg(u)}■\x1B[39m `:""}${u}`:""].filter(Boolean),w=[be(`${t.bold(l)} ${t.dim(f)}`,d?t.dim("◆ signature"):"",n),`${m}${g??t.bold(o)} ${t.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`,...r>=7?[`${m}${t.dim($.length>0?$.join(" "):"as the palette has it")}`]:[]],b=Math.max(8,Math.min(40,n-12));ur.forEach((R,S)=>{let I=e.mode==="tune"&&S===e.channel,P=s[R.key],O=`${P.toFixed(R.digits)}${R.wraps?"°":""}`.padStart(6),F=od(t,D0(s,R,b),sd(P,R.min,R.max,b),I),j=R.key.toUpperCase();w.push(`${I?t.bold(`▸${j}`):t.dim(` ${j}`)} ${F} ${I?t.bold(O):t.dim(O)}`)});let v=ed(e.list,e.signature,e.waive,i);if(a.c<s.c-0.005)v.push({ok:void 0,text:`Chroma held at the sRGB edge — ${a.c.toFixed(3)} of ${s.c.toFixed(3)}`});for(let R of v)for(let[S,I]of kt(R.text,n-2).entries()){if(w.length>=r)return w;w.push(`${S===0?ad(t,R.ok):" "} ${R.ok===!1?I:t.dim(I)}`)}return w}function t$(t,e,n,r,i){let o=Y0(r),s=t.failing().length,a=s===0?"passes the gate":`${s} ${s===1?"miss":"misses"} in the gate`,c=t.list.filter((g,$)=>t.offDefault($)).length,u=be(`${i?o.bold("Palette"):o.dim("Palette")}${c>0?o.dim(` ${c} off its default`):""}`,o.dim(a),e-2),l=Z0(o,t,0,e,i).slice(1,-2),f=[` ${u}`,...l],d=t.row<Kt.length?t.row+2:t.row+4;if(n-f.length>=9)f.push("");let m=n-f.length;if(m>=5){let g=f.length;if(f.push(...zN(o,t,e-2,m).map(($)=>` ${$}`)),t.mode==="tune")d=g+3+(m>=7?1:0)+t.channel;else if(t.typing!==void 0)d=g+2}return{lines:Array.from({length:n},(g,$)=>Et(f[$]??"",e)),at:d}}function KN(t,e,n,r){let i=Y0(r);if(e<rd||n<id){let g=[i.bold("ttheme palette editor"),`Needs ${rd}×${id} — now ${e}×${n}`,i.dim("esc cancels")];return Array.from({length:n},($,w)=>Et(g[w]??"",e))}let o=t.failing().length,s=o===0?"✓ Passes the gate":`✗ ${o} ${o===1?"miss":"misses"} in the gate`,a=t.pictures>0?i.dim(`▣ ${t.pictures} ${t.pictures===1?"picture":"pictures"} `):"",c=`${t.dirty()?`${i.color?"\x1B[33m●\x1B[39m":"●"} unsaved `:""}${a}${i.dim(s)}`,l=`${i.fg(t.list[2])}◆${i.color?"\x1B[39m":""} ${i.bold(t.options.title)} ${i.dim(`· ${t.options.name}`)}`,f=n-4,d;if(t.overlay==="keys")d=WN(i,t,e);else if(t.overlay==="open")d=_N(i,t,e,f);else{let g=e-ps-2,$=t.mode==="seeds"?CN(i,t,f):Z0(i,t,f),w=t.mode==="seeds"?GN(i,t,g,f):jN(i,t,g,f);d=Array.from({length:f},(b,v)=>`${Et($[v]??"",ps)}${i.dim("│")} ${Et(w[v]??"",g)}`)}let m=[be(l,c,e),""];for(let g=0;g<f;g++)m.push(Et(d[g]??"",e));return m.push("",BN(i,t,e)),m}async function e$(t,e){let n=new gs(t),{stdin:r,stdout:i}=process,o=i.columns||rd,s=i.rows||id,a=[],c=[],u="",l="",f,d=(S)=>i.write(S),m=()=>{if(f=void 0,e.look){let I=n.shown();if(I.join(" ")!==u)u=I.join(" "),e.look(I);return}let S="";if(n.shown().forEach((I,P)=>{if(c[P]!==I&&e.only?.includes(P))S+=Il(P,I),c[P]=I}),S)d(S)},g=()=>{let S=KN(n,o,s,e.color),I="";if(S.forEach((P,O)=>{if(a[O]!==P)I+=`\x1B[${O+1};1H\x1B[0m\x1B[2K${P}`}),a=S,I)d(`\x1B[?2026h${I}\x1B[0m\x1B[?2026l`);if(e.only||e.look)f??=setTimeout(m,33)},$,w,b=!1,v=()=>{d(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${Ni}`),r.setRawMode(!0),r.resume()},R=(S)=>{if($&&w)r[S?"on":"off"]("data",$),i[S?"on":"off"]("resize",w)};v();try{return await new Promise((S)=>{let I=async(P)=>{let O=t.find;if(!O)return;b=!0,R(!1),clearTimeout(f),f=void 0;try{n.found(await O(n.edited(),P))}catch(F){n.notice=F instanceof Error?F.message:String(F)}b=!1,v(),R(!0),o=i.columns||o,s=i.rows||s,a=[],c.length=0,u="",g()};w=()=>{o=i.columns||o,s=i.rows||s,a=[],d(Ni),g()},$=(P)=>{l+=P.toString("utf8");let O=fc(l);l=O.pending;for(let j of O.events)if(j.kind==="paste")n.paste(j.text);if(O.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(O.keys)&&n.typing===void 0)n.paste(O.keys);else for(let j of mc(O.keys))if(n.press(j),n.result||n.wants)break;if(n.result){S(n.result==="saved"?n.edited():void 0);return}let F=n.wants;if(F&&!b){n.wants=void 0,I(F.start);return}g()},R(!0),g()})}finally{clearTimeout(f),R(!1),r.setRawMode(!1),r.pause(),d("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as SR}from"node:child_process";import{createHash as E$}from"node:crypto";import{existsSync as ws,mkdirSync as MR,mkdtempSync as IR,readFileSync as OR,rmSync as Ec}from"node:fs";import{homedir as NR,tmpdir as RR}from"node:os";import{dirname as PR,join as lr}from"node:path";import{pathToFileURL as h$}from"node:url";var qN=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),JN=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),YN=0.04,DN=0.1,VN=0.05,ZN=4096;function QN(t){return new Set(t.cutouts.split(/\s+/).map((e)=>e.replace(/^~/,"")).filter(Boolean))}function XN(t,e,n,r=0){let{site:i,post:o}=t,s=new Set(o.tags),a=[...QN(i)].some((l)=>s.has(l)),c=Math.min(o.width,o.height),u=o.width>0&&o.height>0?o.width/o.height/(e.w/e.h):1;return(o.solo?2:0)+([...qN].some((l)=>s.has(l))?-3:0)+([...JN].some((l)=>s.has(l))?-1.5:0)+2*Math.min(1,c/e.h)+(a?1.5:-Math.min(1.5,Math.abs(Math.log(u))))+(n>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(n):0)+2*r}function yc(t,e,n=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:XN(i,e,r.get(i.site)??0,n.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function r$(t){let e=new Map;for(let r of t)e.set(r.site,[...e.get(r.site)??[],r]);let n=[];for(let r=0;n.length<t.length;r++)for(let i of e.values()){let o=i[r];if(o)n.push(o)}return n}function ld(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function n$(t,e,n){let[r,i,o]=[ld(t),ld(e),ld(n)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),a=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),c=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*a-0.0040720468*c,1.9779984951*s-2.428592205*a+0.4505937099*c,0.0259040371*s+0.7827717662*a-0.808675766*c]}function i$(t,e){let n=e.map((s)=>n$(...nt(s))).filter(([,s,a])=>Math.hypot(s,a)>=YN);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/ZN))),i=n.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let a=0;a<t.width;a+=r){let c=(s*t.width+a)*4;if(t.data[c+3]<128)continue;o++;let[u,l,f]=n$(t.data[c],t.data[c+1],t.data[c+2]);n.forEach(([d,m,g],$)=>{if(Math.hypot(u-d,l-m,f-g)<DN)i[$]=i[$]+1})}if(o===0)return 0;return i.reduce((s,a)=>s+Math.min(1,a/o/VN),0)/n.length}import{mkdirSync as rR,readFileSync as dd,writeFileSync as u$}from"node:fs";import{dirname as iR}from"node:path";import{isMainThread as oR,parentPort as l$,Worker as sR}from"node:worker_threads";var tR=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,eR=[[/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 fd(t){let e=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...e&&t.source.includes("pximg")?[`pixiv:${e[1]}_p${e[2]}`]:[]]}function o$(t,e){let n=tR.exec(e.source)?.[1]?.toLowerCase();return[`post:${t.key}:${e.id}`,...e.md5?[`md5:${e.md5}`]:[],...n&&n!==e.md5?[`md5:${n}`]:[],...eR.flatMap(([r,i])=>{let o=r.exec(e.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...e.family?[`family:${t.key}:${e.family}`]:[]]}function s$(t,e){let n=t.owner||t.named.artist[0]||"";return n!==""&&n===(e.owner||e.named.artist[0]||"")&&t.width===e.width&&t.height===e.height}function a$(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),a=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let c=0;c<9;c++){let u=Math.floor(c*t.width/9),l=Math.max(u+1,Math.floor((c+1)*t.width/9)),f=0;for(let d=s;d<a;d++)for(let m=u;m<l;m++){let g=(d*t.width+m)*4,$=t.data[g+3]/255,w=0.299*t.data[g]+0.587*t.data[g+1]+0.114*t.data[g+2];f+=w*$+255*(1-$)}r.push(f/((l-u)*(a-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function nR(t,e){let n=BigInt(`0x${t}`)^BigInt(`0x${e}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function c$(t,e){if(t.width<=0||t.height<=0||e.width<=0||e.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(e.width/e.height)))<0.01&&nR(t.hash,e.hash)<=2}var aR={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},vc;async function cR(t){if(t.job==="redraw")return tc(t.home,t.name,t.key,t.paint,t.blur,t.aligns,t.user);if(t.job==="show"){if(vc?.from!==t.from){let s=Rn(new Uint8Array(dd(t.from)),Vt);vc={from:t.from,clear:sn(s),inked:al(s)}}let{image:r,fill:i,opacity:o}=hp(vc.inked,t.colors,t.tone,t.width,t.height,t.blur,t.tune,t.coloring);return rR(iR(t.to),{recursive:!0}),u$(t.to,je(r)),{clear:vc.clear,fill:i,opacity:o}}let e=Rn(new Uint8Array(dd(t.from)),Vt);if(t.job==="backdrop"){fa(t.home,t.colors,t.tone,e,{...t.origin,bytes:new Uint8Array(dd(t.source)),cut:t.from!==t.source},t,t.blur,t.coloring);let r=t.tune&&fe(t.home,t.colors.name).find((i)=>i.key===Wt(t.origin));if(t.tune&&r)So(X(t.home),r,t.tune,t.aligns??!0,t.user??t.home);return 0}if(t.job==="match")return{match:i$(e,t.colors),hash:a$(e)};if(t.job==="thumb")return x(t.to,je(Zm(e,t.width,t.height))),0;let n=e.data.subarray(t.y*e.width*4,(t.y+t.height)*e.width*4);return u$(t.to,je({width:e.width,height:t.height,data:n})),0}function uR(t){t.on("message",async(e)=>{try{t.postMessage({id:e.id,value:await cR(e)})}catch(n){t.postMessage({id:e.id,error:n instanceof Error?n.message:String(n)})}})}class hd{worker;next=1;waiting=new Map;send(t){let e=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(e,{ok:n,no:r}),i.ref(),i.postMessage({...t,id:e})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new sR(import.meta.filename);t.unref(),t.on("message",({id:n,value:r,error:i})=>{let o=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let e=(n)=>{if(this.worker===t)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return t.on("error",e),t.on("exit",()=>e(void 0)),this.worker=t,t}drop(t){for(let e of this.waiting.values())e.no(t);this.waiting.clear()}}class md{lines=new Map;run(t){let e=aR[t.job],n=this.lines.get(e);if(!n)n=new hd,this.lines.set(e,n);return n.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}class gd{lines;constructor(t){this.lines=Array.from({length:Math.max(1,t)},()=>new hd)}async map(t){let e=[],n=0;return await Promise.all(this.lines.map(async(r)=>{while(n<t.length){let i=n++;try{e[i]=await r.send(t[i])}catch(o){e[i]=o instanceof Error?o:Error(String(o))}}})),e}close(){for(let t of this.lines)t.close()}}if(!oR&&l$)uR(l$);import{existsSync as lR,readFileSync as fR,statSync as dR}from"node:fs";import{join as f$}from"node:path";function hR(t,e){try{return JSON.parse(fR(f$(ke(t),e),"utf8"))}catch{return{}}}function mR(t,e,n){x(f$(ke(t),e),`${JSON.stringify(n)}
522
+ `)}class pd{caches=new Map;unsaved=new Set;owners=new Map;crediting=new Map;inflight=new Map;home;catalog;entry;signal;credited;constructor(t){this.home=t.home,this.catalog=t.catalog,this.entry=t.entry,this.signal=t.signal,this.credited=t.credited}matesOf(t,e){return this.owners.get(t.key)?.get(e)??[]}async transparent(t,e){let n=this.keep(t,"probes.json"),r=n[e.id];if(r!==void 0)return r;try{let i=await go(t,e,this.signal),o=Ir(t,e),s=(i===void 0?await Lg(o.site,o.url,this.signal):i)?.alpha===!0;return n[e.id]=s,this.unsaved.add(`${t.key}/probes.json`),s}catch{return!1}}save(){for(let t of this.unsaved){let[e,n]=t.split("/"),r=q.find((i)=>i.key===e);if(r)mR(r,n,this.keep(r,n))}this.unsaved.clear()}owned(t,e,n){this.keep(t,"owners.json")[e]=n,this.unsaved.add(`${t.key}/owners.json`)}credit(t,e){let{site:n,post:r}=t;if(!ta(n,r))return Promise.resolve();let i=Zt(n,r.id),o=this.crediting.get(i);if(!o)o=this.credits(t,e).finally(()=>this.crediting.delete(i)),this.crediting.set(i,o);return o}async mateOwners(t){let e=this.owners.get(t.key);if(e)return e;let n=yp(this.home),r=this.keep(t,"owners.json"),i=this.catalog.palettes.flatMap((c)=>{let u=n.get(c.name);return c.group===this.entry.group&&c.name!==this.entry.name&&u?.site===t.key?[{name:c.name,id:u.id}]:[]}),o=await Promise.all(i.map(async(c)=>{let u=r[c.id];if(u!==void 0)return{...c,owner:u};try{return{...c,owner:(await fi(t,c.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let c of o)if(c)r[c.id]=c.owner,s.set(c.name,c.owner);this.unsaved.add(`${t.key}/owners.json`);let a=Ng(s);return this.owners.set(t.key,a),a}async cached(t,e,n,r){if(lR(e))return dR(e).size;let i=this.inflight.get(e);if(i)return i;let o=(async()=>{let s=await ra(t,n,this.signal,r);return x(e,s),s.length})();this.inflight.set(e,o);try{return await o}finally{this.inflight.delete(e)}}keep(t,e){let n=`${t.key}/${e}`,r=this.caches.get(n);if(!r)r=hR(t,e),this.caches.set(n,r);return r}async credits({site:t,post:e},n){let r=this.keep(t,"credits.json"),i=r[e.id];if(!i){try{i=await Xs(t,e.id,n)}catch{return}if(!i?.owner)return;r[e.id]=i,this.unsaved.add(`${t.key}/credits.json`)}mo(e,i),this.credited()}}import{rmSync as gR}from"node:fs";import{join as pR}from"node:path";var Ji=2147483645,bs=2147483646,d$=-1073741827,bR=-1073741828,wR=80,$R=16,kR=0.4,yR=3221225472,vR=256;function ER(t){let e=/^(\d+) (\d+)$/.exec(t??"");return e&&(Number(e[1])>0||Number(e[2])>0)?{x:Number(e[1]),y:Number(e[2])}:void 0}var bd=ER(process.env.TTHEME_BG_MARGIN);class wd{screen=[];dirty=!1;ticking;gliding;sent=new Map;placed=new Map;covered="";bands=hb(process.env);files=mb(process.env);moves=pb(process.env);layers=gb(process.env);bandFiles=new Map;nextBand=yR;view;grid;background;renders;scratch;signal;write;constructor(t){this.view=t.view,this.grid=t.grid,this.background=t.background,this.renders=t.renders,this.scratch=t.scratch,this.signal=t.signal,this.write=t.write}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let{cols:t,rows:e,cell:n}=this.grid(),r=Xf(this.view,t,e);this.view.loaderFrom=r.loader?this.view.loaderFrom??this.view.beat:void 0;let i="";r.lines.forEach((a,c)=>{if(this.screen[c]!==a)i+=`\x1B[${c+1};1H\x1B[K${a}`,this.screen[c]=a});let o=new Set;for(let a of r.images){let c=this.bands?this.banded(a):a;if(!c)continue;if(o.add(c.id),this.sent.get(c.id)!==c.path){let l=P0(c,this.files);if(l===void 0)continue;i+=l,this.sent.set(c.id,c.path),this.placed.delete(c.id)}let u=`${c.row};${c.col};${c.cols};${c.rows};${c.crop};${c.z}`;if(this.placed.get(c.id)!==u){if(!this.moves&&this.placed.has(c.id))i+=Zf(c.id);i+=H0(c,n),this.placed.set(c.id,u)}}for(let a of this.sent.keys())if(!o.has(a))i+=F0(a),this.sent.delete(a),this.placed.delete(a);i+=this.cover();let s=this.view.mode==="grid"&&this.view.editing!==void 0?this.caret():"";if(i||s)this.write(`\x1B[?2026h${i}${s}\x1B[?2026l`);this.pace(r.tick)}glide(){if(this.bands)this.prebake();if(this.gliding)return;let{cols:t,rows:e}=this.grid(),n=cr(t,e).height,r=()=>{let i=this.view,o=i.top*gt.height,s=o-i.scroll;if(s===0||i.mode!=="grid"){i.scroll=o;let a=this.gliding!==void 0;if(this.gliding=void 0,a)this.draw();return}if(Math.abs(s)>2*n)i.scroll=o-Math.sign(s)*n,s=o-i.scroll;i.scroll+=Math.sign(s)*Math.max(1,Math.round(Math.abs(s)*kR)),this.draw(),this.gliding=setTimeout(r,$R)};r()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*gt.height}resized(){this.screen=[]}stop(){clearInterval(this.ticking),clearTimeout(this.gliding)}prebake(){let t=this.view,{cols:e,rows:n}=this.grid();for(let r of Xf({...t,scroll:t.top*gt.height},e,n).images)if(r.crop!==void 0)this.band(r.path,r.crop,r.rows)}cover(){let{cols:t,rows:e}=this.grid(),n=`${t};${e}`;if(!this.layers||this.covered===n)return"";let r="";if(!this.covered){let i=Buffer.from(nt(this.background)).toString("base64");if(r+=`\x1B_Ga=t,f=24,s=1,v=1,i=${Ji},q=2;${i}\x1B\\`,bd)r+=`\x1B_Ga=t,f=32,s=1,v=1,i=${bs},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${bs},p=${bs},c=1,r=1,C=1,z=${bR},q=2\x1B\\`}else if(!this.moves)r+=Zf(Ji);if(this.covered=n,bd){let{x:i,y:o}=bd;return`${r}\x1B_Ga=p,i=${Ji},p=${Ji},P=${bs},Q=${bs},H=${-i},V=${-o},c=${t+2*i},r=${e+2*o},C=1,z=${d$},q=2\x1B\\`}return`${r}\x1B[H\x1B_Ga=p,i=${Ji},p=${Ji},c=${t},r=${e},C=1,z=${d$},q=2\x1B\\`}caret(){return`\x1B[1;${Math.min(this.grid().cols,tt(`⌕ ${this.view.editing??""}`)+1)}H`}pace(t){if(t)this.ticking??=setInterval(()=>{this.view.beat++,this.draw()},wR);else if(this.ticking)clearInterval(this.ticking),this.ticking=void 0}banded(t){if(t.crop===void 0)return t;let e=this.band(t.path,t.crop,t.rows,!this.gliding);return e?.ready?{...t,id:e.id,path:e.path,crop:void 0}:void 0}band(t,e,n,r=!0){let i=`${t}|${e}|${n}`,o=this.bandFiles.get(i);if(o||!r)return o;let{cell:s}=this.grid(),a=this.nextBand++,c={id:a,path:pR(this.scratch,`band-${a}.png`),ready:!1};return this.bandFiles.set(i,c),this.renders.run({job:"band",from:t,to:c.path,y:e*s.h,height:n*s.h}).then(()=>{c.ready=!0,this.draw()}).catch(()=>{}),this.trimBands(),c}trimBands(){for(let[t,e]of this.bandFiles){if(this.bandFiles.size<=vR)return;if(e.ready&&!this.sent.has(e.id))this.bandFiles.delete(t),gR(e.path,{force:!0})}}}var Br=[{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:ci,multi:{read:Mr}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Sr,multi:{read:li,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"]},...Li()?[{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:gg,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:pg,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:q.map((t)=>t.name),multi:{read:lo},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:Gu,multi:{read:Js,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 m$(t,e){if(t.multi)return t.multi.read(e).join(" ")||t.multi.none;if(t.entry==="number")return/^\d+$/.test(e??"")&&Number(e)>0?String(Number(e)):"off";if(t.entry==="text")return fo(e).join(" ");return t.choices.find((n)=>n===e)??t.choices[0]}var HR=["fit","newest","score"];function $d(t){return HR.find((e)=>e===t)??"fit"}var FR={left:-1,right:1,"shift-left":-10,"shift-right":10};function xR(t,e,n){if(e<0){if(t!=="fill")return Math.max($$,t+e);if(!n)return t;return Math.max($$,Math.max(100,n)+e+1)}return t==="fill"||t+e>n?"fill":t+e}function S$(t,e){return t.size===e.size&&t.at===e.at&&t.opacity===e.opacity}function LR(t,e){if(S$(t,e))return;return{...t.size!=="fill"?{size:t.size}:{},...t.at!==e.at?{position:Xt[t.at-1]}:{},...t.opacity!==e.opacity?{opacity:t.opacity}:{}}}function TR(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var g$=12,AR=4,CR=150,jR=300,p$=12,GR=2,UR=150,WR=30,_R=4000,BR=8000,b$=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,zR=process.platform==="win32"?"alt+v":"ctrl+v",w$=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",KR=1280,qR=16,JR=Xt.indexOf("top-right")+1,$$=20,k$=2,YR=3,DR=8,VR=9;function Sc(t,e){return{key:t,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:e,stage:"fetch",arrived:new Set}}function $s(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return $s(t.errors[0]);if(t.cause)return $s(t.cause);let e=t.code;if(typeof e==="string")return e;let n=(t.message||t.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function kd(t,e){return`${t}: ${$s(e)}`}function y$(t){return t.width*t.height}function v$(t,e){return`${t}-${E$("sha1").update(e).digest("hex").slice(0,8)}`}function ZR(t){let e=t.lastIndexOf("\x1B");return e!==-1&&/^\[?[0-9;]*$/.test(t.slice(e+1))}class yd{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(Br.map((t)=>[t.name,m$(t,process.env[t.name])]));direction=1;prefetching=0;related=new Map;pool=[];relating;thumbQueue=[];thumbing=0;clarity=new Map;tunedFiles=[];presenting=!1;again=!1;renders=new md;showing;thumbless=new Set;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Kf((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;scratch=IR(lr(RR(),"ttheme-find-"));home;catalog;entry;blurring;start;paint;kept;constructor(t,e,n,r,i){this.start=i,this.home=t,this.catalog=e,this.entry=n,this.tone=Gn(n,n.signatureSlots),this.blurring=Qn(t);let o={size:"fill",at:JR,opacity:this.tone.opacity};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:$d(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Mr(this.setting("TTHEME_FIND_RATING")),block:li(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:lo(this.setting("TTHEME_FIND_SITES")),hide:Js(this.setting("TTHEME_FIND_HIDE")),hideTags:fo(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Br.map((s)=>({label:s.label,choices:[...s.choices],value:this.setting(s.name),default:m$(s,To(s.name)),multi:s.multi&&{none:s.multi.none},about:s.about,entry:s.entry,advanced:s.advanced,cursor:0})),colors:{cursor:n.cursor,selection:n.selection,background:n.background,foreground:n.foreground,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",stage:"fetch",sites:[],focus:0,top:0,scroll:0,beat:0,mode:"grid",help:!1,scene:Math.max(0,he.findIndex((s)=>s.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...o},untuned:o,coloring:Na(t),editing:r===""?"":void 0,chips:[]},this.paint=new wd({view:this.view,grid:()=>({cols:this.cols,rows:this.rows,cell:this.cell}),background:n.background,renders:this.renders,scratch:this.scratch,signal:this.signal,write:(s)=>this.write(s)}),this.kept=new pd({home:t,catalog:e,entry:n,signal:this.signal,credited:()=>{this.show(),this.inform(),this.paint.draw()}}),this.pool=this.selected(this.view),this.syncChips(),this.board=Sc(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:q[this.tab-1]}get sites(){return this.site?[this.site]:q.filter((t)=>this.view.enabled.includes(t.name))}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??AR}get nextTabName(){let t=(this.tab+1)%(q.length+1);return t===0?"all":q[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}narrowed(){return Wu(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(t,e,n){return lr(ke(t),"orig",`${e}.${n}`)}previewPath(t){let{url:e}=Ds(t.site,t.post);return lr(ke(t.site),"thumb",`${v$(t.post.id,e)}.${xn(e)}`)}tileOf(t,e){let{site:n,post:r}=t,i=Zt(n,r.id),o=Ge(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:o.width,height:o.height,reduced:o!==r,page:n===Gr?"":n.pageUrl(r.id),artist:n===Gr?f0(r.source):r.named.artist[0]??"",score:r.score,variants:e,mates:this.kept.matesOf(n,r.owner),thumb:this.thumbPath.get(i),missing:this.thumbless.has(i)}}show(){let t=this.view,e=this.board;if(t.tiles=e.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),t.checked=e.checked,t.total=e.total,t.searching=e.searching,this.stageOf(e),t.note=e.note,t.focus=Math.max(0,Math.min(e.focus,t.tiles.length-1)),t.top=e.top,this.showing!==e)this.showing=e,this.paint.snap()}stageOf(t){let e=this.view;e.stage=t.stage,e.ranking=t.ranking,e.sites=this.sites.map((n)=>({name:n.name,arrived:t.arrived.has(n.name)}))}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:e}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),e.on("resize",this.onResize),this.write(`\x1B[?25l\x1B[?7l${Ni}`);let n=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search(),this.relate(this.view.tag)}else this.view.searching=!1,this.view.error="This terminal does not report its cell size — find needs kitty graphics";if(await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.start&&"paste"in this.start)this.pasted(this.start.paste);else if(this.start)this.fromClipboard();else this.peek();this.paint.draw();let o=await n;return this.session.abort(),this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),this.quietCount(),clearInterval(r),this.paint.stop(),t.off("data",this.onData),e.off("resize",this.onResize),this.write(`\x1B_Ga=d,d=A,q=2\x1B\\${Ni}`),t.setRawMode(!1),t.pause(),this.kept.save(),this.renders.close(),Ec(this.scratch,{recursive:!0,force:!0}),Rg(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved?.text}get installs(){return this.view.installed.length}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let e=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(n)=>{clearTimeout(e),this.probeWait=void 0,t(n)},this.write(R0)})}onData=(t)=>{this.input+=t.toString("utf8");for(let n=Vf(this.input);n;n=Vf(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let e=fc(this.input);if(this.input=e.pending,this.view.editing===void 0&&e.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(e.keys))this.pasted(e.keys),e.keys="";this.typed+=e.keys;for(let n of e.events)this.inbound(n);if(clearTimeout(this.partial),ZR(this.typed)){this.partial=setTimeout(this.flushKeys,WR);return}this.flushKeys()};flushKeys=()=>{let t=mc(this.typed);this.typed="";for(let e of t)this.key(e)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let e=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(e),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let e=this.view;if(e.editing!==void 0&&t.trim()!==""&&!this.picture(t)){e.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.paint.draw();return}if(e.installing!==void 0||e.panel!==void 0||e.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let e=t.trim();if(/^https?:\/\/\S+$/i.test(e))return!Ys(e,this.site??q[0]);return Ui(e).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`No picture on the clipboard — ${w$}`);return}this.pasted(t.text);return}await this.bring(()=>uc(t.bytes,t.source))}notice(t,e=_R){let n=this.view;n.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===t)n.error=void 0,this.paint.draw()},e),this.paint.draw()}async peek(){let t=this.view,e;try{e=await p0()}catch{return}if(!e||e.stamp===this.peeked)return;if(this.peeked=e.stamp,!e.picture||t.installing!==void 0)return;t.hint=`Picture on the clipboard · ${zR} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.paint.draw()},BR),this.paint.draw()}async fromClipboard(){let t=this.view;if(zf()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("Over SSH the clipboard is not here — drop the file");return}let e;try{e=await g0(lr(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${$s(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in e){await this.bring(async(r)=>({...await Bf(e.image,r),source:"clipboard"}));return}let n=e.text.trim();if(!n){this.notice(`No picture on the clipboard — ${w$}`);return}if(this.picture(n)){await this.attach(n);return}if(t.editing===void 0)t.editing="";this.pasted(n)}async attach(t){let e=t.trim();if(/^https?:\/\//i.test(e)){let i=Ys(e,this.site??q[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ui(e).sort((i,o)=>Number(!b$.test(i))-Number(!b$.test(o)));if(!n){this.notice("Nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>Bf(n,i),r.length)}async bring(t,e=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="Reading the picture…",this.paint.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(d){if(!r.signal.aborted)n.note=void 0,this.notice($s(d),8000);return}if(r.signal.aborted)return;n.note=e>0?`The first picture of ${e+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let o=h0(i.bytes);d0(o,i.source);let s=this.origPath(Gr,o,i.ext);x(s,i.bytes);let a=h$(s).href,c={id:o,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:E$("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},u={site:Gr,post:c},l=this.previewPath(u);x(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=Sc(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,u)}single(t,e){t.searching=!1,this.posts.set(Zt(e.site,e.post.id),e),t.groups=[{posts:[e],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(e),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.paint.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>cn(i)>cn(r)?i:r),e=Math.ceil((cn(t)-Date.now())/1000),n=e>0?e:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=t.name,this.paint.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.paint.resized(),this.scroll(),this.paint.snap(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.paint.draw()};key(t){let e=this.view;if(t==="ctrl-c"){this.finish(2);return}if(e.installing!==void 0)return;if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&e.panel===void 0){this.fromClipboard();return}if(e.editing!==void 0){this.editKey(t);return}if(e.panel!==void 0){this.panelKey(t);return}if(e.help){if(t==="?"||t==="esc")e.help=!1,this.paint.draw();return}if(this.cols<Wr.cols||this.rows<Wr.rows){if(t==="esc")this.finish(2);return}if(t==="?"){e.help=!0,this.paint.draw();return}if(e.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let e=this.view,{perRow:n,rowsVis:r}=cr(this.cols,this.rows),o={left:-1,right:1,up:-n,down:n,k:-n,j:n,pgup:-n*r,pgdn:n*r,home:-e.focus,end:e.tiles.length}[t];if(o!==void 0){this.focus(e.focus+o);return}if(/^[1-9]$/.test(t)){this.toggle(Number(t)-1);return}if(t==="enter"&&e.tiles[e.focus]){e.mode="try",e.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){e.preset=e.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"||t==="shift-tab"){let s=q.length+1;this.tab=(this.tab+(t==="tab"?1:s-1))%s,this.syncSite(),this.turn();return}if(t==="/"){e.editing="",this.paint.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){e.panel=0,e.advanced=!1,this.recount(),this.paint.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let e=this.view,n=e.panel??0,r=e.settings[n];if(e.typing!==void 0&&r){this.typeKey(r,t);return}let i=us(e);if(t==="up"||t==="down"){let o=i.indexOf(n)+(t==="up"?-1:1);e.panel=i[(o+i.length)%i.length]??n,this.paint.draw();return}if(t==="a"||t==="enter"&&n===e.settings.length){e.advanced=!e.advanced,e.panel=us(e)[0]??0,this.paint.draw();return}if(r?.entry&&(t==="enter"||r.entry==="number"&&/^[0-9]$/.test(t))){e.typing=t==="enter"?r.entry==="text"?r.value:"":t,this.paint.draw();return}if((t==="left"||t==="right")&&r&&r.entry!=="text"){let o=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+o+r.choices.length)%r.choices.length;else r.value=j0(r.choices,r.value,o),this.recount();this.paint.draw();return}if(t===" "&&r?.multi){let o=r.value.split(" "),s=r.choices.filter((c,u)=>u===r.cursor?!o.includes(c):o.includes(c)),a=r.multi.none;if(s.length>0||a!==void 0)r.value=s.length>0?s.join(" "):a,this.recount(),this.paint.draw();return}if(t==="esc"){e.settings.forEach((o,s)=>{o.value=this.setting(Br[s]?.name??"")}),e.panel=void 0,e.advanced=!1,this.quietCount(),this.paint.draw();return}if(t==="enter"||t==="s"||t==="alt-c")e.panel=void 0,e.advanced=!1,this.quietCount(),this.adopt()}typeKey(t,e){let n=this.view,r=n.typing??"";if(e==="esc"){n.typing=void 0,this.paint.draw();return}if(e==="enter"||e==="up"||e==="down"){if(t.value=t.entry==="number"?Number(r)>0?String(Number(r)):"off":fo(r).join(" "),n.typing=void 0,this.recount(),e==="enter"){this.paint.draw();return}this.panelKey(e);return}if(e==="backspace"){n.typing=r.slice(0,-1),this.paint.draw();return}if(t.entry==="number"?/^[0-9]$/.test(e)&&r.length<Qf:/^[\x20-\x7e]$/.test(e))n.typing=r+e,this.paint.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 t=new AbortController;this.counting=t,this.countTimer=setTimeout(()=>void this.countPending(t),jR)}pending(){let t=(e)=>this.view.settings[Br.findIndex((n)=>n.name===e)]?.value??this.setting(e);return{tag:this.view.tag,chosen:this.view.chosen,preset:t("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:$d(t("TTHEME_FIND_ORDER")),rating:Mr(t("TTHEME_FIND_RATING")),narrow:Wu(t("TTHEME_FIND_MIN_SCORE"),t("TTHEME_FIND_MIN_SIZE"),t("TTHEME_FIND_PNG")),enabled:lo(t("TTHEME_FIND_SITES"))}}async countPending(t){let e=this.pending(),n=this.site?[this.site]:q.filter((o)=>e.enabled.includes(o.name)),r=AbortSignal.any([this.signal,t.signal]),i=await Promise.all(n.map(async(o)=>{let s=this.query(o,e);if(!s)return{site:o.name,count:0};if(o.counts&&!o.counts(s.tags))return{site:o.name};try{let a=await Ku(o,s.tags,r);return{site:o.name,...Number.isFinite(a)?{count:a}:{}}}catch{return{site:o.name}}}));if(this.counting===t&&this.view.panel!==void 0)this.view.counts=i,this.paint.draw()}adopt(){let t=this.view,e=Br.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=Br[i];if(o)this.values.set(o.name,r.value)});let n=Br.filter((r,i)=>this.setting(r.name)!==e[i]);if(n.length===0){this.paint.draw();return}this.save(n),t.rating=Mr(this.setting("TTHEME_FIND_RATING")),t.block=li(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=$d(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",t.narrow=this.narrowed(),t.enabled=lo(this.setting("TTHEME_FIND_SITES")),t.hide=Js(this.setting("TTHEME_FIND_HIDE")),t.hideTags=fo(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((e)=>[e.name,this.setting(e.name)]))}store(t){let e=lr(this.home,"ttheme","config.zsh");try{let n=ws(e)?OR(e,"utf8"):"";return x(e,t.reduce((r,[i,o])=>Ra(r,i,o),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}editKey(t){let e=this.view,n=e.editing??"",r=e.suggest??[];if((t==="up"||t==="down")&&r.length>0){let o=((e.pick??r.length)+(t==="down"?1:r.length))%(r.length+1);e.pick=o===r.length?void 0:o,this.paint.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(e.editing=void 0,e.tag===""){this.finish(2);return}this.paint.draw();return}if(t==="enter"){let i=e.pick===void 0?void 0:r[e.pick],o=i?n.replace(/\S*$/,i.value):n;if(e.editing=void 0,e.suggest=void 0,e.pick=void 0,o.trim()){this.commit(o.trim());return}if(e.tag===""){this.finish(2);return}this.paint.draw();return}if(t==="backspace"){e.editing=n.slice(0,-1),this.suggest(),this.paint.draw();return}if(t.length===1&&t>=" ")e.editing=n+t,this.suggest(),this.paint.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let e=/\S*$/.exec(t.editing??"")?.[0]??"";if(!TR(e)){t.suggest=void 0;return}let n=[...new Map(eb(this.catalog.palettes,this.entry,e).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,YR);t.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Hg(e,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((a)=>[a.value,a.count])),s=new Set(n.map((a)=>a.value));t.suggest=[...n.map((a)=>({...a,count:o.get(a.value)??0})),...i.filter((a)=>!s.has(a.value))].slice(0,DR),t.pick=t.pick!==void 0&&t.pick<n.length?t.pick:void 0,this.paint.draw()}}catch{}},CR)}async commit(t){let e=Ys(t,this.site??q[0]);if(e){await this.jump(e.site,e.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.view.chosen=void 0,this.relate(t),this.boards.clear(),await this.search()}async jump(t,e){let n=++this.gen;this.tab=q.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=Sc(`${t.key}|post:${e}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.paint.draw();try{let i=await fi(t,e,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${e}`,this.view.error=r.error,this.show(),this.paint.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(n,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.paint.draw(),await this.pump()}unfold(){let t=this.view,e=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(t.focus<e+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=e;for(let i of n.posts)if(!this.thumbPath.has(Zt(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.paint.glide(),this.paint.draw();return}e+=r}}openPage(){let t=this.view.tiles[this.view.focus],e=t&&this.posts.get(t.key);if(!e)return;let n=process.platform==="darwin"?"open":"xdg-open";try{SR(n,[e.site.pageUrl(e.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let e=this.view;if(e.tuning){this.tuneKey(t);return}if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(e.focus+this.direction);return}if(t==="shift-left"||t==="shift-right"){e.scene+=t==="shift-left"?-1:1,e.details=!1,this.paint.draw();return}if(t==="i"){e.details=!e.details,this.inform(),this.paint.draw();return}if(t==="t"){e.tuning={field:0,held:{...e.tune},fill:this.current?.fill??0,coloring:e.coloring},this.paint.draw();return}if(t==="c"){this.recolor();return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid",e.error=void 0,this.paint.draw()}tuneKey(t){let e=this.view,n=e.tuning,r=e.tune;if(t==="up"||t==="down"){n.field=(n.field+(t==="up"?2:1))%3,this.paint.draw();return}let i=FR[t];if(i!==void 0){if(n.field===0)r.size=xR(r.size,i,n.fill);else if(n.field===1)r.at=(r.at-1+Math.sign(i)+9)%9+1;else r.opacity=Math.max(0,Math.min(100,Math.round(r.opacity*100)+i))/100;this.retune();return}if(/^[1-9]$/.test(t)){n.field=1,r.at=Number(t),this.retune();return}if(t==="="){let o=e.untuned;if(n.field===0)r.size=o.size;else if(n.field===1)r.at=o.at;else r.opacity=o.opacity;this.retune();return}if(t==="+"){e.tune={...e.untuned},this.retune();return}if(t==="enter"){e.tuning=void 0,this.paint.draw();return}if(t==="c"){this.recolor();return}if(t==="esc")e.tune={...n.held,...n.coloring===e.coloring?{}:{opacity:e.untuned.opacity}},e.tuning=void 0,this.retune()}recolor(){let t=this.view;if(!this.current||t.shown?.id!==this.current.key)return;t.coloring=t.coloring==="tone"?"original":"tone",t.tune.opacity=t.untuned.opacity,this.paint.draw(),this.reveal()}retune(){if(this.paint.draw(),this.current&&this.view.shown?.id===this.current.key)this.reveal()}inform(){let t=this.view,e=t.tiles[t.focus],n=e&&this.posts.get(e.key);t.info=n?this.infoOf(n):void 0}infoOf(t){let{site:e,post:n}=t,r=n.named,i=Og(e,n),o=new Set([...r.artist,...r.character,...r.copyright]),s=ho(n.source),a=/^https?:\/\//i.test(s)?s:e===Gr&&s.startsWith("/")?h$(s).href:void 0;return{page:e===Gr?"":e.pageUrl(n.id),source:s,...a?{link:a}:{},artists:r.artist,characters:r.character,series:r.copyright,tags:n.tags.filter((c)=>!o.has(c)),...i?{rating:i}:{},...n.posted?{posted:n.posted}:{},ext:(Ge(n)??n).ext,uploader:n.owner}}focus(t){let e=this.view;if(e.tiles.length===0)return;let n=Math.max(0,Math.min(e.tiles.length-1,t));if(n===e.focus)return;if(e.focus=n,this.board.focus=n,this.scroll(),this.paint.glide(),this.pump(),e.mode==="try")this.select();this.paint.draw()}scroll(){let t=this.view,{perRow:e,rowsVis:n}=cr(this.cols,this.rows),r=Math.floor(t.focus/e);if(r<t.top)t.top=r;if(r>t.top+n-1)t.top=r-n+1;this.board.top=t.top}selected(t){if(t.chosen)return t.chosen;if(!t.tag)return[];return t.tag===this.entry.booru?Ml(this.entry,"danbooru"):[t.tag]}syncChips(){let t=this.selected(this.view);this.view.chips=this.pool.slice(0,VR).map((e)=>({name:e,on:t.includes(e)}))}toggle(t){let e=this.view,n=e.chips[t];if(!n)return;let r=this.selected(e),i=n.on?r.filter((o)=>o!==n.name):[...r,n.name];if(i.length===0)return;e.chosen=i,e.tag=i.join(" or "),this.syncChips(),this.boards.clear(),this.search()}async relate(t){this.relating?.abort();let e=this.selected({tag:t,chosen:void 0});if(this.pool=e,this.syncChips(),this.paint.draw(),!t||/\s/.test(t))return;let n=this.related.get(t);if(!n){let r=new AbortController;this.relating=r;try{n=(await Fg(t,AbortSignal.any([this.signal,r.signal]))).map((i)=>i.value)}catch{return}if(this.relating!==r)return;this.related.set(t,n)}this.pool=[...new Set([...e,...n])],this.syncChips(),this.paint.draw()}query(t,e=this.view){let n=e.chosen?xg(t,e.chosen):e.tag===this.entry.booru?Ml(this.entry,t.key):[e.tag];if(n.length===0)return;let r=e.chosen?.slice(n.length)??[],i=n.length>1,o=e.preset==="cutouts"?t.cutouts:"",s=i&&o.includes("~"),a=[i?n.map((l)=>`~${l}`).join(" "):n[0],t.rate(e.rating),...t.narrow(e.narrow),s?"":o,e.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let l of a)if(zu([...c,l].join(" "))<=t.tagBudget)c.push(l);else u.push(l);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...r.length>0?[`${t.name} takes ${n.length} tag${n.length===1?"":"s"} — ${r.join(" ")} left out`]:[],...s?[`${t.name} ORs the names, so cutouts are told by the file`]:[],...e.narrow.score>0&&!t.scored?[`${t.name} keeps no score`]:[],...e.narrow.png&&t.guesses?[`${t.name} names a file type only where danbooru holds the file`]:[]]}}async search(){let t=++this.gen,e=Sc(this.boardKey,!0);this.board=e,this.boards.set(e.key,e),this.view.error=void 0;let n=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!n.some((s)=>s.site===o)),i=[...n.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(e.note=i.length>0?i.join(" · "):void 0,n.length===0)e.searching=!1;this.show(),this.paint.draw(),this.tally(t,e,n);try{let o=await Promise.all(n.map(async(s)=>({plan:s,owners:await this.kept.mateOwners(s.site)})));if(t!==this.gen)return;e.sources=o.flatMap(({plan:{site:s,tags:a},owners:c})=>{let u=zu(a)+1<=s.tagBudget?s.uploadedBy:void 0;return[...u?[...c.keys()].map((l)=>({site:s,tags:`${a} ${u(l)}`,page:0,done:!1})):[],{site:s,tags:a,page:0,done:!1}]}),this.show(),this.paint.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,e,n){let r=await Promise.allSettled(n.map(({site:i,tags:o})=>Ku(i,o,this.signal)));if(t===this.gen)e.total=r.reduce((i,o)=>i+(o.status==="fulfilled"&&Number.isFinite(o.value)?o.value:0),0),this.show(),this.paint.draw()}fail(t,e,n=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=kd(n?.name??this.tabName,e),this.board.searching=!1,this.view.error=this.board.error,this.show(),this.paint.draw()}drop(t,e,n){for(let r of t.sources)if(r.site===e)r.done=!0;t.note=[t.note,kd(e.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:t,rowsVis:e}=cr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+e+k$)*t}need(){let{perRow:t,rowsVis:e}=cr(this.cols,this.rows);return(e+k$)*t}live(t){return this.boards.get(t.key)===t}page(t,e,n){let r=`${t.key}|${e}|${n}`,i=this.pages.get(r);if(!i)i=Pg(t,e,n,this.signal).then((o)=>this.borrow(t,o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t,e){let n=t===Ut?[]:e.filter((r)=>r.md5!=="");if(n.length>0)try{ea(n,await na(n.map((r)=>r.md5),this.signal))}catch{}return e}staged(t){if(t===this.board)this.stageOf(t),this.paint.draw()}async round(t){t.stage="fetch",this.staged(t);let e=q.flatMap((a)=>{let c=t.sources.find((u)=>u.site===a&&!u.done);return c?[c]:[]}),n=await Promise.all(e.map(async(a)=>{try{let c=await this.page(a.site,a.tags,a.page);return t.arrived.add(a.site.name),this.staged(t),{source:a,posts:c}}catch(c){if(t.sources.every((u)=>u.site===a.site)||this.signal.aborted)throw c;return this.drop(t,a.site,c),{source:a,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:a,posts:c}of n){if(!c)continue;a.page++,a.done=c.length<Hn;let u=t.last.get(a);for(let l of c){let f=u&&s$(u.post,l)?u.set:`set:${a.site.key}:${l.id}`;u={post:l,set:f};let d=Zt(a.site,l.id);if(t.seen.has(d))continue;t.seen.add(d);let m={site:a.site,post:l};if(this.eligible(m))t.kin.set(m,[f,...o$(a.site,l)]),r.push(m);else t.checked++}if(u)t.last.set(a,u)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=e.length>1?r$(i):i;else{let a=yc(i,this.frame(),this.matched),c=a.slice(0,this.need()),u={done:0,total:c.length};if(t.ranking=u,this.staged(t),await this.looks(c,()=>{u.done++,this.staged(t)}),t.ranking=void 0,!this.live(t))return;s=[...yc(c,this.frame(),this.matched),...a.slice(c.length)]}t.stage="check",this.staged(t);for(let a of s)t.roundOf.set(a,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let e=t.queue.slice(0,this.need()).filter((n)=>!this.looking.has(Zt(n.site,n.post.id)));if(e.length===0)return;this.aheading=!0,this.looks(e).then(()=>{this.aheading=!1;for(let n of new Set(e.map((r)=>t.roundOf.get(r)??0)))this.resort(t,n);this.ahead(t)})}resort(t,e){let n=t.queue.flatMap((i,o)=>t.roundOf.get(i)===e?[o]:[]),r=yc(n.map((i)=>t.queue[i]),this.frame(),this.matched);n.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,e){let n=[];for(let r of e){let i=fd(r.post),o=i.map((a)=>t.same.get(a)).find(Boolean);if(!o){for(let a of i)t.same.set(a,r);n.push(r);continue}if(t.checked++,y$(r.post)<=y$(o.post))continue;for(let a of[...i,...fd(o.post)])t.same.set(a,r);let s=n.indexOf(o);if(s>=0){n[s]=r;continue}this.replace(t,o,r)}return n}replace(t,e,n){t.roundOf.set(n,t.roundOf.get(e)??0);let r=t.queue.indexOf(e);if(r>=0){t.queue[r]=n;return}for(let i of t.groups){let o=i.posts.indexOf(e);if(o>=0){i.posts[o]=n,this.posts.set(Zt(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(t,e){let n=0;await Promise.all(Array.from({length:p$},async()=>{while(n<t.length)await this.look(t[n++]),e?.()}))}look(t){let e=Zt(t.site,t.post.id),n=this.looking.get(e);if(!n)n=(async()=>{let r=this.previewPath(t),i=Ds(t.site,t.post);await this.kept.cached(i.site,r,i.url);let o=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(e,o),this.matched.set(t.post,o.match),o})().catch(()=>{return}),this.looking.set(e,n);return n}async pump(){let t=this.gen,e=this.board;if(this.pumping===t||e.sources.length===0)return;this.pumping=t;let n=[],r;try{e.searching=!0;while(t===this.gen){while(n.length<g$&&e.queue.length>0&&this.wants()){let s=e.queue.shift();n.push({pick:s,passed:this.vet(s)})}if(this.ahead(e),!r&&e.queue.length<g$&&e.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(e).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.paint.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(e.checked++,o)this.admit(i.pick);this.show(),this.paint.draw()}if(t===this.gen)e.searching=!1,this.show(),this.paint.draw()}catch(i){this.fail(t,i)}finally{if(this.kept.save(),this.pumping===t)this.pumping=0}}eligible({site:t,post:e}){let n=Ge(e);if(!Zs(t,e,this.view.rating)||Vs(e,this.view.block).length>0||!n)return!1;if(this.view.solo&&e.solo===!1)return!1;let{score:r,size:i,png:o}=this.view.narrow;if(Math.min(e.width,e.height)<i||t.scored&&e.score<r||o&&e.ext!=="png"||Ig(e,this.view.hide).length>0||this.view.hideTags.some((s)=>e.tags.includes(s)))return!1;return this.view.preset==="all"?["png","jpg","jpeg",""].includes(n.ext):["png",""].includes(e.ext)}async vet(t){let[e]=await Promise.all([this.passes(t),this.look(t)]);return e}async passes({site:t,post:e}){return this.view.preset==="all"||t.vouched||this.kept.transparent(t,e)}admit(t){let{site:e,post:n}=t,r=this.board,i=Zt(e,n.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),a=s&&{hash:s.hash,width:n.width,height:n.height},c=this.view.sets==="fold"?this.kindred(r,o,a):void 0;if(c){if(c.posts.push(t),this.register(r,c,o,a),c.open)this.thumbQueue.push(t),this.thumbs();return}let u={posts:[t],open:!1};r.groups.push(u),this.register(r,u,o,a),this.thumbQueue.push(t),this.thumbs()}kindred(t,e,n){for(let r of e){let i=t.kindred.get(r);if(i)return i}return n&&t.shapes.find((r)=>c$(r.shape,n))?.group}register(t,e,n,r){for(let i of n)if(!t.kindred.has(i))t.kindred.set(i,e);if(r)t.shapes.push({shape:r,group:e})}thumbs(){while(!this.signal.aborted&&this.thumbing<p$&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{this.thumbless.add(Zt(t.site,t.post.id)),this.show(),this.paint.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:e,post:n}=t,r=gt.cols*this.cell.w,i=gt.rows*this.cell.h,o=Ds(e,n),s=lr(ke(e),"tile",`${v$(n.id,o.url)}-${r}x${i}.png`);if(!ws(s)){let a=this.previewPath(t);if(await this.kept.cached(o.site,a,o.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:s,width:r,height:i})}this.thumbPath.set(Zt(e,n.id),s),this.show(),this.paint.draw()}select(){let t=this.view,e=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,this.inform(),!e)return;if(this.current?.key===e.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(e),UR),this.paint.draw()}async load(t){let e=this.view,n=this.posts.get(t.key);if(!n)return;let r=new AbortController;if(this.fetch=r,this.kept.credit(n,r.signal),!Ge(n.post))return;let{site:i}=n,o=this.board;try{await go(i,n.post,r.signal);let s=Ge(n.post),a=this.origPath(i,t.id,s.ext);if(!ws(a))e.fetching={id:t.key,got:0,size:0},this.paint.draw();let c=Ir(i,n.post,s),u=await this.kept.cached(c.site,a,c.url,(d,m)=>{if(e.fetching?.id===t.key)e.fetching={id:t.key,got:d,size:m},this.paint.draw()});if(r.signal.aborted)return;if(e.fetching=void 0,o!==this.board)return;let l={site:i,id:t.id,key:t.key,path:a,ext:s.ext,size:u,using:"plain",failed:!1};e.preparing=t.key,this.paint.flush();let f=await this.render(l,"plain");if(r.signal.aborted||o!==this.board)return;if(f.clear===0&&Li()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(e.preparing=void 0,e.cutting=t.key,this.paint.flush(),l.cut=await this.cutOut(i,t.id,a,r.signal),r.signal.aborted||o!==this.board)return;if(e.cutting=void 0,l.cut){e.preparing=t.key,this.paint.flush();let d=await this.render(l,"cut").catch(()=>{return});if(r.signal.aborted||o!==this.board)return;if(d&&Za(d.clear))l.using="cut";else Ec(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,e.tiles[e.focus]?.key===t.key)await this.present();this.preload()}catch(s){if(!r.signal.aborted&&!this.signal.aborted)e.error=kd(i.name,s)}finally{if(e.fetching?.id===t.key)e.fetching=void 0;if(e.preparing===t.key)e.preparing=void 0;if(e.cutting===t.key)e.cutting=void 0;this.paint.draw()}}async cutOut(t,e,n,r){let i=lr(ke(t),"cut",`${e}.png`);if(ws(i))return i;try{return MR(PR(i),{recursive:!0}),await Ko(n,i,r),i}catch{Ec(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let e of[t.focus+this.direction,t.focus-this.direction]){let n=t.tiles[e],r=n&&this.posts.get(n.key);if(r)this.kept.credit(r,this.signal);if(this.prefetching>=GR||!r||!Ge(r.post))continue;let{site:i,post:o}=r;this.prefetching++,go(i,o,this.signal).then(async()=>{let s=Ge(o),a=this.origPath(i,o.id,s.ext),c=Ir(i,o,s);return await this.kept.cached(c.site,a,c.url),this.render({site:i,id:o.id,key:n.key,path:a,ext:s.ext,size:0,using:"plain",failed:!1},"plain")}).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,e){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,KR),o=Math.max(1,Math.round(r*i/n)),s={...this.view.tune},{coloring:a}=this.view,c=!S$(s,this.view.untuned),u=s.opacity!==this.view.untuned.opacity,l=c?`-${s.size}-${s.at}${u?`-${Math.round(s.opacity*100)}`:""}`:"",f=lr(this.scratch,`${t.site.key}-${t.id}${e==="cut"?"c":""}${a==="original"?"o":""}-${i}x${o}${l}.png`),d=`${t.site.key}:${t.id}:${e}:${a}:${i}x${o}`,m=this.clarity.get(d);if(m&&ws(f))return t.fill=m.fill,{clear:m.clear,path:f,opacity:m.opacity,touched:u};let g=await this.renders.run({job:"show",from:e==="cut"?t.cut:t.path,to:f,width:i,height:o,colors:this.entry,tone:this.tone,blur:this.blurring*i/ol(n,r).width,coloring:a,...c?{tune:{size:s.size,at:s.at,...u?{opacity:s.opacity}:{}}}:{}});if(this.clarity.set(d,g),t.fill=g.fill,c)this.keepTuned(f);return{clear:g.clear,path:f,opacity:g.opacity,touched:u}}keepTuned(t){this.tunedFiles.push(t);while(this.tunedFiles.length>qR){let e=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==t);if(e===-1)return;Ec(this.tunedFiles.splice(e,1)[0],{force:!0})}}async present(){let t=this.current;if(!t)return;let e=t.using,{coloring:n}=this.view,r=this.view.tune.opacity,{clear:i,path:o,opacity:s,touched:a}=await this.render(t,e);if(this.current!==t||t.using!==e||this.view.coloring!==n)return;if(!a&&this.view.tune.opacity===r)this.view.untuned.opacity=s,this.view.tune.opacity=s;if(this.view.tuning&&t.fill)this.view.tuning.fill=t.fill;this.view.shown={id:t.key,clear:i,bytes:t.size,path:o,cut:t.cut?e==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;if(this.presenting){this.again=!0;return}this.presenting=!0,t.preparing=this.current?.key,this.paint.flush(),this.present().catch((e)=>{t.error=e instanceof Error?e.message:String(e)}).finally(()=>{if(this.presenting=!1,this.again){this.again=!1,this.reveal();return}if(t.preparing===this.current?.key)t.preparing=void 0;this.paint.draw()})}async install(){let t=this.view,e=t.tiles[t.focus],n=this.current;if(!e||n?.key!==e.key||t.preparing!==void 0||t.shown?.id!==e.key)return;t.installing=e.key,t.error=void 0,this.paint.flush();let r=LR(t.tune,t.untuned),i=this.posts.get(n.key)?.post;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)}`,artist:i?.named.artist??[],source:ho(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,coloring:t.coloring,...r?{tune:r,aligns:Tr(B(this.home).terminals),user:NR()}:{}}),this.kept.owned(n.site,n.id,i?.owner??""),se(this.home);let{size:o,at:s,opacity:a}=t.tune,c=r?` · ${o==="fill"?"fill":`${o}%`} · ${Xt[s-1]} · ${a.toFixed(2)}`:"",u=i?.named.artist.length?`${i.named.artist.join(", ")} · `:"";t.saved={text:`Background · ${this.entry.name} ← ${u}${n.site.name} ${n.id}${c}`,key:e.key},t.installed.push(e.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(o){t.error=o instanceof Error?o.message:String(o)}t.installing=void 0,this.paint.draw()}}async function M$(t,e,n){let r=new yd(t,Oe(t),e,e.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function I$(t){let e=Y(),n=Oe(e),r=hn(n.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new yd(e,n,r,r.booru??""),o=await i.run();if(i.saved&&o!==0)return process.stderr.write(`${i.saved}
523
+ `),0;return o}import{existsSync as Ic,readdirSync as QR,readFileSync as vd,rmSync as O$,statSync as N$}from"node:fs";import{homedir as XR}from"node:os";import{join as ks}from"node:path";var tP=150,eP=260;function Mc(t){return t?.includes(`path = "${T("")}`)===!0}function nP(t){try{return B(t).terminals.includes("warp")}catch{return!1}}function rP(t,e){let n=T(e);if(!Ic(t))return;return QR(t).filter((i)=>i.startsWith(`${n}.`)&&/^[0-9a-f]{8}\.yaml$/.test(i.slice(n.length+1))).map((i)=>({file:i,at:N$(ks(t,i)).mtimeMs})).sort((i,o)=>o.at-i.at)[0]?.file??(Ic(ks(t,`${n}.yaml`))?`${n}.yaml`:void 0)}function fr(t,e,n,r=XR()){if(!e||zt(t)||t.TMUX||re(t)!=="warp")return;let i=rr(r,n);if(!Ic(i)||!nP(n))return;let o=xr(r),s=Wa(n),a=[],c,u,l=(g)=>{let $=vd(i,"utf8"),w=ir($);if(w===g)return;if(Mc(g)&&!Mc(w)&&!Ic(s))x(s,w??"");if(Ae(i,_a($,g)),!Mc(g))O$(s,{force:!0})},f=(g)=>{for(let $ of a.splice(0))if($===g)a.push($);else O$(ks(o,$),{force:!0})},d=()=>{clearTimeout(c),clearTimeout(u)},m=(g,$)=>{d(),c=setTimeout(()=>{let w=$;if(!w)w=`${T(g.name)}.view-${process.pid}-${a.length+1}.yaml`,x(ks(o,w),jo(g)),a.push(w);let b=w,v=Date.now()-N$(ks(o,b)).mtimeMs;u=setTimeout(()=>{l(sf(g.name,b)),f(b)},Math.max(0,eP-v))},tP)};return{slots:[],paint:(g)=>{return m(g,rP(o,g.name)),""},look:(g,$)=>{let[w="",b="",v="",,...R]=$;m({name:g,background:w,foreground:b,cursor:v,ansi:R})},wear:(g,$)=>$.includes("warp")?"":void 0,saved:async()=>new Map([["theme",ir(vd(i,"utf8"))??""]]),restore:(g)=>{d();let $=g.get("theme");if($)l($);else if(Mc(ir(vd(i,"utf8"))))l(Ua);return f(),""}}}function Sd(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function R$(t,e){if(t.includes("/"))return t;let n=Pr(e,!1),r=n.filter((o)=>zn(o.dir).some((s)=>s.slug===t)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${t}`:t}function sP(t,e,n){let r=B(t),i=n.filter((o)=>!r.palettes.includes(o));if(i.length>0)Ye(t,e,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((o)=>r.palettes.includes(o)))At(t,e,r);return{state:r,fresh:i}}function aP(t){let e=Math.max(0,...t.map((n)=>n.slot.length));return t.map((n)=>` ${n.slot.padEnd(e)} ${n.from} → ${n.to} ${n.rule}`)}function P$(t,e,n){let r=_p(e),i=de(ne(r.name,$l(r),n.palettes)),o=wt(t,n,!1).palettes.find((s)=>s.name===i.name);if(o&&JSON.stringify(o)!==JSON.stringify(i))throw Error(`${i.name} is already in ${rt(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!o)ya(t,[...dn(t),i]);return i.name}var cP=["background","foreground","cursor"];function H$(t){try{t();return}catch(e){return e.message}}function F$(t,e,n){return wt(t,e,!1).palettes.filter((r)=>r.name!==n).map((r)=>({name:r.name,colors:{background:r.background,foreground:r.foreground,cursor:r.cursor,selection:r.selection,ansi:r.ansi}}))}function x$(t,e){let n=new Set(fe(t,e).map((r)=>r.key));return{count:()=>fe(t,e).length,added:()=>fe(t,e).filter((r)=>!n.has(r.key)).length,fresh:()=>(Xa(t,e)??[]).filter((r)=>!n.has(Wt(r))),discard:()=>{let r=fe(t,e).filter((i)=>!n.has(i.key));for(let i of r)yi(t,e,i.key),la(t,e);if(r.length>0)se(t)}}}function uP(...t){let e=new Map;for(let n of t.flatMap((r)=>r??[]))e.set(Wt(n),n);return e.size>0?[...e.values()]:void 0}function L$(t,e,n,r){if(!db(process.env))return;return async(i,o)=>{let s=de(ne(e,r(i),n.palettes)),{saved:a}=await M$(t,s,o);return{...a?{note:a}:{},count:fe(t,e).length}}}async function T$(t){let e=process.stdout.isTTY===!0,n=Yn(process.env,e)??fr(process.env,e,Y()),r=n?await n.saved():new Map,i=n?.look?{look:(o)=>n.look?.(t.name,o)}:n?{only:n.slots}:{};try{return await e$(t,{color:!zt(),...i})}finally{if(n)process.stdout.write(n.restore(r))}}async function A$(t,e,n){let r=Y(),i=ct(r),o=await Yw(r,n),s=t.includes("/")?t:`${o.id}/${t}`,a=ve(s);if(a)throw Error(`${s} ${a}`);if(rt(s)!==o.id)throw Error(`palettes in ${o.dir} are named ${o.id}/<palette> — ${s} belongs elsewhere`);let c=bl(r,s);if(ys(c))throw Error(`${s} already exists — \`ttheme edit ${s}\` changes it`);let u=e?hn(wt(r,i).palettes,e):void 0;if(!Sd())throw Error("new opens the palette editor — run it in a terminal");let l=u&&(rt(u.name)?u.base:u.default?void 0:u.name),f=u?wl(u,s,`kept from ${u.name}`):void 0,d=u?Xa(r,u.name)??u.pictures:void 0,{base:m,ansiSource:g,group:$,...w}=f??{name:s,signature:cP,..._r(bc)},b=x$(r,s),v=({colors:I,signature:P})=>{let O=uP(d,b.fresh());return $l({...w,...I,signature:P,...l?{base:l}:{},...O?{pictures:O}:{}})},R=await T$({title:"New palette",name:s,...f?{colors:f}:{},signature:w.signature,...w.waive?{waive:w.waive}:{},palettes:F$(r,i,s),pictures:b.count(),find:L$(r,s,i,v),check:(I)=>H$(()=>ne(s,v(I),i.palettes))});if(!R){b.discard(),console.log("Nothing made");return}iP(oP(c),{recursive:!0}),x(c,v(R));let{state:S}=sP(r,i,[s]);console.log(` + ${s}${u?` from ${u.name}`:""}
524
+ ${c}`),await gn(r,wt(r,i).palettes.filter((I)=>I.name===s),S.terminals),console.log(`
525
+ \`ttheme use ${s}\` wears it · \`ttheme edit ${s}\` opens it again`)}function lP(t,e,n){let r=de(ne(t,e,n.palettes));return Ho(r).length>0?No(r).filter((i)=>i.startsWith(" ✗")):[]}async function C$(t){let e=Y(),n=ct(e),r=B(e),i=wt(e,n,!1),o=R$(t,e),s=Nc(e,o),a=s&&ys(s)?o:i.palettes.some((b)=>b.name===t)?t:o,c=Nc(e,a);if(!c||!ys(c)){let b=i.palettes.some((v)=>v.name===a);throw Error(b?`${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(!Sd())throw Error("edit opens the palette editor — run it in a terminal");let u=Ed(c,"utf8"),l;try{l=ne(a,u,n.palettes)}catch(b){throw Error(`${c} cannot be read — ${b.message}`)}let f=x$(e,a),d=new Set((l.pictures??[]).map((b)=>Wt(b))),m=({colors:b,signature:v})=>jp(Bp(yl(u,b),v),f.fresh().filter((R)=>!d.has(Wt(R)))),g=await T$({title:"Edit palette",name:a,colors:kl(l),signature:l.signatureSlots,waive:l.waive,palettes:F$(e,n,a),pictures:f.count(),find:L$(e,a,n,m),check:(b)=>H$(()=>ne(a,m(b),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let $=m(g);if($===u){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(x(c,$),r.palettes.includes(a))At(e,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let w=lP(a,$,n);if(w.length>0)console.log(`
511
526
  It misses the contrast gate:
512
- ${p.join(`
527
+ ${w.join(`
513
528
  `)}
514
- \`ttheme check --fix ${a}\` suggests colors that pass`)}function Y0(e,t,n){return Ar(e.palettes,e.palettes.some((r)=>r.name===t)?t:W0(t,n))}function Q0(e,t=!1){let n=ue(),r=We(n),i=ne(n),s=Y0(Ke(n,r),e,n);if(console.log(`${s.name} · ${s.group}
515
- `),console.log(As(s).join(`
516
- `)),Cs(s).length===0)return console.log(`
517
- Passes the gate`),0;let{theme:a,moves:u,left:c}=$u(Sn(s));if(u.length===0)return console.log(`
529
+ \`ttheme check --fix ${a}\` suggests colors that pass`)}function j$(t,e,n){return hn(t.palettes,t.palettes.some((r)=>r.name===e)?e:R$(e,n))}function G$(t,e=!1){let n=Y(),r=ct(n),i=B(n),o=j$(wt(n,r),t,n);if(console.log(`${o.name} · ${o.group}
530
+ `),console.log(No(o).join(`
531
+ `)),Ho(o).length===0)return console.log(`
532
+ Passes the gate`),0;let{theme:a,moves:c,left:u}=pc(Se(o));if(c.length===0)return console.log(`
518
533
  No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
519
- ${c.length===0?"These colors pass":"These colors come closer"}:
520
- ${qN(u).join(`
521
- `)}`);let l=Tu(n,s.name);if(!l||!So(l))return console.log(`
522
- \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
523
- \`ttheme check --fix ${s.name}\` writes them`),1;if(K(l,gl(ad(l,"utf8"),hl(a))),i.palettes.includes(s.name))mt(n,r,i);return console.log(`
524
- Wrote ${l}`),c.length===0?0:1}function Tu(e,t){let n=Me(t);return n&&xr(e,!1).some((r)=>r.id===n)?ll(e,t):void 0}function QN(e,t){let n=Tu(e,t.name),r=n&&So(n)?vt(t.name,ad(n,"utf8"),[t]).waiveReason:void 0,i=tu(e,t.name)??t.pictures,{pictures:s,...o}=fl(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Z0(e){let t=ue(),n=fp(QN(t,Y0(Ke(t,We(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
525
- Anyone with ttheme wears it with: ttheme add ${In}…`)}function Hu(e){console.log(`
526
- ${e} palettes installed — open a new tab, or reload your terminal config`)}function XN(e,t){return e.map((n)=>{if(n.startsWith(In))return n;let r=Me(n);if(r===void 0)return t===ee?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 X0(e,t){let n=ue(),r=t?XN(e,(await mf(n,t)).id):e,i=We(n),s=[...new Set(r.map((l)=>l.startsWith(In)?U0(n,l,i):l))],o=ne(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){mt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};gn(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Rn(n,Ke(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Hu(c.palettes.length)}function D0(e){let t=ue(),n=We(t),r=ne(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))};gn(t,n,r,o),Za(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Hu(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function e$(e){let t=ue(),n=We(t),r=ne(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=gn(t,n,r,{...s,startup:e},!0);console.log(r$(e,r.terminals,o).join(`
527
- `))}function t$(){let e=ue(),t=ne(e),n=Gr(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=gn(e,We(e),t,i);console.log(r$(n,i.terminals,s).join(`
528
- `))}function n$(){let e=ue(),t=ne(e);if(t.off){console.log("Already off");return}let n=gn(e,We(e),t,{...t,off:!0}),r=Gr(t);console.log(`Off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`);for(let i of Ce(t.terminals))if(n.get(i.id)?.restart)console.log(`${i.name} new tabs open on your own profile once ${i.name} restarts`)}function r$(e,t,n){let r=Ce(t).filter((s)=>!s.defaults),i=r.length>0?[`Default ${e} · ${r.map((s)=>s.name).join(", ")} open new tabs with it once their config reloads`]:[];for(let s of Ce(t)){let o=s.defaults?.profile(e);if(o)i.push(n.get(s.id)?.restart?`${s.name} new tabs open with it once ${s.name} restarts — "${o}" is now its default profile`:`${s.name} new tabs open with it — "${o}" is its default profile`)}return i.length>0?i:[`Default ${e} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function i$(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of Ea(e,t.palettes,!1))n.set(r.name,"mine");return n}function s$(e,t=!1){let n=ue(),r=We(n),i=new Set(ne(n).palettes),s=i$(n,r),o=Xe(Ke(n,r).palettes),a=Tr(e?$p(o,e):o),u=(f)=>s.get(f)??"kept";if(t){let f=a.map((d)=>({name:d.name,group:d.group,...d.catalog?{catalog:d.catalog}:{},installed:i.has(d.name),source:u(d.name)}));console.log(JSON.stringify(f,null,2));return}let c=Math.max(...a.map((f)=>f.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let f of a){let d=f.catalog?`${f.group} / ${f.catalog}`:f.group;console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(c)} ${d}${l[u(f.name)]}`)}if(process.stdout.isTTY){let f=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
529
- ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function o$(){let e=ue(),t=Mi(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(d,h)=>`${ye(d)}: ${h.message} — kept the copy from the last update`;for(let d of t.filter(xe))try{console.log(` ${fw(e,d)}`)}catch(h){console.log(` ${n(d,h)}`)}let r=t.filter((d)=>!xe(d)),i=new Set(r),s=wr(),o=()=>s.set(`Updating ${[...i].map(ye).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(o(),await Promise.all(r.map(async(d)=>{let h;try{h=cf(await eo(e,d))}catch(g){h=n(d,g)}if(i.delete(d),i.size>0)o();else s.done();s.say(` ${h}`)})),s.done(),!ZN(tr(e)))return;let a=We(e),u=ne(e),c=i$(e,a),l=u.palettes.filter((d)=>!c.has(d)),f=new Map(Nn(e).map((d)=>[d.name,d.pictures]));mt(e,a,u);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await Rn(e,Ke(e,a,!1).palettes.filter((d)=>u.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Ci(d,f.get(d.name))),u.terminals)}async function ud(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Tr(e.palettes),s=process.stdout.isTTY===!0,o=cr(process.env,s)??kr(process.env,s,ue()),a=o?await o.saved():new Map,u=new Nf({entries:i,scope:n,installed:t,required:r,color:!gt(),fx:au(process.env.TTHEME_FX),onFocus:o?(l)=>process.stdout.write(o.paint(l)):void 0}),c=await u.prompt();if(o)process.stdout.write(o.restore(a));if(ht(c))return;return e.palettes.filter((l)=>u.picked.has(l.name)).map((l)=>l.name)}function cd(e,t,n,r){let i;try{i=Wi(e,n)}catch{i=yt(n)?er(n):ye(n)}let s=[];if(xe(n))try{s=sr(n,i,Gi(e,ee),!1)}catch{s=[]}else s=Gi(e,n);return{source:n,id:i,shown:ye(n),entries:s,auto:nr(n,t.updates),status:wf(e,n,r)}}function xu(e){return e instanceof Error?e.message:String(e)}function eP(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of st(t.markets)){let a=i.get(o)??ye(o),u=n[o],c=Xs(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${to(u.at)}: ${u.error}`});if(o===ee)try{cn(a$(Vt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ye(Vt(e))}: ${xu(l)}`})}else if(yt(o))if(!DN(qt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{or(e,o)}catch(l){s.push({where:a,source:o,message:`${ye(qt(e,o))}: ${xu(l)}`})}else try{let l=Et(un(o)),f=new Map;for(let d of ir(o))try{let h=xs(d,f);if(h)throw Error(h);f.set(d.slug,d),vt(`${l}/${d.slug}`,a$(d.path,"utf8"),Gi(e,ee))}catch(h){s.push({where:ye(d.path),message:xu(h)})}}catch(l){s.push({where:a,message:xu(l)})}}return s}function tP(e,t,n,r){return{refresh:async(i)=>{if(xe(i)){let o=cd(e,t,i,On());return{market:o,refreshed:{source:i,id:o.id,count:Xe(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await eo(e,i,af);return{market:cd(e,t,i,On()),refreshed:s}},fetch:async(i)=>{if(xe(i)){let o=Et(un(i));return{source:i,id:o,shown:ye(i),entries:sr(i,o,Gi(e,ee),!1),auto:!1,status:"read in place"}}let s=await Ds(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ye(i),entries:s.entries,auto:nr(i,{}),status:"not added yet"}},search:(i)=>kf(i,r)}}function nP(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==ee&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${dt(Xe(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} · ${ye(i)}`);let o=n.filter((a)=>(Me(a)??ee)===s);if(o.length>0)r.push(bf(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 rP(e,t,n,r,i){let s=ne(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let m of r.adds){let k=i.get(m.source);if(k)_i(e,k)}for(let m of r.removes)pf(e,m);let a=[...st(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=no(s,a,{...s.updates,...r.auto});if(o)hn(e,u);let c=We(e,!1),l=Ke(e,c,!1).palettes.filter((m)=>r.picked.has(m.name)).map((m)=>m.name),f=s.palettes.filter((m)=>!l.includes(m)),d=l.filter((m)=>!s.palettes.includes(m));if(!o&&d.length===0&&f.length===0){await ru(e,s,t,r.refreshed),console.log("Nothing changed");return}let h={...u,palettes:l};gn(e,c,s,h),Za(e,c,s.terminals,f);for(let m of nP(r,n,l))console.log(m);for(let m of d)console.log(` + ${m}`);for(let m of f)console.log(` - ${m}`);let g=new Map(t.map((m)=>[m.name,m.pictures])),b=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),p=Ke(e,c,!1).palettes;if(await Rn(e,[...p.filter((m)=>d.includes(m.name)),...p.filter((m)=>l.includes(m.name)&&!d.includes(m.name)&&b.has(m.name)&&g.has(m.name)).map((m)=>Ci(m,g.get(m.name)))],h.terminals),d.length>0||f.length>0)Hu(h.palettes.length)}async function u$(){let e=ue(),t=ne(e),n=Nn(e),r=On(),i=st(t.markets).map((p)=>cd(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((m)=>m.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0,l=cr(process.env,c)??kr(process.env,c,e),f=l?await l.saved():new Map,d=Yt(t),h=new Of({markets:i,kept:o,installed:t.palettes,...d?{startup:d}:{},problems:eP(e,t,r,i),due:uf(e,t),io:tP(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Tr},color:!gt(),fx:au(process.env.TTHEME_FX),...l?{onFocus:(p)=>process.stdout.write(l.paint(p))}:{}}),g=await h.prompt();if(l)process.stdout.write(l.restore(f));u.abort(),await h.idle();let b=h.result();for(let p of b.refreshed){let m=lf(p);if(m)console.log(m)}if(ht(g)){await ru(e,ne(e),n,b.refreshed),console.log("Nothing changed");return}await rP(e,n,i,b,a)}import{rmSync as c$}from"node:fs";import{basename as iP,join as Io}from"node:path";var l$=Io(import.meta.dirname,".."),sP=Io(l$,"themes"),ld=Io(l$,"dist"),Au=St.map((e)=>br[e].emitter),oP=[Tl,sl],w8=Au.map((e)=>e.id);async function Lu({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?Au.filter((s)=>e.includes(s.id)):Au,n=vm(sP),r=kh(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===Au.length)c$(ld,{recursive:!0,force:!0});else for(let s of t)c$(Io(ld,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...oP]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(Io(ld,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>iP(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
530
- ${n.length} themes (${Mm(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{readFileSync as g$}from"node:fs";import{availableParallelism as aP,homedir as f$}from"node:os";var uP=4;async function Cu(e,t,n=f$()){let r=ct(Se(e)),i=Lr(e),s=new Map(ln(e).palettes.map((f)=>[f.name,Ps(f)])),o=Object.entries(r.palettes).flatMap(([f,d])=>{let h=s.get(f);return h?d.pictures.filter((g)=>Rs(g)||(g.blur??0)!==i).map((g)=>({name:f,key:g.key,paint:h})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=Wr(ne(e).terminals),u=new td(Math.min(uP,aP()-1)),c=await u.map(o.map(({name:f,key:d,paint:h})=>({job:"redraw",home:e,user:n,name:f,key:d,paint:h,blur:i,aligns:a})));u.close();let l=[];return c.forEach((f,d)=>{let{name:h,key:g}=o[d];if(f instanceof Error||f===null){t(` ▢ ${h} ${g} — ${f instanceof Error?f.message:"no original to draw it from"}, left as it was`);return}l.push({name:h,picture:f})}),il(e,l),Nt(e,n),l.length}async function d$(e,t,n,r,i=f$()){let s=ct(Se(e)).palettes[t],o=s?.pictures.find((l)=>l.key===(r??s.active));if(!s||!o)throw Error(`${t} has no picture ${r??"shown"}`);if(Dn(o)===n)return{key:o.key,changed:!1};let a=ln(e).palettes.find((l)=>l.name===t);if(!a)throw Error(`no palette called ${t}`);let u=Wr(ne(e).terminals),c=await nu(e,t,o.key,Ps(a),Lr(e),u,i,n);if(!c)throw Error(`${t} ${o.key} has no original to draw it from`);return il(e,[{name:t,picture:c}]),Nt(e,i),{key:o.key,changed:!0}}async function h$(){return await Cu(ue(),(e)=>process.stderr.write(`${e}
531
- `)),0}async function m$(e,t,n){let r=ue();if(Ar(ln(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=Ei(r,e,n);return Nt(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
532
- `),0}if(t==="drop"){let{key:i,left:s}=pa(r,e,n);return Nt(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
533
- `),0}if(t==="tone"||t==="original"){let i=await d$(r,e,t,n);return process.stderr.write(`Background · ${e} ${i.key} ${t==="tone"?"tinted":"in its own colors"}
534
- `),0}if(t==="tuned")return Nt(r),0;throw Error(`unknown image action ${t} — show, drop, tone, original or tuned`)}function p$(e,t){let n=/^(\d+)x(\d+)$/.exec(e),r=/^(\d+)x(\d+)([+-]\d+)([+-]\d+)$/.exec(t);if(!n||!r)throw Error("a canvas is <width>x<height> and a place <width>x<height>+<x>+<y>");let[i,s]=n.slice(1).map(Number),[o,a,u,c]=r.slice(1).map(Number);return{width:i,height:s,at:{x:u,y:c,w:o,h:a}}}function cP(e,t,n){let r=p$(t,n),i=Math.min(1,e.width/r.at.w);if(i===1)return r;return{width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*i)),at:{x:Math.round(r.at.x*i),y:Math.round(r.at.y*i),w:e.width,h:e.height}}}function b$(e,t,n,r){let i=At(new Uint8Array(g$(e)));return K(t,Cg(Rg(i,p$(n,r)))),0}function w$(e,t,n,r,i,s){let o=Number(r);if(!Ht(n)||!Number.isFinite(o))throw Error("flatten needs a #rrggbb background and an opacity from 0 to 1");let a=At(new Uint8Array(g$(e))),u=i===void 0?void 0:cP(a,i,s??"");return K(t,zo(Vo(a,n,Math.max(0,Math.min(1,o)),u))),0}import{execFileSync as lP}from"node:child_process";import{readFileSync as fP}from"node:fs";import{arch as dP,platform as _u,release as fd}from"node:os";var hP={ghostty:"ghostty",iterm2:"iTerm.app",wezterm:"WezTerm","terminal-app":"Apple_Terminal",warp:"WarpTerminal"};function gP(e,t){if(e==="konsole"){let r=/^(\d{2})(\d{2})(\d{2})$/.exec(t.KONSOLE_VERSION??"");return r?`${r[1]}.${r[2]}.${Number(r[3])}`:t.KONSOLE_VERSION}let n=hP[e];return n!==void 0&&t.TERM_PROGRAM===n?t.TERM_PROGRAM_VERSION:void 0}function mP(e){let t=Mt(e),n=e.TERM_PROGRAM&&e.TERM_PROGRAM!=="tmux"?e.TERM_PROGRAM:void 0,r=t==="unknown"?`unknown${n?` (TERM_PROGRAM=${n})`:""}`:t==="editor"?`editor (${Sl(e)})`:`${t} ${gP(t,e)??"(version unknown)"}`,i=e.TERM_PROGRAM==="tmux"?e.TERM_PROGRAM_VERSION:void 0;return[r,e.TMUX?`tmux ${i??"yes"}`:"tmux no",e.SSH_CONNECTION||e.SSH_TTY?"ssh yes":"ssh no"].join(" · ")}function $$(e,t){try{return lP(e,t,{encoding:"utf8",timeout:2000,stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function pP(){let e=dP();if(_u()==="darwin")return`macOS ${$$("sw_vers",["-productVersion"])??`(Darwin ${fd()})`} · ${e}`;if(_u()==="linux"){let t="";try{t=fP("/etc/os-release","utf8")}catch{}return`${/^PRETTY_NAME="?([^"\n]*)"?$/m.exec(t)?.[1]??"Linux"} · linux ${fd()} · ${e}`}return`${_u()==="win32"?"Windows":_u()} ${fd()} · ${e}`}function bP(e){if(e.TTHEME_ZSH)return`zsh ${e.TTHEME_ZSH}`;return(e.SHELL?$$(e.SHELL,["--version"])?.split(`
535
- `)[0]:void 0)??e.SHELL??"unknown"}function wP(e){try{let{terminals:t}=ne(e);return t.length>0?t.join(", "):"none"}catch{return"installed.json missing or unreadable"}}function $P(e){let t=Ra.flatMap((n)=>{let r=e[n];return r===void 0||r===Us(n)?[]:[`${n}=${/\s/.test(r)?JSON.stringify(r):r}`]});return t.length>0?t.join(" "):void 0}function k$(){let e=process.env,n=[["ttheme",et.version],["OS",pP()],["Shell",bP(e)],["Terminal",mP(e)],["Wired",wP(ue())],["Settings",$P(e)]].filter((i)=>i[1]!==void 0),r=Math.max(...n.map(([i])=>i.length));for(let[i,s]of n)console.log(`${i.padEnd(r)} ${s}`)}import{execFileSync as kP,spawnSync as yP}from"node:child_process";import{chmodSync as EP,copyFileSync as vP,existsSync as Qr,mkdirSync as y$,readdirSync as MP,readFileSync as Wu,rmSync as dd}from"node:fs";import{homedir as SP}from"node:os";import{dirname as zi,join as Ue}from"node:path";function IP(e,t,n){for(let r of MP(t))e.push({from:Ue(t,r),to:Ue(n,r)})}function pd(e){return JSON.parse(Wu(Ue(e,"dist","manifest.json"),"utf8"))}function Gu(e,t){let n=Ue(t.configHome,"ttheme"),r=[{from:Ue(t.root,"bin","ttheme.js"),to:Ue(n,"ttheme.js")},{from:Ue(t.root,"bin","ttheme.js.map"),to:Ue(n,"ttheme.js.map")},{from:Ue(t.root,"shell","ttheme.zsh"),to:Ue(n,"ttheme.zsh")},{from:Ue(t.root,"shell","launch-tab.zsh"),to:Ue(n,"launch-tab.zsh"),executable:!0}];IP(r,Ue(t.root,"shell","adapters"),Ue(n,"adapters"));let i=[{file:Ue(t.zdotdir,".zshrc"),block:_p(n)}],s=Ue(n,"config.zsh"),o=Wp(Qr(s)?Wu(s,"utf8"):""),a={file:s,content:e.warpFast===void 0?o:Ta(o,"TTHEME_WARP_FAST",e.warpFast?"on":"off")},u={terminals:e.terminals,palettes:e.palettes,...Object.fromEntries(Ce(e.terminals).flatMap((f)=>Object.entries(f.installs?.(t)??{}).filter(([,d])=>d!==void 0))),...e.off?{off:!0}:{}},c=Ab(t.configHome,u,t.home),l=t.stateDir?[Ue(t.stateDir,"ghostty",".blind")]:[];return{home:t.home,copies:r,edits:i,settings:a,forget:l,catalog:pd(t.root),installed:u,notes:c}}function v$(e){try{return ne(e)}catch{return}}function M$(e){try{return Ke(e,We(e),!1).palettes}catch{return[]}}function NP(e,t){let n=pd(t.root),r=st(e.markets).includes(ee)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=M$(t.configHome).filter((o)=>!i.has(o.name)&&(Me(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function S$(e,t){let n=Gr(e);return n&&t.includes(n)?n:void 0}function PP(e,t,n){let r=Gu(t,n),i=S$(e,t.palettes),s=new Set(["terminals","palettes","off","startup",...St.flatMap((a)=>Object.keys(br[a].installs?.(n)??{}))]),o=Object.fromEntries(Object.entries(e).filter(([a])=>!s.has(a)));return{...r,installed:{...o,...r.installed,...i?{startup:i}:{}}}}function RP(e,t){let n=Gu({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...M$(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 OP(e){try{return kP(process.execPath,[Ue(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function I$(e){let t=Yt(e);return[Ce(e.terminals).map((n)=>n.name).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function hd(e,t=Cr()){for(let o of e.copies)if(y$(zi(o.to),{recursive:!0}),dd(o.to,{force:!0}),dd(`${o.to}.zwc`,{force:!0}),vP(o.from,o.to),o.executable)EP(o.to,493);K(e.settings.file,e.settings.content);for(let o of e.forget)dd(o,{force:!0});let n=zi(zi(e.settings.file)),r=v$(n),i=Object.fromEntries(Ce(e.installed.terminals).flatMap((o)=>{let a=o.defaults?.key,u=a?r?.[a]:void 0;return a&&u?[[a,u]]:[]})),s=rf(n,{...e.installed,...i},t,e.home);if(st(s.markets).includes(ee))va(n,e.catalog);hn(n,s),mt(n,We(n),s,e.home);for(let o of e.edits){y$(zi(o.file),{recursive:!0});let a=Qr(o.file)?Wu(o.file,"utf8"):"";en(o.file,lr(a,o.block))}return Qs(n,s,!0,t,e.home)}class yr extends Error{}function No(e){if(ht(e))throw ti("Nothing changed"),new yr;return e}function gd(e,t){return St.filter((n)=>br[n].offered(e,t))}async function FP(e,t,n,r){return No(await lh({message:"Wire which terminals?",options:gd(n,r).map((i)=>({value:i,label:br[i].name,hint:i===e?"detected":void 0})),initialValues:t,required:!0}))}async function TP(e){return No(await bn({message:"Switch Warp to each tab's palette in about 0.2 s instead of 0.6 s?\nAbout 8% CPU while Warp is in front with tabs of different palettes — `ttheme config` changes it",initialValue:Oa(e,"TTHEME_WARP_FAST")!=="off"}))}function md(e){let t=[...e.copies.filter((n)=>!Qr(n.to)).map((n)=>n.to),...Qr(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!Wu(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
536
- ${t.join(`
537
- `)}`)}function N$(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function HP(e,t,n){let r=e.palettes.find((o)=>o.name===Yt(t)),i=process.stdout.isTTY===!0,s=r&&(cr(process.env,i)??kr(process.env,i,n))?.wear(r,t.terminals);if(s===void 0)return!1;return process.stdout.write(s),!0}function xP(e,t){let n=Yt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Gr(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function AP(e){yP("zsh",["-c",'source "$1" && __tt_preview init',"zsh",Ue(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function LP(e,t,n,r){let i=N$(e.catalog,t.palettes);vr([`${i.join(", ")} (${t.palettes.length})`,...xP(e.installed,n)].join(`
538
- `),`Installed ${t.palettes.length} palettes`),vr(["exec zsh The ttheme command in this tab",...bd(e,r)].join(`
539
- `),"Next"),rc("Done")}function bd(e,t){return[...Lb(zi(zi(e.settings.file)),e.installed,t,e.home),...e.notes]}function P$(e){return e?(t)=>xn.step(t):(t)=>console.log(t)}async function E$(e,t,n,r){let i=RP(e,t),s=hd(i,n);md(i),await Cu(t.configHome,P$(r),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...bd(i,s)],a=`Updated to ${et.version} — kept ${I$(i.installed)}`;if(!r){console.log([a,...o].join(`
540
- `));return}vr(o.join(`
541
- `),a),rc("Done")}function CP(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}`),...bd(e,t),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
542
- `))}async function R$(e={}){let t=Ue(import.meta.dirname,"..");if(!Qr(Ue(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Qr(Ue(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Lu()}let n=SP(),r=ue(),i=process.env.ZDOTDIR??n,s=Cr(),o=Pb(s),a=process.env.WT_PROFILE_ID,u={root:t,home:n,configHome:r,zdotdir:i,stateDir:Ue(process.env.XDG_STATE_HOME??Ue(n,".local","state"),"ttheme"),...o?{wtHome:o}:{},...a?{wtProfile:a}:{}},c=Mt(process.env),l=gd(u,s).filter(($)=>$===c||br[$].present(u));if(!e.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");let f=v$(r);if(e.yes&&f){await E$(f,u,s,!1);return}if(e.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${Ce(gd(u,s)).map((F)=>F.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let N=Gu({terminals:l,palettes:[]},u),R=hd(N,s);md(N),CP(N,R);return}if(Wo("ttheme init"),f){let $=OP(r);if(No(await bn({message:`ttheme${$?` ${$}`:""} is installed — ${I$(f)}
543
- ${$===et.version?"Reinstall":"Update to"} ${et.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await E$(f,u,s,!0);return}}let d=await FP(c,f?.terminals??l,u,s),h=d.includes("warp")?await TP(r):void 0,g=f?NP(f,u):pd(t),b=f?await ud(g,f.palettes,"palette",!0):await ud(g,[],"series",!0);if(!b)throw ti("Nothing changed"),new yr;let p=(f&&S$(f,b))??b[0],m=b.length>1&&(zt[c].paints||c==="warp"&&d.includes("warp")&&Qr(mr(n,r))),k=No(await bn({message:m?"Pick a default palette in ttheme preview once installed?":`Wear ${p} in every tab?`,initialValue:f?!f.off:!0})),v={terminals:d,palettes:b,off:!k,warpFast:h},M=f?PP(f,v,u):Gu(v,u);if(vr([`Install ${b.length} palettes — ${N$(g,b).join(", ")}`,`Copy ${M.copies.length} files under ${r}`,`Write ${M.settings.file}`,...M.edits.map(($)=>`Edit ${$.file} — a ttheme block: source ttheme.zsh`),...xb(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",k?m?`Open ttheme preview — every tab wears the palette picked there, ${p} until then`:`Paint every tab with ${p}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...k&&p?Ce(d).flatMap(($)=>$.defaults?[`Make "${$.defaults.profile(p)}" the ${$.name} default profile`]:[]):[]].join(`
544
- `),`Wiring ${Ce(d).map(($)=>$.name).join(", ")}`),!No(await bn({message:"Apply these changes?"})))throw ti("Nothing changed"),new yr;let w=hd(M,s);if(md(M),await Cu(r,P$(!0),n),k&&m)AP(r);let I=ne(r);LP({...M,catalog:g,installed:I},v,HP(g,I,r),w)}import{existsSync as O$,rmSync as _P,utimesSync as GP}from"node:fs";import{homedir as WP}from"node:os";import{join as Po}from"node:path";function UP(e){try{return ne(e)}catch{return}}function jP(e){let{home:t,configHome:n}=e,r=UP(n),i={configHome:n,home:t},s=Ce(St),o=s.map((u)=>u.unwire(i,r)),a=[Po(n,"ttheme"),e.cacheDir,e.stateDir];return{edits:[...fn(Po(e.zdotdir,".zshrc"),fr),...o.flatMap((u)=>u.edits)],removals:[...s.flatMap((u)=>u.shelf?xa(u.shelf.dir(i)):[]),...o.flatMap((u)=>u.removals),...a.filter((u)=>O$(u))],touches:o.flatMap((u)=>u.touches),...r?{state:r}:{}}}function KP(e,t,n=Cr()){let r=[];for(let{file:s,content:o}of e.edits){let a=vh(s,o);r.push(a==="removed"?`Removed ${s} — ttheme had created it`:a==="restored"?`Took ttheme out of ${s}`:`Took ttheme out of ${s} — kept ${s}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state){let s=Qs(t.configHome,{...e.state,off:!0,palettes:[]},!1,n,t.home);for(let o of Ce(e.state.terminals))if(s.has(o.id))r.push(`Gave ${o.name} its own default profile back — it takes it at its next start`)}for(let s of e.removals)_P(s,{recursive:!0,force:!0});if(e.removals.length>0)r.push(`Deleted ${e.removals.length} files and folders ttheme wrote`);let i=new Date;for(let s of e.touches)GP(s,i,i);return r}function BP(){let e=WP();return{home:e,configHome:ue(),zdotdir:process.env.ZDOTDIR??e,cacheDir:pi(),stateDir:Po(process.env.XDG_STATE_HOME??Po(e,".local","state"),"ttheme")}}async function F$(e=!1){let t=BP(),n=jP(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=Po(t.configHome,"ttheme");Wo("ttheme uninstall"),vr([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${O$(ka(t.configHome))?`, and your markets under ${ka(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
545
- `),"Uninstall");let i=await bn({message:"Remove ttheme?"});if(ht(i)||!i)throw ti("Nothing changed"),new yr}for(let r of KP(n,t))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var qP=new Set(["add","remove","market","default","on","off"]),VP={default:([e])=>e$(e),on:()=>t$(),off:()=>n$(),browse:()=>u$(),list:([e],{json:t})=>s$(e,t),add:(e,{market:t})=>X0(e,t),remove:(e)=>D0(e),update:()=>o$(),market:([e,t])=>lw(e,t),new:([e],{from:t,in:n})=>V0(e,t,n),edit:([e])=>z0(e),check:([e],{fix:t})=>Q0(e,t),share:([e])=>Z0(e),init:(e,{yes:t})=>R$({yes:t}),uninstall:(e,{yes:t})=>F$(t),info:()=>k$(),build:(e,{only:t})=>Lu({only:t}),find:([e])=>L0(e),image:([e,t,n])=>m$(e,t,n),redraw:()=>h$(),flatten:([e,t,n,r,i,s])=>w$(e,t,n,r,i,s),bake:([e,t,n,r])=>b$(e,t,n,r)},zP=Gs.map((e)=>({...e,run:VP[e.name]}));class Zr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function T$(e){let t=zP.find((n)=>n.name===e);if(!t)throw new Zr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function YP(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 JP({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Zr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function QP(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:T$(n[0]),code:0}}let r=T$(t),i=YP(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:f}]of Object.entries(r.flags??{}))for(let d of[i.values[l]??[]].flat())if(f&&!f.includes(String(d)))throw new Zr(`--${l} takes ${f.join(", ")} — not ${d}`,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 Zr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new Zr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function H$(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function wd(e,t=!1){if(!e)return Ws(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${_s(e)}`,"",e.about,...e.actions?["","Actions:",...H$(e.actions)]:[],...n.length>0?["","Options:",...H$(n)]:[]].join(`
546
- `)}var ZP=[TypeError,RangeError,ReferenceError,SyntaxError];function XP(e){return ZP.some((t)=>e instanceof t)||e instanceof Error&&"code"in e}async function x$(e){let t;try{let n=QP(e);if(n.kind==="version")return console.log(et.version),0;if(n.kind==="help"){if(n.code===0)console.log(wd(n.verb,n.all));else console.error(wd(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(qP.has(n.verb.name))await zb();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Zr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
534
+ ${u.length===0?"These colors pass":"These colors come closer"}:
535
+ ${aP(c).join(`
536
+ `)}`);let l=Nc(n,o.name);if(!l||!ys(l))return console.log(`
537
+ \`ttheme new <name> --from ${o.name}\` makes a copy you can fix`),1;if(!e)return console.log(`
538
+ \`ttheme check --fix ${o.name}\` writes them`),1;if(x(l,yl(Ed(l,"utf8"),kl(a))),i.palettes.includes(o.name))At(n,r,i);return console.log(`
539
+ Wrote ${l}`),u.length===0?0:1}function Nc(t,e){let n=rt(e);return n&&Pr(t,!1).some((r)=>r.id===n)?bl(t,e):void 0}function fP(t,e){let n=Nc(t,e.name),r=n&&ys(n)?ne(e.name,Ed(n,"utf8"),[e]).waiveReason:void 0,i=Xa(t,e.name)??e.pictures,{pictures:o,...s}=wl(e,e.name,r);return{...s,...i?{pictures:i}:{}}}async function dP(t,e,n){if(t===e)return e;let r=n;if(r===void 0)if(!Sd())r="tuned";else{let i=await Th({message:`Share ${e.name} as…`,options:[{value:"tuned",label:"Your tone",hint:`named ${Oc(e.name)}`},{value:"original",label:"The original"}]});if(Lt(i))throw new Pe;r=i}return r==="original"?e:t}function Oc(t){return`${t}-tuned`}async function U$(t,e){let n=Y(),r=ct(n),i=j$(Hr(n,r),t,n),o=Ro(i,fn(n)[i.name]),s=await dP(o,i,e),a=fP(n,s),c=s===o&&o!==i;if(c){let u=ve(Oc(s.name));if(u)throw Error(`${Oc(s.name)} ${u} — share the original, or tune a palette with a shorter name`);a.name=Oc(s.name)}if(console.log(Wp(a)),process.stdout.isTTY)console.error(`
540
+ Anyone with ttheme wears it with: ttheme add ${ln}…${c?`
541
+ It carries your tone, named ${a.name} so it does not clash with ${s.name}`:""}`)}function Rc(t){console.log(`
542
+ ${t} palettes installed — open a new tab, or reload your terminal config`)}function mP(t,e){return t.map((n)=>{if(n.startsWith(ln))return n;let r=rt(n);if(r===void 0)return e===J?n:`${e}/${n}`;if(r!==e)throw Error(`${n} is not in ${e} — give its bare name, or leave --market out`);return n})}async function W$(t,e){let n=Y(),r=e?mP(t,(await Sf(n,e)).id):t,i=ct(n),o=[...new Set(r.map((l)=>l.startsWith(ln)?P$(n,l,i):l))],s=B(n),a=o.filter((l)=>s.palettes.includes(l)),c=o.filter((l)=>!s.palettes.includes(l));if(c.length===0){At(n,i,s),console.log(`Already installed: ${a.join(", ")}`);return}let u={...s,palettes:[...s.palettes,...c]};Ye(n,i,s,u);for(let l of c)console.log(` + ${l}`);await gn(n,wt(n,i,!1).palettes.filter((l)=>c.includes(l.name)),u.terminals),Rc(u.palettes.length)}function _$(t){let e=Y(),n=ct(e),r=B(e),i=t.filter((a)=>r.palettes.includes(a)),o=t.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${o.join(", ")} — \`ttheme list\` marks what is`);let s={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};Ye(e,n,r,s),Ya(e,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Rc(s.palettes.length),o.length>0)return console.error(`ttheme remove: not installed: ${o.join(", ")}`),1;return 0}function B$(t){let e=Y(),n=ct(e),r=B(e);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{off:i,...o}=r,s=Ye(e,n,r,{...o,startup:t},!0);console.log(q$(t,r.terminals,s).join(`
543
+ `))}function z$(){let t=Y(),e=B(t),n=Lr(e);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!e.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=e,o=Ye(t,ct(t),e,i);console.log(q$(n,i.terminals,o).join(`
544
+ `))}function K$(){let t=Y(),e=B(t);if(e.off){console.log("Already off");return}let n=Ye(t,ct(t),e,{...e,off:!0}),r=Lr(e);console.log(`Off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`);for(let i of ft(e.terminals))if(n.get(i.id)?.restart)console.log(`${i.name} new tabs open on your own profile once ${i.name} restarts`)}function q$(t,e,n){let r=ft(e).filter((o)=>!o.defaults),i=r.length>0?[`Default ${t} · ${r.map((o)=>o.name).join(", ")} open new tabs with it once their config reloads`]:[];for(let o of ft(e)){let s=o.defaults?.profile(t);if(s)i.push(n.get(o.id)?.restart?`${o.name} new tabs open with it once ${o.name} restarts — "${s}" is now its default profile`:`${o.name} new tabs open with it — "${s}" is its default profile`)}return i.length>0?i:[`Default ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function J$(t,e){let n=new Map(e.palettes.map((r)=>[r.name,"market"]));for(let r of ga(t,e.palettes,!1))n.set(r.name,"mine");return n}function Y$(t,e=!1){let n=Y(),r=ct(n),i=new Set(B(n).palettes),o=J$(n,r),s=Mt(wt(n,r).palettes),a=Nr(t?tb(s,t):s),c=(f)=>o.get(f)??"kept";if(e){let f=a.map((d)=>({name:d.name,group:d.group,...d.catalog?{catalog:d.catalog}:{},installed:i.has(d.name),source:c(d.name)}));console.log(JSON.stringify(f,null,2));return}let u=Math.max(...a.map((f)=>f.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let f of a){let d=f.catalog?`${f.group} / ${f.catalog}`:f.group;console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(u)} ${d}${l[c(f.name)]}`)}if(process.stdout.isTTY){let f=t?`${a.length} of ${s.length}`:`${s.length}`;console.log(`
545
+ ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function D$(){let t=Y(),e=Si(t);if(e.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(d,m)=>`${et(d)}: ${m.message} — kept the copy from the last update`;for(let d of e.filter(ut))try{console.log(` ${Zw(t,d)}`)}catch(m){console.log(` ${n(d,m)}`)}let r=e.filter((d)=>!ut(d)),i=new Set(r),o=sr(),s=()=>o.set(`Updating ${[...i].map(et).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(s(),await Promise.all(r.map(async(d)=>{let m;try{m=wf(await Yo(t,d))}catch(g){m=n(d,g)}if(i.delete(d),i.size>0)s();else o.done();o.say(` ${m}`)})),o.done(),!hP(Wn(t)))return;let a=ct(t),c=B(t),u=J$(t,a),l=c.palettes.filter((d)=>!u.has(d)),f=new Map(dn(t).map((d)=>[d.name,d.pictures]));At(t,a,c);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await gn(t,wt(t,a,!1).palettes.filter((d)=>c.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Ai(d,f.get(d.name))),c.terminals)}async function Md(t,e,n,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:Nr(t.palettes),o=process.stdout.isTTY===!0,s=Yn(process.env,o)??fr(process.env,o,Y()),a=s?await s.saved():new Map,c=new Af({entries:i,scope:n,installed:e,required:r,color:!zt(),fx:ic(process.env.TTHEME_FX),onFocus:s?(l)=>process.stdout.write(s.paint(l)):void 0}),u=await c.prompt();if(s)process.stdout.write(s.restore(a));if(Lt(u))return;return t.palettes.filter((l)=>c.picked.has(l.name)).map((l)=>l.name)}function Id(t,e,n,r){let i;try{i=Gi(t,n)}catch{i=te(n)?Un(n):et(n)}let o=[];if(ut(n))try{o=Kn(n,i,ji(t,J),!1)}catch{o=[]}else o=ji(t,n);return{source:n,id:i,shown:et(n),entries:o,auto:_n(n,e.updates),status:Of(t,n,r)}}function Pc(t){return t instanceof Error?t.message:String(t)}function pP(t,e,n,r){let i=new Map(r.map((s)=>[s.source,s.id])),o=[];for(let s of Ft(e.markets)){let a=i.get(s)??et(s),c=n[s],u=qo(t,s);if(c&&(u===void 0||c.at>u))o.push({where:a,source:s,update:!0,message:`Update failed ${Do(c.at)}: ${c.error}`});if(s===J)try{ze(V$(Ie(t),"utf8"))}catch(l){o.push({where:a,source:s,message:`${et(Ie(t))}: ${Pc(l)}`})}else if(te(s))if(!gP(Me(t,s)))o.push({where:a,source:s,message:"No copy of its index yet — `ttheme update` fetches it"});else try{qn(t,s)}catch(l){o.push({where:a,source:s,message:`${et(Me(t,s))}: ${Pc(l)}`})}else try{let l=ee(Be(s)),f=new Map;for(let d of zn(s))try{let m=Oo(d,f);if(m)throw Error(m);f.set(d.slug,d),ne(`${l}/${d.slug}`,V$(d.path,"utf8"),ji(t,J))}catch(m){o.push({where:et(d.path),message:Pc(m)})}}catch(l){o.push({where:a,message:Pc(l)})}}return o}function bP(t,e,n,r){return{refresh:async(i)=>{if(ut(i)){let s=Id(t,e,i,pn());return{market:s,refreshed:{source:i,id:s.id,count:Mt(s.entries).length,change:{added:[],changed:[],gone:[]}}}}let o=await Yo(t,i,pf);return{market:Id(t,e,i,pn()),refreshed:o}},fetch:async(i)=>{if(ut(i)){let s=ee(Be(i));return{source:i,id:s,shown:et(i),entries:Kn(i,s,ji(t,J),!1),auto:!1,status:"read in place"}}let o=await Jo(i,void 0,r);return n.set(i,o),{source:i,id:o.id,shown:et(i),entries:o.entries,auto:_n(i,{}),status:"not added yet"}},search:(i)=>Rf(i,r)}}function wP(t,e,n){let r=[];for(let i of t.adds){let o=i.source!==J&&(t.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${_t(Mt(i.entries).length)}${o?", updating on its own":""}`)}for(let i of t.removes){let o=e.find((a)=>a.source===i)?.id??i;r.push(`Removed ${o} · ${et(i)}`);let s=n.filter((a)=>(rt(a)??J)===o);if(s.length>0)r.push(If(s))}for(let[i,o]of Object.entries(t.auto)){let s=e.find((a)=>a.source===i);if(s&&!t.removes.includes(i))r.push(`${s.id} ${o?"updates on its own now":"no longer updates on its own"}`)}return r}async function $P(t,e,n,r,i){let o=B(t),s=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let b of r.adds){let v=i.get(b.source);if(v)Ci(t,v)}for(let b of r.removes)Mf(t,b);let a=[...Ft(o.markets).filter((b)=>!r.removes.includes(b)),...r.adds.map((b)=>b.source)],c=Zo(o,a,{...o.updates,...r.auto});if(s)Je(t,c);let u=ct(t,!1),l=wt(t,u,!1).palettes.filter((b)=>r.picked.has(b.name)).map((b)=>b.name),f=o.palettes.filter((b)=>!l.includes(b)),d=l.filter((b)=>!o.palettes.includes(b));if(!s&&d.length===0&&f.length===0){await Vo(t,o,e,r.refreshed),console.log("Nothing changed");return}let m={...c,palettes:l};Ye(t,u,o,m),Ya(t,u,o.terminals,f);for(let b of wP(r,n,l))console.log(b);for(let b of d)console.log(` + ${b}`);for(let b of f)console.log(` - ${b}`);let g=new Map(e.map((b)=>[b.name,b.pictures])),$=new Set(r.refreshed.flatMap((b)=>[...b.change.changed,...b.change.gone])),w=wt(t,u,!1).palettes;if(await gn(t,[...w.filter((b)=>d.includes(b.name)),...w.filter((b)=>l.includes(b.name)&&!d.includes(b.name)&&$.has(b.name)&&g.has(b.name)).map((b)=>Ai(b,g.get(b.name)))],m.terminals),d.length>0||f.length>0)Rc(m.palettes.length)}async function Z$(){let t=rb(process.env),e=Y(),n=B(e),r=dn(e),i=pn(),o=Ft(n.markets).map((v)=>Id(e,n,v,i)),s=new Set(o.flatMap((v)=>v.entries.map((R)=>R.name))),a=r.filter((v)=>n.palettes.includes(v.name)&&!s.has(v.name)),c=new Map,u=new AbortController,l=process.stdout.isTTY===!0,f=Yn(process.env,l)??fr(process.env,l,e),d=f&&!t?await f.saved():new Map,m=Re(n);if(t)process.stdout.write("\x1B[?2026h");let g=new Gf({markets:o,kept:a,installed:n.palettes,...m?{startup:m}:{},...t?{hub:t}:{},problems:pP(e,n,i,o),due:bf(e,n),io:bP(e,n,c,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Nr},color:!zt(),fx:ic(process.env.TTHEME_FX),...f?{onFocus:(v)=>process.stdout.write(f.paint(v))}:{}});if(l&&!t)process.stdout.write("\x1B[?1049h");let $;try{$=await g.prompt()}finally{if(f&&!t)process.stdout.write(f.restore(d));u.abort()}await g.idle();let w=g.result(),b=g.next();if(t&&b!==void 0)return process.stdout.write("\x1B[?25l"),await Vo(e,B(e),r,w.refreshed),b;if(l)process.stdout.write("\x1B[?1049l\x1B[?25h");for(let v of w.refreshed){let R=$f(v);if(R)console.log(R)}if(Lt($))await Vo(e,B(e),r,w.refreshed),console.log("Nothing changed");else await $P(e,r,o,w,c);return t?Sa:0}import{rmSync as Q$}from"node:fs";import{basename as kP,join as vs}from"node:path";var X$=vs(import.meta.dirname,".."),yP=vs(X$,"themes"),Od=vs(X$,"dist"),Hc=ie.map((t)=>or[t].emitter),vP=[Tl,_l],H4=Hc.map((t)=>t.id);async function Fc({only:t}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let e=t&&t.length>0?Hc.filter((o)=>t.includes(o.id)):Hc,n=Vg(yP),r=Kh(n);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(e.length===Hc.length)Q$(Od,{recursive:!0,force:!0});else for(let o of e)Q$(vs(Od,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...e,...vP]){let s=n.flatMap((u)=>o.emit?.(u)??[]),a=o.emitShared?.(n)??[];for(let u of[...s,...a])await Bun.write(vs(Od,u.path),u.content),i++;let c=s.length>0?`${n.length} themes${o.limits?` (${o.limits})`:""}`:a.map((u)=>kP(u.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${c}`)}console.log(`
546
+ ${n.length} themes (${Zg(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{readFileSync as ik}from"node:fs";import{availableParallelism as EP,homedir as tk}from"node:os";var SP=4;async function xc(t,e,n=tk()){let r=Rt(X(t)),i=Qn(t),o=new Map(Oe(t).palettes.map((f)=>[f.name,wi(f)])),s=Object.entries(r.palettes).flatMap(([f,d])=>{let m=o.get(f);return m?d.pictures.filter((g)=>$i(g)||(g.blur??0)!==i).map((g)=>({name:f,key:g.key,paint:m})):[]});if(s.length===0)return 0;e(`Drawing ${s.length} background picture${s.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=Tr(B(t).terminals),c=new gd(Math.min(SP,EP()-1)),u=await c.map(s.map(({name:f,key:d,paint:m})=>({job:"redraw",home:t,user:n,name:f,key:d,paint:m,blur:i,aligns:a})));c.close();let l=[];return u.forEach((f,d)=>{let{name:m,key:g}=s[d];if(f instanceof Error||f===null){e(` ▢ ${m} ${g} — ${f instanceof Error?f.message:"no original to draw it from"}, left as it was`);return}l.push({name:m,picture:f})}),dl(t,l),se(t,n),l.length}async function ek(t,e,n,r,i=tk()){let o=Rt(X(t)).palettes[e],s=o?.pictures.find((l)=>l.key===(r??o.active));if(!o||!s)throw Error(`${e} has no picture ${r??"shown"}`);if(Ee(s)===n)return{key:s.key,changed:!1};let a=Oe(t).palettes.find((l)=>l.name===e);if(!a)throw Error(`no palette called ${e}`);let c=Tr(B(t).terminals),u=await tc(t,e,s.key,wi(a),Qn(t),c,i,n);if(!u)throw Error(`${e} ${s.key} has no original to draw it from`);return dl(t,[{name:e,picture:u}]),se(t,i),{key:s.key,changed:!0}}function nk(t,e,n){let r=Rt(X(t)).palettes[e],i=r?.pictures.find((a)=>a.key===(n??r.active));if(!r||!i)throw Error(`${e} has no picture ${n??"shown"}`);let o=Oe(t).palettes.find((a)=>a.name===e);if(!o)throw Error(`no palette called ${e}`);let s=Ee(i)==="original"?"tone":"original";if(!Nw(t,e,i.key,wi(o),Qn(t),s))throw Error(`${e} ${i.key} has no original to draw it from`);return{key:i.key,coloring:s}}async function rk(){return await xc(Y(),(t)=>process.stderr.write(`${t}
547
+ `)),0}async function ok(t,e,n){let r=Y();if(hn(Oe(r).palettes,t),e==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:o}=yi(r,t,n);return se(r),process.stderr.write(`Background · ${t} ${i}/${o} ${n}
548
+ `),0}if(e==="drop"){let{key:i,left:o}=la(r,t,n);return se(r),process.stderr.write(`Background · ${t} removed ${i} · ${o} left
549
+ `),0}if(e==="tone"||e==="original"){let i=await ek(r,t,e,n);return process.stderr.write(`Background · ${t} ${i.key} ${e==="tone"?"tinted":"in its own colors"}
550
+ `),0}if(e==="prepare"){let{key:i,coloring:o}=nk(r,t,n);return process.stderr.write(`Background · ${t} ${i} ready in ${o==="tone"?"its tone":"its own colors"}
551
+ `),0}if(e==="tuned")return se(r),0;throw Error(`unknown image action ${e} — show, drop, tone, original, prepare or tuned`)}function sk(t,e){let n=/^(\d+)x(\d+)$/.exec(t),r=/^(\d+)x(\d+)([+-]\d+)([+-]\d+)$/.exec(e);if(!n||!r)throw Error("a canvas is <width>x<height> and a place <width>x<height>+<x>+<y>");let[i,o]=n.slice(1).map(Number),[s,a,c,u]=r.slice(1).map(Number);return{width:i,height:o,at:{x:c,y:u,w:s,h:a}}}function MP(t,e,n){let r=sk(e,n),i=Math.min(1,t.width/r.at.w);if(i===1)return r;return{width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*i)),at:{x:Math.round(r.at.x*i),y:Math.round(r.at.y*i),w:t.width,h:t.height}}}function ak(t,e,n,r){let i=le(new Uint8Array(ik(t)));return x(e,je(Dm(i,sk(n,r)))),0}function ck(t,e,n,r,i,o){let s=Number(r);if(!Bt(n)||!Number.isFinite(s))throw Error("flatten needs a #rrggbb background and an opacity from 0 to 1");let a=le(new Uint8Array(ik(t))),c=i===void 0?void 0:MP(a,i,o??"");return x(e,Ks(zs(a,n,Math.max(0,Math.min(1,s)),c))),0}import{execFileSync as IP}from"node:child_process";import{readFileSync as OP}from"node:fs";import{arch as NP,platform as Lc,release as Nd}from"node:os";var RP={ghostty:"ghostty",iterm2:"iTerm.app",wezterm:"WezTerm","terminal-app":"Apple_Terminal",warp:"WarpTerminal"};function PP(t,e){if(t==="konsole"){let r=/^(\d{2})(\d{2})(\d{2})$/.exec(e.KONSOLE_VERSION??"");return r?`${r[1]}.${r[2]}.${Number(r[3])}`:e.KONSOLE_VERSION}let n=RP[t];return n!==void 0&&e.TERM_PROGRAM===n?e.TERM_PROGRAM_VERSION:void 0}function HP(t){let e=re(t),n=t.TERM_PROGRAM&&t.TERM_PROGRAM!=="tmux"?t.TERM_PROGRAM:void 0,r=e==="unknown"?`unknown${n?` (TERM_PROGRAM=${n})`:""}`:e==="editor"?`editor (${Nl(t)})`:`${e} ${PP(e,t)??"(version unknown)"}`,i=t.TERM_PROGRAM==="tmux"?t.TERM_PROGRAM_VERSION:void 0;return[r,t.TMUX?`tmux ${i??"yes"}`:"tmux no",t.SSH_CONNECTION||t.SSH_TTY?"ssh yes":"ssh no"].join(" · ")}function uk(t,e){try{return IP(t,e,{encoding:"utf8",timeout:2000,stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function FP(){let t=NP();if(Lc()==="darwin")return`macOS ${uk("sw_vers",["-productVersion"])??`(Darwin ${Nd()})`} · ${t}`;if(Lc()==="linux"){let e="";try{e=OP("/etc/os-release","utf8")}catch{}return`${/^PRETTY_NAME="?([^"\n]*)"?$/m.exec(e)?.[1]??"Linux"} · linux ${Nd()} · ${t}`}return`${Lc()==="win32"?"Windows":Lc()} ${Nd()} · ${t}`}function xP(t){if(t.TTHEME_ZSH)return`zsh ${t.TTHEME_ZSH}`;return(t.SHELL?uk(t.SHELL,["--version"])?.split(`
552
+ `)[0]:void 0)??t.SHELL??"unknown"}function LP(t){try{let{terminals:e}=B(t);return e.length>0?e.join(", "):"none"}catch{return"installed.json missing or unreadable"}}function TP(t){let e=Ia.flatMap((n)=>{let r=t[n];return r===void 0||r===To(n)?[]:[`${n}=${/\s/.test(r)?JSON.stringify(r):r}`]});return e.length>0?e.join(" "):void 0}function lk(){let t=process.env,n=[["ttheme",Ot.version],["OS",FP()],["Shell",xP(t)],["Terminal",HP(t)],["Wired",LP(Y())],["Settings",TP(t)]].filter((i)=>i[1]!==void 0),r=Math.max(...n.map(([i])=>i.length));for(let[i,o]of n)console.log(`${i.padEnd(r)} ${o}`)}import{execFileSync as AP,spawnSync as CP}from"node:child_process";import{chmodSync as jP,copyFileSync as GP,existsSync as zr,mkdirSync as fk,readdirSync as UP,readFileSync as Ac,rmSync as Rd}from"node:fs";import{homedir as WP}from"node:os";import{dirname as Yi,join as lt}from"node:path";function _P(t,e,n){for(let r of UP(e))t.push({from:lt(e,r),to:lt(n,r)})}function xd(t){return JSON.parse(Ac(lt(t,"dist","manifest.json"),"utf8"))}function Tc(t,e){let n=lt(e.configHome,"ttheme"),r=[{from:lt(e.root,"bin","ttheme.js"),to:lt(n,"ttheme.js")},{from:lt(e.root,"bin","ttheme.js.map"),to:lt(n,"ttheme.js.map")},{from:lt(e.root,"shell","ttheme.zsh"),to:lt(n,"ttheme.zsh")},{from:lt(e.root,"shell","preview.zsh"),to:lt(n,"preview.zsh")},{from:lt(e.root,"shell","launch-tab.zsh"),to:lt(n,"launch-tab.zsh"),executable:!0}];_P(r,lt(e.root,"shell","adapters"),lt(n,"adapters"));let i=[{file:lt(e.zdotdir,".zshrc"),block:bb(n)}],o=lt(n,"config.zsh"),s=$b(zr(o)?Ac(o,"utf8"):""),a={file:o,content:t.warpFast===void 0?s:Ra(s,"TTHEME_WARP_FAST",t.warpFast?"on":"off")},c={terminals:t.terminals,palettes:t.palettes,...Object.fromEntries(ft(t.terminals).flatMap((f)=>Object.entries(f.installs?.(e)??{}).filter(([,d])=>d!==void 0))),...t.off?{off:!0}:{}},u=$w(e.configHome,c,e.home),l=e.stateDir?[lt(e.stateDir,"ghostty",".blind")]:[];return{home:e.home,copies:r,edits:i,settings:a,forget:l,catalog:xd(e.root),installed:c,notes:u}}function hk(t){try{return B(t)}catch{return}}function mk(t){try{return wt(t,ct(t),!1).palettes}catch{return[]}}function BP(t,e){let n=xd(e.root),r=Ft(t.markets).includes(J)?n.palettes:[],i=new Set(r.map((s)=>s.name)),o=mk(e.configHome).filter((s)=>!i.has(s.name)&&(rt(s.name)!==void 0||t.palettes.includes(s.name)));return{...n,palettes:[...r,...o]}}function gk(t,e){let n=Lr(t);return n&&e.includes(n)?n:void 0}function zP(t,e,n){let r=Tc(e,n),i=gk(t,e.palettes),o=new Set(["terminals","palettes","off","startup",...ie.flatMap((a)=>Object.keys(or[a].installs?.(n)??{}))]),s=Object.fromEntries(Object.entries(t).filter(([a])=>!o.has(a)));return{...r,installed:{...s,...r.installed,...i?{startup:i}:{}}}}function KP(t,e){let n=Tc({terminals:t.terminals,palettes:t.palettes,off:t.off},e),r=new Set([...n.catalog.palettes,...mk(e.configHome)].map((l)=>l.name)),i=t.palettes.filter((l)=>r.has(l)),o=t.palettes.filter((l)=>!r.has(l)),{startup:s,...a}=t,c={...a,palettes:i,...s&&i.includes(s)?{startup:s}:{}},u=o.length>0?[`Dropped ${o.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:c,notes:u}}function qP(t){try{return AP(process.execPath,[lt(t,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function pk(t){let e=Re(t);return[ft(t.terminals).map((n)=>n.name).join(", "),`${t.palettes.length} palettes`,e?`default ${e}`:"no default — ttheme is off"].join(" · ")}function Pd(t,e=Fr()){for(let s of t.copies)if(fk(Yi(s.to),{recursive:!0}),Rd(s.to,{force:!0}),Rd(`${s.to}.zwc`,{force:!0}),GP(s.from,s.to),s.executable)jP(s.to,493);x(t.settings.file,t.settings.content);for(let s of t.forget)Rd(s,{force:!0});let n=Yi(Yi(t.settings.file)),r=hk(n),i=Object.fromEntries(ft(t.installed.terminals).flatMap((s)=>{let a=s.defaults?.key,c=a?r?.[a]:void 0;return a&&c?[[a,c]]:[]})),o=hf(n,{...t.installed,...i},e,t.home);if(Ft(o.markets).includes(J))$a(n,t.catalog);Je(n,o),At(n,ct(n),o,t.home);for(let s of t.edits){fk(Yi(s.file),{recursive:!0});let a=zr(s.file)?Ac(s.file,"utf8"):"";Ae(s.file,Dn(a,s.block))}return zo(n,o,!0,e,t.home)}function Es(t){if(Lt(t))throw Zr("Nothing changed"),new Pe;return t}function Hd(t,e){return ie.filter((n)=>or[n].offered(t,e))}async function JP(t,e,n,r){return Es(await Lh({message:"Wire which terminals?",options:Hd(n,r).map((i)=>({value:i,label:or[i].name,hint:i===t?"detected":void 0})),initialValues:e,required:!0}))}async function YP(t){return Es(await nn({message:"Switch Warp to each tab's palette in about 0.2 s instead of 0.6 s?\nAbout 8% CPU while Warp is in front with tabs of different palettes — `ttheme config` changes it",initialValue:Oa(t,"TTHEME_WARP_FAST")!=="off"}))}function Fd(t){let e=[...t.copies.filter((n)=>!zr(n.to)).map((n)=>n.to),...zr(t.settings.file)?[]:[t.settings.file],...t.edits.filter((n)=>!Ac(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(e.length>0)throw Error(`init left gaps:
553
+ ${e.join(`
554
+ `)}`)}function bk(t,e){return[...new Set(t.palettes.filter((n)=>e.includes(n.name)).map((n)=>n.group))]}function DP(t,e,n){let r=t.palettes.find((s)=>s.name===Re(e)),i=process.stdout.isTTY===!0,o=r&&(Yn(process.env,i)??fr(process.env,i,n))?.wear(r,e.terminals);if(o===void 0)return!1;return process.stdout.write(o),!0}function VP(t,e){let n=Re(t);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Lr(t)}`];return[`Default ${n}${e?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function ZP(t){CP("zsh",["-c",'source "$1" && __tt_preview init',"zsh",lt(t,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function QP(t,e,n,r){let i=bk(t.catalog,e.palettes);wr([`${i.join(", ")} (${e.palettes.length})`,...VP(t.installed,n)].join(`
555
+ `),`Installed ${e.palettes.length} palettes`),wr(["exec zsh The ttheme command in this tab",...Ld(t,r)].join(`
556
+ `),"Next"),lu("Done")}function Ld(t,e){return[...kw(Yi(Yi(t.settings.file)),t.installed,e,t.home),...t.notes]}function wk(t){return t?(e)=>vn.step(e):(e)=>console.log(e)}async function dk(t,e,n,r){let i=KP(t,e),o=Pd(i,n);Fd(i),await xc(e.configHome,wk(r),e.home);let s=["exec zsh Open tabs run the new layer — new tabs already do",...Ld(i,o)],a=`Updated to ${Ot.version} — kept ${pk(i.installed)}`;if(!r){console.log([a,...s].join(`
557
+ `));return}wr(s.join(`
558
+ `),a),lu("Done")}function XP(t,e){let n=[`Placed ${t.copies.length} files`,`Settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`Wired ${r.file}`),...Ld(t,e),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
559
+ `))}async function $k(t={}){let e=lt(import.meta.dirname,"..");if(!zr(lt(e,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!zr(lt(e,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Fc()}let n=WP(),r=Y(),i=process.env.ZDOTDIR??n,o=Fr(),s=dw(o),a=process.env.WT_PROFILE_ID,c={root:e,home:n,configHome:r,zdotdir:i,stateDir:lt(process.env.XDG_STATE_HOME??lt(n,".local","state"),"ttheme"),...s?{wtHome:s}:{},...a?{wtProfile:a}:{}},u=re(process.env),l=Hd(c,o).filter((O)=>O===u||or[O].present(c));if(!t.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");let f=hk(r);if(t.yes&&f){await dk(f,c,o,!1);return}if(t.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${ft(Hd(c,o)).map((W)=>W.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let F=Tc({terminals:l,palettes:[]},c),j=Pd(F,o);Fd(F),XP(F,j);return}if(Gs("ttheme init"),f){let O=qP(r);if(Es(await nn({message:`ttheme${O?` ${O}`:""} is installed — ${pk(f)}
560
+ ${O===Ot.version?"Reinstall":"Update to"} ${Ot.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await dk(f,c,o,!0);return}}let d=await JP(u,f?.terminals??l,c,o),m=d.includes("warp")?await YP(r):void 0,g=f?BP(f,c):xd(e),$=f?await Md(g,f.palettes,"palette",!0):await Md(g,[],"series",!0);if(!$)throw Zr("Nothing changed"),new Pe;let w=(f&&gk(f,$))??$[0],b=$.length>1&&(Ne[u].paints||u==="warp"&&d.includes("warp")&&zr(rr(n,r))),v=Es(await nn({message:b?"Pick a default palette in ttheme preview once installed?":`Wear ${w} in every tab?`,initialValue:f?!f.off:!0})),R={terminals:d,palettes:$,off:!v,warpFast:m},S=f?zP(f,R,c):Tc(R,c);if(wr([`Install ${$.length} palettes — ${bk(g,$).join(", ")}`,`Copy ${S.copies.length} files under ${r}`,`Write ${S.settings.file}`,...S.edits.map((O)=>`Edit ${O.file} — a ttheme block: source ttheme.zsh`),...ww(r,S.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",v?b?`Open ttheme preview — every tab wears the palette picked there, ${w} until then`:`Paint every tab with ${w}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...v&&w?ft(d).flatMap((O)=>O.defaults?[`Make "${O.defaults.profile(w)}" the ${O.name} default profile`]:[]):[]].join(`
561
+ `),`Wiring ${ft(d).map((O)=>O.name).join(", ")}`),!Es(await nn({message:"Apply these changes?"})))throw Zr("Nothing changed"),new Pe;let I=Pd(S,o);if(Fd(S),await xc(r,wk(!0),n),v&&b)ZP(r);let P=B(r);QP({...S,catalog:g,installed:P},R,DP(g,P,r),I)}import{createInterface as tH}from"node:readline";var eH="\x1F",kk="\x1E",nH=new Set(["up","down","left","right","home","end","pgup","pgdn","tab","shift-tab","shift-left","shift-right","enter","esc","backspace","ctrl-c"]);function yk(t){return{background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selection,ansi:t.ansi}}class vk{editor;base;cols=cd;rows=ud;focused=!0;home;name;color;constructor(t,e,n){this.home=t,this.name=e,this.color=n,this.base=hn(Hr(t,ct(t),!1).palettes,e);let r=Ro(this.base,fn(t)[e]);this.editor=new gs({title:"Tone",name:e,colors:yk(r),original:yk(this.base),variant:"theme",signature:r.signatureSlots,...r.waived?{waive:r.waived}:{},check:()=>{return}})}save(){try{let t=Jp(this.base,this.editor.list);qp(this.home,Yp(fn(this.home),this.name,t)),At(this.home,ct(this.home),B(this.home)),this.editor.markSaved();return}catch(t){return t instanceof Error?t.message:String(t)}}frame(t="ok",e){let n=X0(this.editor),r=this.editor.act??"-";this.editor.act=void 0;let{lines:i,at:o}=t$(this.editor,this.cols,this.rows,this.color,this.focused);return[t,r,n.mode,this.editor.dirty()?"1":"0",this.editor.shown().join(" "),n.keys.map(([s])=>s).join(kk),n.keys.map(([,s])=>s).join(kk),e??n.note,String(o),...i].join(eH)}handle(t){let[e="",...n]=t.split(" "),r=n.join(" ");if(e==="quit")return;if(e==="size"){let[i,o]=r.split(" ").map(Number);this.cols=Math.max(30,i??cd),this.rows=Math.max(10,o??ud)}else if(e==="focus")this.focused=r==="1";else if(e==="key"&&nH.has(r))this.editor.press(r);else if(e==="ch"){let i=Number(r);if(Number.isInteger(i)&&i>0)this.editor.press(String.fromCharCode(i))}else if(e==="save"){let i=this.save();return i===void 0?this.frame("saved","Saved"):this.frame("error",i)}return this.frame()}}async function Ek(t){let e=new vk(Y(),t,process.env.NO_COLOR===void 0),n=tH({input:process.stdin});for await(let r of n){let i=e.handle(r);if(i===void 0)break;process.stdout.write(`${i}
562
+ `)}return n.close(),process.stdin.destroy(),0}import{existsSync as Sk,rmSync as rH,utimesSync as iH}from"node:fs";import{homedir as oH}from"node:os";import{join as Ss}from"node:path";function sH(t){try{return B(t)}catch{return}}function aH(t){let{home:e,configHome:n}=t,r=sH(n),i={configHome:n,home:e},o=ft(ie),s=o.map((c)=>c.unwire(i,r)),a=[Ss(n,"ttheme"),t.cacheDir,t.stateDir];return{edits:[...Ke(Ss(t.zdotdir,".zshrc"),Vn),...s.flatMap((c)=>c.edits)],removals:[...o.flatMap((c)=>c.shelf?Ha(c.shelf.dir(i)):[]),...s.flatMap((c)=>c.removals),...a.filter((c)=>Sk(c))],touches:s.flatMap((c)=>c.touches),...r?{state:r}:{}}}function cH(t,e,n=Fr()){let r=[];for(let{file:o,content:s}of t.edits){let a=Yh(o,s);r.push(a==="removed"?`Removed ${o} — ttheme had created it`:a==="restored"?`Took ttheme out of ${o}`:`Took ttheme out of ${o} — kept ${o}.ttheme.bak, since the file changed after ttheme's first edit`)}if(t.state){let o=zo(e.configHome,{...t.state,off:!0,palettes:[]},!1,n,e.home);for(let s of ft(t.state.terminals))if(o.has(s.id))r.push(`Gave ${s.name} its own default profile back — it takes it at its next start`)}for(let o of t.removals)rH(o,{recursive:!0,force:!0});if(t.removals.length>0)r.push(`Deleted ${t.removals.length} files and folders ttheme wrote`);let i=new Date;for(let o of t.touches)iH(o,i,i);return r}function uH(){let t=oH();return{home:t,configHome:Y(),zdotdir:process.env.ZDOTDIR??t,cacheDir:Tn(),stateDir:Ss(process.env.XDG_STATE_HOME??Ss(t,".local","state"),"ttheme")}}async function Mk(t=!1){let e=uH(),n=aH(e);if(n.edits.length===0&&n.removals.length===0){console.log("Nothing of ttheme is installed");return}if(!t){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=Ss(e.configHome,"ttheme");Gs("ttheme uninstall"),wr([...n.edits.map((o)=>`Take ttheme out of ${o.file}`),...n.removals.map((o)=>o===r?`Delete ${o} — settings, pins, every installed picture${Sk(ha(e.configHome))?`, and your markets under ${ha(e.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${o}`)].join(`
563
+ `),"Uninstall");let i=await nn({message:"Remove ttheme?"});if(Lt(i)||!i)throw Zr("Nothing changed"),new Pe}for(let r of cH(n,e))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var fH=new Set(["add","remove","market","default","on","off"]),dH={default:([t])=>B$(t),on:()=>z$(),off:()=>K$(),browse:()=>Z$(),list:([t],{json:e})=>Y$(t,e),add:(t,{market:e})=>W$(t,e),remove:(t)=>_$(t),update:()=>D$(),market:([t,e])=>Vw(t,e),new:([t],{from:e,in:n})=>A$(t,e,n),edit:([t])=>C$(t),check:([t],{fix:e})=>G$(t,e),share:([t],{tone:e})=>U$(t,e),init:(t,{yes:e})=>$k({yes:e}),uninstall:(t,{yes:e})=>Mk(e),info:()=>lk(),build:(t,{only:e})=>Fc({only:e}),find:([t])=>I$(t),image:([t,e,n])=>ok(t,e,n),redraw:()=>rk(),tone:([t])=>Ek(t),flatten:([t,e,n,r,i,o])=>ck(t,e,n,r,i,o),bake:([t,e,n,r])=>ak(t,e,n,r)},hH=xo.map((t)=>({...t,run:dH[t.name]}));class Kr extends Error{verb;constructor(t,e){super(t);this.verb=e}}function Ik(t){let e=hH.find((n)=>n.name===t);if(!e)throw new Kr(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return e}function mH(t,e){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(t.flags??{}))n[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return lH({args:e,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Kr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function gH(t){let[e,...n]=t;if(e===void 0)return{kind:"help",code:1};if(e==="-h"||e==="--help")return{kind:"help",code:0};if(e==="-V"||e==="--version")return{kind:"version"};if(e==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:Ik(n[0]),code:0}}let r=Ik(e),i=mH(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[l,{choices:f}]of Object.entries(r.flags??{}))for(let d of[i.values[l]??[]].flat())if(f&&!f.includes(String(d)))throw new Kr(`--${l} takes ${f.join(", ")} — not ${d}`,r);let o=i.positionals,s=r.args.filter((l)=>l.startsWith("<")).length,a=r.args.some((l)=>l.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Kr(`missing ${r.args[o.length]}`,r);if(o.length>a)throw new Kr(`too many arguments: ${o.slice(a).join(" ")}`,r);let{help:c,...u}=i.values;return{kind:"run",verb:r,args:o,flags:u}}function Ok(t){let e=Math.max(0,...t.map(([n])=>n.length));return t.map(([n,r])=>` ${n.padEnd(e)} ${r}`)}function Td(t,e=!1){if(!t)return Lo(e);let n=Object.entries(t.flags??{}).map(([r,{short:i,value:o,about:s}])=>[`${i?`-${i}, `:""}--${r}${o?` ${o}`:""}`,s]);return[`Usage: ttheme ${Fo(t)}`,"",t.about,...t.actions?["","Actions:",...Ok(t.actions)]:[],...n.length>0?["","Options:",...Ok(n)]:[]].join(`
564
+ `)}var pH=[TypeError,RangeError,ReferenceError,SyntaxError];function bH(t){return pH.some((e)=>t instanceof e)||t instanceof Error&&"code"in t}async function Nk(t){let e;try{let n=gH(t);if(n.kind==="version")return console.log(Ot.version),0;if(n.kind==="help"){if(n.code===0)console.log(Td(n.verb,n.all));else console.error(Td(n.verb,n.all));return n.code}if(e=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");if(fH.has(n.verb.name))await Lw();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Kr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
547
565
 
548
- ${wd(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof yr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
549
- ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}${XP(n)?"\nReport a bug with the output of `ttheme info`":""}`),1}}if(eR)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=DP(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await x$(process.argv.slice(2));
566
+ ${Td(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof Pe)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
567
+ ttheme${e?` ${e.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}${bH(n)?"\nReport a bug with the output of `ttheme info`":""}`),1}}if($H)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let t=wH(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=t.status??1}else process.exitCode=await Nk(process.argv.slice(2));
550
568
 
551
- //# debugId=912A2507F3D9A0B564756E2164756E21
569
+ //# debugId=2E050346347C0A5664756E2164756E21
552
570
  //# sourceMappingURL=ttheme.js.map