@kecan0406/ttheme 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,74 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as C0}from"node:module";var F0=Object.create;var{getPrototypeOf:R0,defineProperty:Qf,getOwnPropertyNames:H0}=Object;var T0=Object.prototype.hasOwnProperty;function A0(e){return this[e]}var L0,x0,bo=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?L0??=new WeakMap:x0??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?F0(R0(e)):{};let o=t||!e||!e.__esModule?Qf(n,"default",{value:e,enumerable:!0}):n;for(let a of H0(e))if(!T0.call(o,a))Qf(o,a,{get:A0.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 st=C0(import.meta.url);var ku=He((WN,ld)=>{var $u={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"},X0={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},D0={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?$u.up():"");if(e)t+=$u.left;return t}};ld.exports={cursor:$u,scroll:X0,erase:D0,beep:"\x07"}});var Kd=He((kP,Oo)=>{var jd=jd||function(e){return Buffer.from(e).toString("base64")};function z$(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),p=Array(64),b=[],m=0,$=7,k=Array(64),M=Array(64),w=Array(64),S=Array(256),y=Array(2048),N,O=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],T=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],_=[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],L=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],J=[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(E){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 B=0;B<64;B++){var U=r((G[B]*E+50)/100);if(U<1)U=1;else if(U>255)U=255;i[O[B]]=U}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 ne=0;ne<64;ne++){var me=r((te[ne]*E+50)/100);if(me<1)me=1;else if(me>255)me=255;s[O[ne]]=me}var pe=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var Re=0;Re<8;Re++)for(var P=0;P<8;P++)o[Ue]=1/(i[O[Ue]]*pe[Re]*pe[P]*8),a[Ue]=1/(s[O[Ue]]*pe[Re]*pe[P]*8),Ue++}function Y(E,G){var B=0,U=0,te=[];for(var ne=1;ne<=16;ne++){for(var me=1;me<=E[ne];me++)te[G[U]]=[],te[G[U]][0]=B,te[G[U]][1]=ne,U++,B++;B*=2}return te}function Le(){u=Y(T,A),c=Y(L,R),l=Y(C,_),f=Y(J,Ee)}function de(){var E=1,G=2;for(var B=1;B<=15;B++){for(var U=E;U<G;U++)h[32767+U]=B,d[32767+U]=[],d[32767+U][1]=B,d[32767+U][0]=U;for(var te=-(G-1);te<=-E;te++)h[32767+te]=B,d[32767+te]=[],d[32767+te][1]=B,d[32767+te][0]=G-1+te;E<<=1,G<<=1}}function ae(){for(var E=0;E<256;E++)y[E]=19595*E,y[E+256>>0]=38470*E,y[E+512>>0]=7471*E+32768,y[E+768>>0]=-11059*E,y[E+1024>>0]=-21709*E,y[E+1280>>0]=32768*E+8421375,y[E+1536>>0]=-27439*E,y[E+1792>>0]=-5329*E}function ie(E){var G=E[0],B=E[1]-1;while(B>=0){if(G&1<<B)m|=1<<$;if(B--,$--,$<0){if(m==255)v(255),v(0);else v(m);$=7,m=0}}}function v(E){b.push(E)}function W(E){v(E>>8&255),v(E&255)}function Se(E,G){var B,U,te,ne,me,pe,Ue,Re,P=0,x,V=8,_e=64;for(x=0;x<V;++x){B=E[P],U=E[P+1],te=E[P+2],ne=E[P+3],me=E[P+4],pe=E[P+5],Ue=E[P+6],Re=E[P+7];var re=B+Re,ue=B-Re,Ie=U+Ue,q=U-Ue,we=te+pe,tt=te-pe,xe=ne+me,It=ne-me,qt=re+xe,dr=re-xe,Wr=Ie+we,Ur=Ie-we;E[P]=qt+Wr,E[P+4]=qt-Wr;var Wi=(Ur+dr)*0.707106781;E[P+2]=dr+Wi,E[P+6]=dr-Wi,qt=It+tt,Wr=tt+q,Ur=q+ue;var Ui=(qt-Ur)*0.382683433,ho=0.5411961*qt+Ui,ji=1.306562965*Ur+Ui,Ki=Wr*0.707106781,Ji=ue+Ki,Bi=ue-Ki;E[P+5]=Bi+ho,E[P+3]=Bi-ho,E[P+1]=Ji+ji,E[P+7]=Ji-ji,P+=8}P=0;for(x=0;x<V;++x){B=E[P],U=E[P+8],te=E[P+16],ne=E[P+24],me=E[P+32],pe=E[P+40],Ue=E[P+48],Re=E[P+56];var xf=B+Re,gu=B-Re,Cf=U+Ue,Gf=U-Ue,_f=te+pe,Wf=te-pe,Uf=ne+me,O0=ne-me,qi=xf+Uf,mu=xf-Uf,go=Cf+_f,mo=Cf-_f;E[P]=qi+go,E[P+32]=qi-go;var jf=(mo+mu)*0.707106781;E[P+16]=mu+jf,E[P+48]=mu-jf,qi=O0+Wf,go=Wf+Gf,mo=Gf+gu;var Kf=(qi-mo)*0.382683433,Jf=0.5411961*qi+Kf,Bf=1.306562965*mo+Kf,qf=go*0.707106781,zf=gu+qf,Yf=gu-qf;E[P+40]=Yf+Jf,E[P+24]=Yf-Jf,E[P+8]=zf+Bf,E[P+56]=zf-Bf,P++}var po;for(x=0;x<_e;++x)po=E[x]*G[x],g[x]=po>0?po+0.5|0:po-0.5|0;return g}function Me(){W(65504),W(16),v(74),v(70),v(73),v(70),v(0),v(1),v(1),v(0),W(1),W(1),v(0),v(0)}function le(E){if(!E)return;if(W(65505),E[0]===69&&E[1]===120&&E[2]===105&&E[3]===102)W(E.length+2);else W(E.length+5+2),v(69),v(120),v(105),v(102),v(0);for(var G=0;G<E.length;G++)v(E[G])}function fe(E,G){W(65472),W(17),v(8),W(G),W(E),v(3),v(1),v(17),v(0),v(2),v(17),v(1),v(3),v(17),v(1)}function se(){W(65499),W(132),v(0);for(var E=0;E<64;E++)v(i[E]);v(1);for(var G=0;G<64;G++)v(s[G])}function H(){W(65476),W(418),v(0);for(var E=0;E<16;E++)v(T[E+1]);for(var G=0;G<=11;G++)v(A[G]);v(16);for(var B=0;B<16;B++)v(C[B+1]);for(var U=0;U<=161;U++)v(_[U]);v(1);for(var te=0;te<16;te++)v(L[te+1]);for(var ne=0;ne<=11;ne++)v(R[ne]);v(17);for(var me=0;me<16;me++)v(J[me+1]);for(var pe=0;pe<=161;pe++)v(Ee[pe])}function F(E){if(typeof E>"u"||E.constructor!==Array)return;E.forEach((G)=>{if(typeof G!=="string")return;W(65534);var B=G.length;W(B+2);var U;for(U=0;U<B;U++)v(G.charCodeAt(U))})}function Fe(){W(65498),W(12),v(3),v(1),v(0),v(2),v(17),v(3),v(17),v(0),v(63),v(0)}function Q(E,G,B,U,te){var ne=te[0],me=te[240],pe,Ue=16,Re=63,P=64,x=Se(E,G);for(var V=0;V<P;++V)p[O[V]]=x[V];var _e=p[0]-B;if(B=p[0],_e==0)ie(U[0]);else pe=32767+_e,ie(U[h[pe]]),ie(d[pe]);var re=63;for(;re>0&&p[re]==0;re--);if(re==0)return ie(ne),B;var ue=1,Ie;while(ue<=re){var q=ue;for(;p[ue]==0&&ue<=re;++ue);var we=ue-q;if(we>=Ue){Ie=we>>4;for(var tt=1;tt<=Ie;++tt)ie(me);we=we&15}pe=32767+p[ue],ie(te[(we<<4)+h[pe]]),ie(d[pe]),ue++}if(re!=Re)ie(ne);return B}function oe(){var E=String.fromCharCode;for(var G=0;G<256;G++)S[G]=E(G)}this.encode=function(E,G){var B=new Date().getTime();if(G)Mt(G);b=[],m=0,$=7,W(65496),Me(),F(E.comments),le(E.exifBuffer),se(),fe(E.width,E.height),H(),Fe();var U=0,te=0,ne=0;m=0,$=7,this.encode.displayName="_encode_";var{data:me,width:pe,height:Ue}=E,Re=pe*4,P=pe*3,x,V=0,_e,re,ue,Ie,q,we,tt,xe;while(V<Ue){x=0;while(x<Re){Ie=Re*V+x,q=Ie,we=-1,tt=0;for(xe=0;xe<64;xe++){if(tt=xe>>3,we=(xe&7)*4,q=Ie+tt*Re+we,V+tt>=Ue)q-=Re*(V+1+tt-Ue);if(x+we>=Re)q-=x+we-Re+4;_e=me[q++],re=me[q++],ue=me[q++],k[xe]=(y[_e]+y[re+256>>0]+y[ue+512>>0]>>16)-128,M[xe]=(y[_e+768>>0]+y[re+1024>>0]+y[ue+1280>>0]>>16)-128,w[xe]=(y[_e+1280>>0]+y[re+1536>>0]+y[ue+1792>>0]>>16)-128}U=Q(k,o,U,u,l),te=Q(M,a,te,c,f),ne=Q(w,a,ne,c,f),x+=32}V+=8}if($>=0){var It=[];It[1]=$+1,It[0]=(1<<$+1)-1,ie(It)}if(W(65497),typeof Oo>"u")return new Uint8Array(b);return Buffer.from(b);var qt,dr};function Mt(E){if(E<=0)E=1;if(E>100)E=100;if(N==E)return;var G=0;if(E<50)G=Math.floor(5000/E);else G=Math.floor(200-E*2);be(G),N=E}function Ct(){var E=new Date().getTime();if(!e)e=50;oe(),Le(),de(),ae(),Mt(e);var G=new Date().getTime()-E}Ct()}if(typeof Oo<"u")Oo.exports=Ud;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ud;function Ud(e,t){if(typeof t>"u")t=50;var n=new z$(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var Bd=He((yP,Wu)=>{var _u=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){var M=0,w=[],S,y,N=16;while(N>0&&!$[N-1])N--;w.push({children:[],index:0});var O=w[0],T;for(S=0;S<N;S++){for(y=0;y<$[S];y++){O=w.pop(),O.children[O.index]=k[M];while(O.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");O=w.pop()}O.index++,w.push(O);while(w.length<=S)w.push(T={children:[],index:0}),O.children[O.index]=T.children,O=T;M++}if(S+1<N)w.push(T={children:[],index:0}),O.children[O.index]=T.children,O=T}return w[0].children}function d($,k,M,w,S,y,N,O,T,A){var{precision:C,samplesPerLine:_,scanLines:L,mcusPerLine:R,progressive:J,maxH:Ee,maxV:be}=M,Y=k,Le=0,de=0;function ae(){if(de>0)return de--,Le>>de&1;if(Le=$[k++],Le==255){var P=$[k++];if(P)throw Error("unexpected marker: "+(Le<<8|P).toString(16))}return de=7,Le>>>7}function ie(P){var x=P,V;while((V=ae())!==null){if(x=x[V],typeof x==="number")return x;if(typeof x!=="object")throw Error("invalid huffman sequence")}return null}function v(P){var x=0;while(P>0){var V=ae();if(V===null)return;x=x<<1|V,P--}return x}function W(P){var x=v(P);if(x>=1<<P-1)return x;return x+(-1<<P)+1}function Se(P,x){var V=ie(P.huffmanTableDC),_e=V===0?0:W(V);x[0]=P.pred+=_e;var re=1;while(re<64){var ue=ie(P.huffmanTableAC),Ie=ue&15,q=ue>>4;if(Ie===0){if(q<15)break;re+=16;continue}re+=q;var we=t[re];x[we]=W(Ie),re++}}function Me(P,x){var V=ie(P.huffmanTableDC),_e=V===0?0:W(V)<<T;x[0]=P.pred+=_e}function le(P,x){x[0]|=ae()<<T}var fe=0;function se(P,x){if(fe>0){fe--;return}var V=y,_e=N;while(V<=_e){var re=ie(P.huffmanTableAC),ue=re&15,Ie=re>>4;if(ue===0){if(Ie<15){fe=v(Ie)+(1<<Ie)-1;break}V+=16;continue}V+=Ie;var q=t[V];x[q]=W(ue)*(1<<T),V++}}var H=0,F;function Fe(P,x){var V=y,_e=N,re=0;while(V<=_e){var ue=t[V],Ie=x[ue]<0?-1:1;switch(H){case 0:var q=ie(P.huffmanTableAC),we=q&15,re=q>>4;if(we===0)if(re<15)fe=v(re)+(1<<re),H=4;else re=16,H=1;else{if(we!==1)throw Error("invalid ACn encoding");F=W(we),H=re?2:3}continue;case 1:case 2:if(x[ue])x[ue]+=(ae()<<T)*Ie;else if(re--,re===0)H=H==2?3:0;break;case 3:if(x[ue])x[ue]+=(ae()<<T)*Ie;else x[ue]=F<<T,H=0;break;case 4:if(x[ue])x[ue]+=(ae()<<T)*Ie;break}V++}if(H===4){if(fe--,fe===0)H=0}}function Q(P,x,V,_e,re){var ue=V/R|0,Ie=V%R,q=ue*P.v+_e,we=Ie*P.h+re;if(P.blocks[q]===void 0&&A.tolerantDecoding)return;x(P,P.blocks[q][we])}function oe(P,x,V){var _e=V/P.blocksPerLine|0,re=V%P.blocksPerLine;if(P.blocks[_e]===void 0&&A.tolerantDecoding)return;x(P,P.blocks[_e][re])}var Mt=w.length,Ct,E,G,B,U,te;if(J)if(y===0)te=O===0?Me:le;else te=O===0?se:Fe;else te=Se;var ne=0,me,pe;if(Mt==1)pe=w[0].blocksPerLine*w[0].blocksPerColumn;else pe=R*M.mcusPerColumn;if(!S)S=pe;var Ue,Re;while(ne<pe){for(E=0;E<Mt;E++)w[E].pred=0;if(fe=0,Mt==1){Ct=w[0];for(U=0;U<S;U++)oe(Ct,te,ne),ne++}else for(U=0;U<S;U++){for(E=0;E<Mt;E++){Ct=w[E],Ue=Ct.h,Re=Ct.v;for(G=0;G<Re;G++)for(B=0;B<Ue;B++)Q(Ct,te,ne,G,B)}if(ne++,ne===pe)break}if(ne===pe)do{if($[k]===255){if($[k+1]!==0)break}k+=1}while(k<$.length-2);if(de=0,me=$[k]<<8|$[k+1],me<65280)throw Error("marker was not found");if(me>=65488&&me<=65495)k+=2;else break}return k-Y}function h($,k){var M=[],w=k.blocksPerLine,S=k.blocksPerColumn,y=w<<3,N=new Int32Array(64),O=new Uint8Array(64);function T(Y,Le,de){var ae=k.quantizationTable,ie,v,W,Se,Me,le,fe,se,H,F=de,Fe;for(Fe=0;Fe<64;Fe++)F[Fe]=Y[Fe]*ae[Fe];for(Fe=0;Fe<8;++Fe){var Q=8*Fe;if(F[1+Q]==0&&F[2+Q]==0&&F[3+Q]==0&&F[4+Q]==0&&F[5+Q]==0&&F[6+Q]==0&&F[7+Q]==0){H=u*F[0+Q]+512>>10,F[0+Q]=H,F[1+Q]=H,F[2+Q]=H,F[3+Q]=H,F[4+Q]=H,F[5+Q]=H,F[6+Q]=H,F[7+Q]=H;continue}ie=u*F[0+Q]+128>>8,v=u*F[4+Q]+128>>8,W=F[2+Q],Se=F[6+Q],Me=c*(F[1+Q]-F[7+Q])+128>>8,se=c*(F[1+Q]+F[7+Q])+128>>8,le=F[3+Q]<<4,fe=F[5+Q]<<4,H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=W*a+Se*o+128>>8,W=W*o-Se*a+128>>8,Se=H,H=Me-fe+1>>1,Me=Me+fe+1>>1,fe=H,H=se+le+1>>1,le=se-le+1>>1,se=H,H=ie-Se+1>>1,ie=ie+Se+1>>1,Se=H,H=v-W+1>>1,v=v+W+1>>1,W=H,H=Me*s+se*i+2048>>12,Me=Me*i-se*s+2048>>12,se=H,H=le*r+fe*n+2048>>12,le=le*n-fe*r+2048>>12,fe=H,F[0+Q]=ie+se,F[7+Q]=ie-se,F[1+Q]=v+fe,F[6+Q]=v-fe,F[2+Q]=W+le,F[5+Q]=W-le,F[3+Q]=Se+Me,F[4+Q]=Se-Me}for(Fe=0;Fe<8;++Fe){var oe=Fe;if(F[8+oe]==0&&F[16+oe]==0&&F[24+oe]==0&&F[32+oe]==0&&F[40+oe]==0&&F[48+oe]==0&&F[56+oe]==0){H=u*de[Fe+0]+8192>>14,F[0+oe]=H,F[8+oe]=H,F[16+oe]=H,F[24+oe]=H,F[32+oe]=H,F[40+oe]=H,F[48+oe]=H,F[56+oe]=H;continue}ie=u*F[0+oe]+2048>>12,v=u*F[32+oe]+2048>>12,W=F[16+oe],Se=F[48+oe],Me=c*(F[8+oe]-F[56+oe])+2048>>12,se=c*(F[8+oe]+F[56+oe])+2048>>12,le=F[24+oe],fe=F[40+oe],H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=W*a+Se*o+2048>>12,W=W*o-Se*a+2048>>12,Se=H,H=Me-fe+1>>1,Me=Me+fe+1>>1,fe=H,H=se+le+1>>1,le=se-le+1>>1,se=H,H=ie-Se+1>>1,ie=ie+Se+1>>1,Se=H,H=v-W+1>>1,v=v+W+1>>1,W=H,H=Me*s+se*i+2048>>12,Me=Me*i-se*s+2048>>12,se=H,H=le*r+fe*n+2048>>12,le=le*n-fe*r+2048>>12,fe=H,F[0+oe]=ie+se,F[56+oe]=ie-se,F[8+oe]=v+fe,F[48+oe]=v-fe,F[16+oe]=W+le,F[40+oe]=W-le,F[24+oe]=Se+Me,F[32+oe]=Se-Me}for(Fe=0;Fe<64;++Fe){var Mt=128+(F[Fe]+8>>4);Le[Fe]=Mt<0?0:Mt>255?255:Mt}}m(y*S*8);var A,C;for(var _=0;_<S;_++){var L=_<<3;for(A=0;A<8;A++)M.push(new Uint8Array(y));for(var R=0;R<w;R++){T(k.blocks[_][R],O,N);var J=0,Ee=R<<3;for(C=0;C<8;C++){var be=M[L+C];for(A=0;A<8;A++)be[Ee+A]=O[J++]}}}return M}function g($){return $<0?0:$>255?255:$}l.prototype={load:function(k){var M=new XMLHttpRequest;M.open("GET",k,!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(k){var M=this.opts.maxResolutionInMP*1000*1000,w=0,S=k.length;function y(){var q=k[w]<<8|k[w+1];return w+=2,q}function N(){var q=y(),we=k.subarray(w,w+q-2);return w+=we.length,we}function O(q){var we=1,tt=1,xe,It;for(It in q.components)if(q.components.hasOwnProperty(It)){if(xe=q.components[It],we<xe.h)we=xe.h;if(tt<xe.v)tt=xe.v}var qt=Math.ceil(q.samplesPerLine/8/we),dr=Math.ceil(q.scanLines/8/tt);for(It in q.components)if(q.components.hasOwnProperty(It)){xe=q.components[It];var Wr=Math.ceil(Math.ceil(q.samplesPerLine/8)*xe.h/we),Ur=Math.ceil(Math.ceil(q.scanLines/8)*xe.v/tt),Wi=qt*xe.h,Ui=dr*xe.v,ho=Ui*Wi,ji=[];m(ho*256);for(var Ki=0;Ki<Ui;Ki++){var Ji=[];for(var Bi=0;Bi<Wi;Bi++)Ji.push(new Int32Array(64));ji.push(Ji)}xe.blocksPerLine=Wr,xe.blocksPerColumn=Ur,xe.blocks=ji}q.maxH=we,q.maxV=tt,q.mcusPerLine=qt,q.mcusPerColumn=dr}var T=null,A=null,C=null,_,L,R=[],J=[],Ee=[],be=[],Y=y(),Le=-1;if(this.comments=[],Y!=65496)throw Error("SOI not found");Y=y();while(Y!=65497){var de,ae,ie;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 v=N();if(Y===65534){var W=String.fromCharCode.apply(null,v);this.comments.push(W)}if(Y===65504){if(v[0]===74&&v[1]===70&&v[2]===73&&v[3]===70&&v[4]===0)T={version:{major:v[5],minor:v[6]},densityUnits:v[7],xDensity:v[8]<<8|v[9],yDensity:v[10]<<8|v[11],thumbWidth:v[12],thumbHeight:v[13],thumbData:v.subarray(14,14+3*v[12]*v[13])}}if(Y===65505){if(v[0]===69&&v[1]===120&&v[2]===105&&v[3]===102&&v[4]===0)this.exifBuffer=v.subarray(5,v.length)}if(Y===65518){if(v[0]===65&&v[1]===100&&v[2]===111&&v[3]===98&&v[4]===101&&v[5]===0)A={version:v[6],flags0:v[7]<<8|v[8],flags1:v[9]<<8|v[10],transformCode:v[11]}}break;case 65499:var Se=y(),Me=Se+w-2;while(w<Me){var le=k[w++];m(256);var fe=new Int32Array(64);if(le>>4===0)for(ae=0;ae<64;ae++){var se=t[ae];fe[se]=k[w++]}else if(le>>4===1)for(ae=0;ae<64;ae++){var se=t[ae];fe[se]=y()}else throw Error("DQT: invalid table spec");R[le&15]=fe}break;case 65472:case 65473:case 65474:y(),_={},_.extended=Y===65473,_.progressive=Y===65474,_.precision=k[w++],_.scanLines=y(),_.samplesPerLine=y(),_.components={},_.componentsOrder=[];var H=_.scanLines*_.samplesPerLine;if(H>M){var F=Math.ceil((H-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${F}MP`)}var Fe=k[w++],Q,oe=0,Mt=0;for(de=0;de<Fe;de++){Q=k[w];var Ct=k[w+1]>>4,E=k[w+1]&15,G=k[w+2];if(Ct<=0||E<=0)throw Error("Invalid sampling factor, expected values above 0");_.componentsOrder.push(Q),_.components[Q]={h:Ct,v:E,quantizationIdx:G},w+=3}O(_),J.push(_);break;case 65476:var B=y();for(de=2;de<B;){var U=k[w++],te=new Uint8Array(16),ne=0;for(ae=0;ae<16;ae++,w++)ne+=te[ae]=k[w];m(16+ne);var me=new Uint8Array(ne);for(ae=0;ae<ne;ae++,w++)me[ae]=k[w];de+=17+ne,(U>>4===0?be:Ee)[U&15]=f(te,me)}break;case 65501:y(),L=y();break;case 65500:y(),y();break;case 65498:var pe=y(),Ue=k[w++],Re=[],P;for(de=0;de<Ue;de++){P=_.components[k[w++]];var x=k[w++];P.huffmanTableDC=be[x>>4],P.huffmanTableAC=Ee[x&15],Re.push(P)}var V=k[w++],_e=k[w++],re=k[w++],ue=d(k,w,_,Re,L,V,_e,re>>4,re&15,this.opts);w+=ue;break;case 65535:if(k[w]!==255)w--;break;default:if(k[w-3]==255&&k[w-2]>=192&&k[w-2]<=254){w-=3;break}else if(Y===224||Y==225){if(Le!==-1)throw Error(`first unknown JPEG marker at offset ${Le.toString(16)}, second unknown JPEG marker ${Y.toString(16)} at offset ${(w-1).toString(16)}`);Le=w-1;let q=y();if(k[w+q-2]===255){w+=q-2;break}}throw Error("unknown JPEG marker "+Y.toString(16))}Y=y()}if(J.length!=1)throw Error("only single frame JPEGs supported");for(var de=0;de<J.length;de++){var Ie=J[de].components;for(var ae in Ie)Ie[ae].quantizationTable=R[Ie[ae].quantizationIdx],delete Ie[ae].quantizationIdx}this.width=_.samplesPerLine,this.height=_.scanLines,this.jfif=T,this.adobe=A,this.components=[];for(var de=0;de<_.componentsOrder.length;de++){var P=_.components[_.componentsOrder[de]];this.components.push({lines:h(_,P),scaleX:P.h/_.maxH,scaleY:P.v/_.maxV})}},getData:function(k,M){var w=this.width/k,S=this.height/M,y,N,O,T,A,C,_,L,R,J,Ee=0,be,Y,Le,de,ae,ie,v,W,Se,Me,le,fe=k*M*this.components.length;m(fe);var se=new Uint8Array(fe);switch(this.components.length){case 1:y=this.components[0];for(J=0;J<M;J++){A=y.lines[0|J*y.scaleY*S];for(R=0;R<k;R++)be=A[0|R*y.scaleX*w],se[Ee++]=be}break;case 2:y=this.components[0],N=this.components[1];for(J=0;J<M;J++){A=y.lines[0|J*y.scaleY*S],C=N.lines[0|J*N.scaleY*S];for(R=0;R<k;R++)be=A[0|R*y.scaleX*w],se[Ee++]=be,be=C[0|R*N.scaleX*w],se[Ee++]=be}break;case 3:if(le=!0,this.adobe&&this.adobe.transformCode)le=!0;else if(typeof this.opts.colorTransform<"u")le=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],O=this.components[2];for(J=0;J<M;J++){A=y.lines[0|J*y.scaleY*S],C=N.lines[0|J*N.scaleY*S],_=O.lines[0|J*O.scaleY*S];for(R=0;R<k;R++){if(!le)W=A[0|R*y.scaleX*w],Se=C[0|R*N.scaleX*w],Me=_[0|R*O.scaleX*w];else be=A[0|R*y.scaleX*w],Y=C[0|R*N.scaleX*w],Le=_[0|R*O.scaleX*w],W=g(be+1.402*(Le-128)),Se=g(be-0.3441363*(Y-128)-0.71413636*(Le-128)),Me=g(be+1.772*(Y-128));se[Ee++]=W,se[Ee++]=Se,se[Ee++]=Me}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(le=!1,this.adobe&&this.adobe.transformCode)le=!0;else if(typeof this.opts.colorTransform<"u")le=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],O=this.components[2],T=this.components[3];for(J=0;J<M;J++){A=y.lines[0|J*y.scaleY*S],C=N.lines[0|J*N.scaleY*S],_=O.lines[0|J*O.scaleY*S],L=T.lines[0|J*T.scaleY*S];for(R=0;R<k;R++){if(!le)ae=A[0|R*y.scaleX*w],ie=C[0|R*N.scaleX*w],v=_[0|R*O.scaleX*w],de=L[0|R*T.scaleX*w];else be=A[0|R*y.scaleX*w],Y=C[0|R*N.scaleX*w],Le=_[0|R*O.scaleX*w],de=L[0|R*T.scaleX*w],ae=255-g(be+1.402*(Le-128)),ie=255-g(be-0.3441363*(Y-128)-0.71413636*(Le-128)),v=255-g(be+1.772*(Y-128));se[Ee++]=255-ae,se[Ee++]=255-ie,se[Ee++]=255-v,se[Ee++]=255-de}}break;default:throw Error("Unsupported color mode")}return se},copyToImageData:function(k,M){var{width:w,height:S,data:y}=k,N=this.getData(w,S),O=0,T=0,A,C,_,L,R,J,Ee,be,Y;switch(this.components.length){case 1:for(C=0;C<S;C++)for(A=0;A<w;A++)if(_=N[O++],y[T++]=_,y[T++]=_,y[T++]=_,M)y[T++]=255;break;case 3:for(C=0;C<S;C++)for(A=0;A<w;A++)if(Ee=N[O++],be=N[O++],Y=N[O++],y[T++]=Ee,y[T++]=be,y[T++]=Y,M)y[T++]=255;break;case 4:for(C=0;C<S;C++)for(A=0;A<w;A++)if(R=N[O++],J=N[O++],_=N[O++],L=N[O++],Ee=255-g(R*(1-L/255)+L),be=255-g(J*(1-L/255)+L),Y=255-g(_*(1-L/255)+L),y[T++]=Ee,y[T++]=be,y[T++]=Y,M)y[T++]=255;break;default:throw Error("Unsupported color mode")}}};var p=0,b=0;function m($=0){var k=p+$;if(k>b){var M=Math.ceil((k-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}p=k}return l.resetMaxMemoryUsage=function($){p=0,b=$},l.getBytesAllocated=function(){return p},l.requestMemoryAllocation=m,l}();if(typeof Wu<"u")Wu.exports=Jd;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Jd;function Jd(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 _u;s.opts=r,_u.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{_u.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 zd=He((EP,qd)=>{var Y$=Kd(),Q$=Bd();qd.exports={encode:Y$,decode:Q$}});var Uu=He((vP,Qd)=>{var V$=st("util"),Yd=st("stream"),_t=Qd.exports=function(){Yd.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};V$.inherits(_t,Yd);_t.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))};_t.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};_t.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()};_t.prototype.destroySoon=_t.prototype.end;_t.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};_t.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};_t.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)};_t.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)};_t.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 ju=He((Z$)=>{var xn=[{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]}];Z$.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<xn.length;a++){let u=xn[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};Z$.getInterlaceIterator=function(e){return function(t,n,r){let i=t%xn[r].x.length,s=(t-i)/xn[r].x.length*8+xn[r].x[i],o=n%xn[r].y.length,a=(n-o)/xn[r].y.length*8+xn[r].y[o];return s*4+a*e*4}}});var Ku=He((MP,Vd)=>{Vd.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 Ju=He((IP,Xd)=>{var ek=ju(),tk=Ku();function Zd(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var Qr=Xd.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=ek.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Zd(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Zd(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};Qr.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Qr.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}};Qr.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}};Qr.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}};Qr.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=tk(c,u,l);t[o]=a+f}};Qr.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 th=He((NP,eh)=>{var nk=st("util"),Dd=Uu(),rk=Ju(),ik=eh.exports=function(e){Dd.call(this);let t=[],n=this;this._filter=new rk(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};nk.inherits(ik,Dd)});var Vr=He((PP,nh)=>{nh.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 zu=He((OP,rh)=>{var Bu=[];(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;Bu[e]=t}})();var qu=rh.exports=function(){this._crc=-1};qu.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=Bu[(this._crc^e[t])&255]^this._crc>>>8;return!0};qu.prototype.crc32=function(){return this._crc^-1};qu.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=Bu[(t^e[n])&255]^t>>>8;return t^-1}});var Yu=He((FP,ih)=>{var Ze=Vr(),sk=zu(),et=ih.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(){}};et.prototype.start=function(){this.read(Ze.PNG_SIGNATURE.length,this._parseSignature.bind(this))};et.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))};et.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 sk,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))};et.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};et.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};et.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))};et.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};et.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()};et.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};et.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()};et.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};et.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()};et.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};et.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ze.GAMMA_DIVISION),this._handleChunkEnd()};et.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};et.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()};et.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};et.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Qu=He((fk)=>{var sh=ju(),ok=[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]}],ak=[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 uk(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 ck(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);ok[r](t,i,f,s),s+=r}return s}function lk(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);ak[r](t,f,d,s)}i.resetAfterLine()}}fk.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=uk(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=sh.getImagePasses(n,r),d=sh.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=ck(f[h],u,d,s,e,l);else lk(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 Vu=He((HP,oh)=>{function hk(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 gk(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 mk(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}}oh.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)hk(e,c,i,s,u);else{if(a)gk(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);mk(e,c,i,s,r)}}return c}});var ch=He((TP,uh)=>{var pk=st("util"),Zu=st("zlib"),ah=Uu(),bk=th(),wk=Yu(),$k=Qu(),kk=Vu(),Vt=uh.exports=function(e){ah.call(this),this._parser=new wk(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()};pk.inherits(Vt,ah);Vt.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};Vt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Zu.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,Zu.Z_MIN_CHUNK);this._inflate=Zu.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)};Vt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new bk(this._bitmapInfo)};Vt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Vt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Vt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Vt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Vt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Vt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=$k.dataToBitMap(e,this._bitmapInfo);t=kk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var fh=He((AP,lh)=>{var Ot=Vr();lh.exports=function(e,t,n,r){let i=[Ot.COLORTYPE_COLOR_ALPHA,Ot.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[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=Ot.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=Ot.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,p,b,m=o;switch(r.inputColorType){case Ot.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],p=s[l+1],b=s[l+2];break;case Ot.COLORTYPE_COLOR:g=s[l],p=s[l+1],b=s[l+2];break;case Ot.COLORTYPE_ALPHA:m=s[l+1],g=s[l],p=g,b=g;break;case Ot.COLORTYPE_GRAYSCALE:g=s[l],p=g,b=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),p=Math.min(Math.max(Math.round((1-m)*d.green+m*p),0),o),b=Math.min(Math.max(Math.round((1-m)*d.blue+m*b),0),o)}return{red:g,green:p,blue:b,alpha:m}}for(let g=0;g<n;g++)for(let p=0;p<t;p++){let b=h(s,l);switch(r.colorType){case Ot.COLORTYPE_COLOR_ALPHA:case Ot.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[f]=b.red,c[f+1]=b.green,c[f+2]=b.blue,i)c[f+3]=b.alpha}else if(c.writeUInt16BE(b.red,f),c.writeUInt16BE(b.green,f+2),c.writeUInt16BE(b.blue,f+4),i)c.writeUInt16BE(b.alpha,f+6);break;case Ot.COLORTYPE_ALPHA:case Ot.COLORTYPE_GRAYSCALE:{let m=(b.red+b.green+b.blue)/3;if(r.bitDepth===8){if(c[f]=m,i)c[f+1]=b.alpha}else if(c.writeUInt16BE(m,f),i)c.writeUInt16BE(b.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=u}return c}});var gh=He((LP,hh)=>{var dh=Ku();function yk(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Ek(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function vk(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 Sk(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 Mk(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 Ik(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 Nk(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 Pk(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 Ok(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]-dh(a,u,c);r[i+o]=l}}function Fk(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]-dh(o,a,u);i+=Math.abs(c)}return i}var Rk={0:yk,1:vk,2:Mk,3:Nk,4:Ok},Hk={0:Ek,1:Sk,2:Ik,3:Pk,4:Fk};hh.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=Hk[s[h]](e,u,o,i);if(g<d)l=s[h],d=g}}c[a]=l,a++,Rk[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var Xu=He((xP,mh)=>{var ut=Vr(),Tk=zu(),Ak=fh(),Lk=gh(),xk=st("zlib"),Cn=mh.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||xk.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")};Cn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Cn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Cn.prototype.filterData=function(e,t,n){let r=Ak(e,t,n,this._options),i=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Lk(r,t,n,this._options,i)};Cn.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(Tk.crc32(r.slice(4,r.length-4)),r.length-4),r};Cn.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)};Cn.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)};Cn.prototype.packIDAT=function(e){return this._packChunk(ut.TYPE_IDAT,e)};Cn.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var $h=He((CP,wh)=>{var Ck=st("util"),ph=st("stream"),Gk=Vr(),_k=Xu(),bh=wh.exports=function(e){ph.call(this);let t=e||{};this._packer=new _k(t),this._deflate=this._packer.createDeflate(),this.readable=!0};Ck.inherits(bh,ph);bh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(Gk.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 Mh=He((Di,Sh)=>{var kh=st("assert").ok,Zr=st("zlib"),Wk=st("util"),yh=st("buffer").kMaxLength;function br(e){if(!(this instanceof br))return new br(e);if(e&&e.chunkSize<Zr.Z_MIN_CHUNK)e.chunkSize=Zr.Z_MIN_CHUNK;if(Zr.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 Uk(e){return new br(e)}function Eh(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}br.prototype._processChunk=function(e,t,n){if(typeof n==="function")return Zr.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,p){if(r._hadError)return;let b=s-p;if(kh(b>=0,"have should not go down"),b>0){let m=r._buffer.slice(r._offset,r._offset+b);if(r._offset+=b,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(p===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(p===0)return a+=i-g,i=g,!0;return!1}kh(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>=yh)throw Eh(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+yh.toString(16)+" bytes");let h=Buffer.concat(u,c);return Eh(this),h};Wk.inherits(br,Zr.Inflate);function jk(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=Zr.Z_FINISH;return e._processChunk(t,n)}function vh(e,t){return jk(new br(t),e)}Sh.exports=Di=vh;Di.Inflate=br;Di.createInflate=Uk;Di.inflateSync=vh});var Du=He((GP,Nh)=>{var Ih=Nh.exports=function(e){this._buffer=e,this._reads=[]};Ih.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};Ih.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 Ph=He((Bk)=>{var Kk=Du(),Jk=Ju();Bk.process=function(e,t){let n=[],r=new Kk(e);return new Jk(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Hh=He((WP,Rh)=>{var Oh=!0,Fh=st("zlib"),zk=Mh();if(!Fh.deflateSync)Oh=!1;var Yk=Du(),Qk=Ph(),Vk=Yu(),Zk=Qu(),Xk=Vu();Rh.exports=function(e,t){if(!Oh)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 Yk(e);if(new Vk(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 p=Buffer.concat(f);f.length=0;let b;if(i.interlace)b=Fh.inflateSync(p);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=zk(p,{chunkSize:w,maxLength:w})}if(p=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let m=Qk.process(b,i);p=null;let $=Zk.dataToBitMap(m,i);m=null;let k=Xk($,i,t.skipRescale);return i.data=k,i.gamma=c||0,i}});var xh=He((UP,Lh)=>{var Th=!0,Ah=st("zlib");if(!Ah.deflateSync)Th=!1;var Dk=Vr(),ey=Xu();Lh.exports=function(e,t){if(!Th)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new ey(t||{}),i=[];if(i.push(Buffer.from(Dk.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=Ah.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 Ch=He((ry)=>{var ty=Hh(),ny=xh();ry.read=function(e,t){return ty(e,t||{})};ry.write=function(e,t){return ny(e,t)}});var _h=He((ly)=>{var oy=st("util"),Gh=st("stream"),ay=ch(),uy=$h(),cy=Ch(),ct=ly.PNG=function(e){if(Gh.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 ay(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 uy(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"))};oy.inherits(ct,Gh);ct.sync=cy;ct.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};ct.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};ct.prototype.write=function(e){return this._parser.write(e),!0};ct.prototype.end=function(e){this._parser.end(e)};ct.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};ct.prototype._gamma=function(e){this.gamma=e};ct.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};ct.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)};ct.prototype.bitblt=function(e,t,n,r,i,s,o){return ct.bitblt(this,e,t,n,r,i,s,o),this};ct.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}};ct.prototype.adjustGamma=function(){ct.adjustGamma(this)}});import{spawnSync as PN}from"node:child_process";import{isMainThread as ON}from"node:worker_threads";import{parseArgs as EN}from"node:util";var ot={name:"@kecan0406/ttheme",version:"1.2.0",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","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 UI,readFileSync as u0}from"node:fs";import{styleText as Eo}from"node:util";import{stdout as hd,stdin as e$}from"node:process";import t$ from"node:readline";var Vf=(()=>{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}})(),Zf=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Xf=(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 _0=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,W0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Df=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,U0=/\t{1,1000}/y,ed=/[\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,j0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,K0=/\p{M}+/gu,J0={limit:1/0,ellipsis:""},td=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?td(i,J0,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=[[j0,f],[_0,0],[W0,a],[U0,u],[ed,c],[Df,d]],g=0,p=0,b=e.length,m=0,$=!1,k=b,M=Math.max(0,r-s),w=0,S=0,y=0,N=0;e:while(!0){if(S>w||p>=b&&p>g){let O=e.slice(w,S)||e.slice(g,p);m=0;for(let T of O.replaceAll(K0,"")){let A=T.codePointAt(0)||0;if(Zf(A))N=2;else if(Xf(A))N=d;else N=f;if(y+N>M)k=Math.min(k,Math.max(w,g)+m);if(y+N>r){$=!0;break e}m+=T.length,y+=N}w=S=0}if(p>=b)break e;for(let O=0,T=h.length;O<T;O++){let[A,C]=h[O];if(A.lastIndex=p,A.test(e)){if(m=A===Df?Vf(e.slice(p,A.lastIndex)):A===ed?1:A.lastIndex-p,N=m*C,y+N>M)k=Math.min(k,p+Math.floor((M-y)/C));if(y+N>r){$=!0;break e}y+=N,w=g,S=p,p=g=A.lastIndex;continue e}}p+=1}return{width:$?M:y,index:$?k:b,truncated:$,ellipsed:$&&r>=s}},nd=td;var B0={limit:1/0,ellipsis:"",ellipsisWidth:0},q0=(e,t={})=>{return nd(e,B0,t).width},$e=q0;var wo="\x1B",ad="›",z0=39,bu="\x07",ud="[",Y0="]",cd="m",wu=`${Y0}8;;`,rd=new RegExp(`(?:\\${ud}(?<code>\\d+)m|\\${wu}(?<uri>.*)${bu})`,"y"),id=(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},sd=(e)=>`${wo}${ud}${e}${cd}`,od=(e)=>`${wo}${wu}${e}${bu}`,pu=(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===wo||f===ad)i=!0,s=t.startsWith(wu,l+1);if(i){if(s){if(f===bu)i=!1,s=!1}else if(f===cd)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()},Q0=(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("")},V0=(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)??"",p=g.trimStart();if(g.length!==p.length)a[a.length-1]=p,u=$e(p)}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,p=1+Math.floor((h-g-1)/t);if(Math.floor((h-1)/t)<p)a.push("");pu(a,d,t),u=$e(a.at(-1)??"");continue}if(u+h>t&&u&&h){if(n.wordWrap===!1&&u<t){pu(a,d,t),u=$e(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>t&&n.wordWrap===!1){pu(a,d,t),u=$e(a.at(-1)??"");continue}a[a.length-1]+=d,u+=h}if(n.trim!==!1)a=a.map((f)=>Q0(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===wo||d===ad){rd.lastIndex=f+1;let g=rd.exec(c)?.groups;if(g?.code!==void 0){let p=Number.parseFloat(g.code);i=p===z0?void 0:p}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[f+1]===`
4
- `){if(s)r+=od("");let h=i?id(i):void 0;if(i&&h)r+=sd(h)}else if(d===`
5
- `){if(i&&id(i))r+=sd(i);if(s)r+=od(s)}}return r},Z0=/\r?\n/;function Nn(e,t,n){return String(e).normalize().split(Z0).map((r)=>V0(r,t,n)).join(`
6
- `)}var mt=bo(ku(),1);function jr(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?jr(s,t<0?-1:1,n):s}function $o(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 n$=["up","down","left","right","space","enter","cancel"],r$=["January","February","March","April","May","June","July","August","September","October","November","December"],at={actions:new Set(n$),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:[...r$],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 gd(e,t){if(typeof e=="string")return at.aliases.get(e)===t;for(let n of e)if(n!==void 0&&gd(n,t))return!0;return!1}function i$(e,t){if(e===t)return;let n=e.split(`
2
+ import{createRequire as i$}from"node:module";var Z0=Object.create;var{getPrototypeOf:X0,defineProperty:ad,getOwnPropertyNames:D0}=Object;var e$=Object.prototype.hasOwnProperty;function t$(e){return this[e]}var n$,r$,Eo=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?n$??=new WeakMap:r$??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?Z0(X0(e)):{};let o=t||!e||!e.__esModule?ad(n,"default",{value:e,enumerable:!0}):n;for(let a of D0(e))if(!e$.call(o,a))ad(o,a,{get:t$.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Te=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var st=i$(import.meta.url);var Nu=Te((iP,Ed)=>{var Iu={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"},$$={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},k$={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?Iu.up():"");if(e)t+=Iu.left;return t}};Ed.exports={cursor:Iu,scroll:$$,erase:k$,beep:"\x07"}});var th=Te((_P,Ao)=>{var eh=eh||function(e){return Buffer.from(e).toString("base64")};function gk(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),p=Array(64),b=[],m=0,$=7,k=Array(64),S=Array(64),w=Array(64),M=Array(256),y=Array(2048),N,O=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],T=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],G=[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],x=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],F=[0,1,2,3,4,5,6,7,8,9,10,11],J=[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(E){var _=[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 B=0;B<64;B++){var U=r((_[B]*E+50)/100);if(U<1)U=1;else if(U>255)U=255;i[O[B]]=U}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 ne=0;ne<64;ne++){var me=r((te[ne]*E+50)/100);if(me<1)me=1;else if(me>255)me=255;s[O[ne]]=me}var pe=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var He=0;He<8;He++)for(var P=0;P<8;P++)o[Ue]=1/(i[O[Ue]]*pe[He]*pe[P]*8),a[Ue]=1/(s[O[Ue]]*pe[He]*pe[P]*8),Ue++}function Y(E,_){var B=0,U=0,te=[];for(var ne=1;ne<=16;ne++){for(var me=1;me<=E[ne];me++)te[_[U]]=[],te[_[U]][0]=B,te[_[U]][1]=ne,U++,B++;B*=2}return te}function xe(){u=Y(T,A),c=Y(x,F),l=Y(C,G),f=Y(J,Ee)}function de(){var E=1,_=2;for(var B=1;B<=15;B++){for(var U=E;U<_;U++)h[32767+U]=B,d[32767+U]=[],d[32767+U][1]=B,d[32767+U][0]=U;for(var te=-(_-1);te<=-E;te++)h[32767+te]=B,d[32767+te]=[],d[32767+te][1]=B,d[32767+te][0]=_-1+te;E<<=1,_<<=1}}function ae(){for(var E=0;E<256;E++)y[E]=19595*E,y[E+256>>0]=38470*E,y[E+512>>0]=7471*E+32768,y[E+768>>0]=-11059*E,y[E+1024>>0]=-21709*E,y[E+1280>>0]=32768*E+8421375,y[E+1536>>0]=-27439*E,y[E+1792>>0]=-5329*E}function ie(E){var _=E[0],B=E[1]-1;while(B>=0){if(_&1<<B)m|=1<<$;if(B--,$--,$<0){if(m==255)v(255),v(0);else v(m);$=7,m=0}}}function v(E){b.push(E)}function W(E){v(E>>8&255),v(E&255)}function Se(E,_){var B,U,te,ne,me,pe,Ue,He,P=0,L,V=8,Ge=64;for(L=0;L<V;++L){B=E[P],U=E[P+1],te=E[P+2],ne=E[P+3],me=E[P+4],pe=E[P+5],Ue=E[P+6],He=E[P+7];var re=B+He,ce=B-He,Ne=U+Ue,q=U-Ue,we=te+pe,tt=te-pe,Le=ne+me,Nt=ne-me,qt=re+Le,gr=re-Le,Br=Ne+we,qr=Ne-we;E[P]=qt+Br,E[P+4]=qt-Br;var ji=(qr+gr)*0.707106781;E[P+2]=gr+ji,E[P+6]=gr-ji,qt=Nt+tt,Br=tt+q,qr=q+ce;var Ki=(qt-qr)*0.382683433,wo=0.5411961*qt+Ki,Ji=1.306562965*qr+Ki,Bi=Br*0.707106781,qi=ce+Bi,zi=ce-Bi;E[P+5]=zi+wo,E[P+3]=zi-wo,E[P+1]=qi+Ji,E[P+7]=qi-Ji,P+=8}P=0;for(L=0;L<V;++L){B=E[P],U=E[P+8],te=E[P+16],ne=E[P+24],me=E[P+32],pe=E[P+40],Ue=E[P+48],He=E[P+56];var Yf=B+He,yu=B-He,Qf=U+Ue,Vf=U-Ue,Zf=te+pe,Xf=te-pe,Df=ne+me,V0=ne-me,Yi=Yf+Df,Eu=Yf-Df,$o=Qf+Zf,ko=Qf-Zf;E[P]=Yi+$o,E[P+32]=Yi-$o;var ed=(ko+Eu)*0.707106781;E[P+16]=Eu+ed,E[P+48]=Eu-ed,Yi=V0+Xf,$o=Xf+Vf,ko=Vf+yu;var td=(Yi-ko)*0.382683433,nd=0.5411961*Yi+td,rd=1.306562965*ko+td,id=$o*0.707106781,sd=yu+id,od=yu-id;E[P+40]=od+nd,E[P+24]=od-nd,E[P+8]=sd+rd,E[P+56]=sd-rd,P++}var yo;for(L=0;L<Ge;++L)yo=E[L]*_[L],g[L]=yo>0?yo+0.5|0:yo-0.5|0;return g}function Ie(){W(65504),W(16),v(74),v(70),v(73),v(70),v(0),v(1),v(1),v(0),W(1),W(1),v(0),v(0)}function le(E){if(!E)return;if(W(65505),E[0]===69&&E[1]===120&&E[2]===105&&E[3]===102)W(E.length+2);else W(E.length+5+2),v(69),v(120),v(105),v(102),v(0);for(var _=0;_<E.length;_++)v(E[_])}function fe(E,_){W(65472),W(17),v(8),W(_),W(E),v(3),v(1),v(17),v(0),v(2),v(17),v(1),v(3),v(17),v(1)}function se(){W(65499),W(132),v(0);for(var E=0;E<64;E++)v(i[E]);v(1);for(var _=0;_<64;_++)v(s[_])}function H(){W(65476),W(418),v(0);for(var E=0;E<16;E++)v(T[E+1]);for(var _=0;_<=11;_++)v(A[_]);v(16);for(var B=0;B<16;B++)v(C[B+1]);for(var U=0;U<=161;U++)v(G[U]);v(1);for(var te=0;te<16;te++)v(x[te+1]);for(var ne=0;ne<=11;ne++)v(F[ne]);v(17);for(var me=0;me<16;me++)v(J[me+1]);for(var pe=0;pe<=161;pe++)v(Ee[pe])}function R(E){if(typeof E>"u"||E.constructor!==Array)return;E.forEach((_)=>{if(typeof _!=="string")return;W(65534);var B=_.length;W(B+2);var U;for(U=0;U<B;U++)v(_.charCodeAt(U))})}function Fe(){W(65498),W(12),v(3),v(1),v(0),v(2),v(17),v(3),v(17),v(0),v(63),v(0)}function Q(E,_,B,U,te){var ne=te[0],me=te[240],pe,Ue=16,He=63,P=64,L=Se(E,_);for(var V=0;V<P;++V)p[O[V]]=L[V];var Ge=p[0]-B;if(B=p[0],Ge==0)ie(U[0]);else pe=32767+Ge,ie(U[h[pe]]),ie(d[pe]);var re=63;for(;re>0&&p[re]==0;re--);if(re==0)return ie(ne),B;var ce=1,Ne;while(ce<=re){var q=ce;for(;p[ce]==0&&ce<=re;++ce);var we=ce-q;if(we>=Ue){Ne=we>>4;for(var tt=1;tt<=Ne;++tt)ie(me);we=we&15}pe=32767+p[ce],ie(te[(we<<4)+h[pe]]),ie(d[pe]),ce++}if(re!=He)ie(ne);return B}function oe(){var E=String.fromCharCode;for(var _=0;_<256;_++)M[_]=E(_)}this.encode=function(E,_){var B=new Date().getTime();if(_)It(_);b=[],m=0,$=7,W(65496),Ie(),R(E.comments),le(E.exifBuffer),se(),fe(E.width,E.height),H(),Fe();var U=0,te=0,ne=0;m=0,$=7,this.encode.displayName="_encode_";var{data:me,width:pe,height:Ue}=E,He=pe*4,P=pe*3,L,V=0,Ge,re,ce,Ne,q,we,tt,Le;while(V<Ue){L=0;while(L<He){Ne=He*V+L,q=Ne,we=-1,tt=0;for(Le=0;Le<64;Le++){if(tt=Le>>3,we=(Le&7)*4,q=Ne+tt*He+we,V+tt>=Ue)q-=He*(V+1+tt-Ue);if(L+we>=He)q-=L+we-He+4;Ge=me[q++],re=me[q++],ce=me[q++],k[Le]=(y[Ge]+y[re+256>>0]+y[ce+512>>0]>>16)-128,S[Le]=(y[Ge+768>>0]+y[re+1024>>0]+y[ce+1280>>0]>>16)-128,w[Le]=(y[Ge+1280>>0]+y[re+1536>>0]+y[ce+1792>>0]>>16)-128}U=Q(k,o,U,u,l),te=Q(S,a,te,c,f),ne=Q(w,a,ne,c,f),L+=32}V+=8}if($>=0){var Nt=[];Nt[1]=$+1,Nt[0]=(1<<$+1)-1,ie(Nt)}if(W(65497),typeof Ao>"u")return new Uint8Array(b);return Buffer.from(b);var qt,gr};function It(E){if(E<=0)E=1;if(E>100)E=100;if(N==E)return;var _=0;if(E<50)_=Math.floor(5000/E);else _=Math.floor(200-E*2);be(_),N=E}function Ct(){var E=new Date().getTime();if(!e)e=50;oe(),xe(),de(),ae(),It(e);var _=new Date().getTime()-E}Ct()}if(typeof Ao<"u")Ao.exports=Dd;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Dd;function Dd(e,t){if(typeof t>"u")t=50;var n=new gk(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var rh=Te((GP,zu)=>{var qu=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){var S=0,w=[],M,y,N=16;while(N>0&&!$[N-1])N--;w.push({children:[],index:0});var O=w[0],T;for(M=0;M<N;M++){for(y=0;y<$[M];y++){O=w.pop(),O.children[O.index]=k[S];while(O.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");O=w.pop()}O.index++,w.push(O);while(w.length<=M)w.push(T={children:[],index:0}),O.children[O.index]=T.children,O=T;S++}if(M+1<N)w.push(T={children:[],index:0}),O.children[O.index]=T.children,O=T}return w[0].children}function d($,k,S,w,M,y,N,O,T,A){var{precision:C,samplesPerLine:G,scanLines:x,mcusPerLine:F,progressive:J,maxH:Ee,maxV:be}=S,Y=k,xe=0,de=0;function ae(){if(de>0)return de--,xe>>de&1;if(xe=$[k++],xe==255){var P=$[k++];if(P)throw Error("unexpected marker: "+(xe<<8|P).toString(16))}return de=7,xe>>>7}function ie(P){var L=P,V;while((V=ae())!==null){if(L=L[V],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function v(P){var L=0;while(P>0){var V=ae();if(V===null)return;L=L<<1|V,P--}return L}function W(P){var L=v(P);if(L>=1<<P-1)return L;return L+(-1<<P)+1}function Se(P,L){var V=ie(P.huffmanTableDC),Ge=V===0?0:W(V);L[0]=P.pred+=Ge;var re=1;while(re<64){var ce=ie(P.huffmanTableAC),Ne=ce&15,q=ce>>4;if(Ne===0){if(q<15)break;re+=16;continue}re+=q;var we=t[re];L[we]=W(Ne),re++}}function Ie(P,L){var V=ie(P.huffmanTableDC),Ge=V===0?0:W(V)<<T;L[0]=P.pred+=Ge}function le(P,L){L[0]|=ae()<<T}var fe=0;function se(P,L){if(fe>0){fe--;return}var V=y,Ge=N;while(V<=Ge){var re=ie(P.huffmanTableAC),ce=re&15,Ne=re>>4;if(ce===0){if(Ne<15){fe=v(Ne)+(1<<Ne)-1;break}V+=16;continue}V+=Ne;var q=t[V];L[q]=W(ce)*(1<<T),V++}}var H=0,R;function Fe(P,L){var V=y,Ge=N,re=0;while(V<=Ge){var ce=t[V],Ne=L[ce]<0?-1:1;switch(H){case 0:var q=ie(P.huffmanTableAC),we=q&15,re=q>>4;if(we===0)if(re<15)fe=v(re)+(1<<re),H=4;else re=16,H=1;else{if(we!==1)throw Error("invalid ACn encoding");R=W(we),H=re?2:3}continue;case 1:case 2:if(L[ce])L[ce]+=(ae()<<T)*Ne;else if(re--,re===0)H=H==2?3:0;break;case 3:if(L[ce])L[ce]+=(ae()<<T)*Ne;else L[ce]=R<<T,H=0;break;case 4:if(L[ce])L[ce]+=(ae()<<T)*Ne;break}V++}if(H===4){if(fe--,fe===0)H=0}}function Q(P,L,V,Ge,re){var ce=V/F|0,Ne=V%F,q=ce*P.v+Ge,we=Ne*P.h+re;if(P.blocks[q]===void 0&&A.tolerantDecoding)return;L(P,P.blocks[q][we])}function oe(P,L,V){var Ge=V/P.blocksPerLine|0,re=V%P.blocksPerLine;if(P.blocks[Ge]===void 0&&A.tolerantDecoding)return;L(P,P.blocks[Ge][re])}var It=w.length,Ct,E,_,B,U,te;if(J)if(y===0)te=O===0?Ie:le;else te=O===0?se:Fe;else te=Se;var ne=0,me,pe;if(It==1)pe=w[0].blocksPerLine*w[0].blocksPerColumn;else pe=F*S.mcusPerColumn;if(!M)M=pe;var Ue,He;while(ne<pe){for(E=0;E<It;E++)w[E].pred=0;if(fe=0,It==1){Ct=w[0];for(U=0;U<M;U++)oe(Ct,te,ne),ne++}else for(U=0;U<M;U++){for(E=0;E<It;E++){Ct=w[E],Ue=Ct.h,He=Ct.v;for(_=0;_<He;_++)for(B=0;B<Ue;B++)Q(Ct,te,ne,_,B)}if(ne++,ne===pe)break}if(ne===pe)do{if($[k]===255){if($[k+1]!==0)break}k+=1}while(k<$.length-2);if(de=0,me=$[k]<<8|$[k+1],me<65280)throw Error("marker was not found");if(me>=65488&&me<=65495)k+=2;else break}return k-Y}function h($,k){var S=[],w=k.blocksPerLine,M=k.blocksPerColumn,y=w<<3,N=new Int32Array(64),O=new Uint8Array(64);function T(Y,xe,de){var ae=k.quantizationTable,ie,v,W,Se,Ie,le,fe,se,H,R=de,Fe;for(Fe=0;Fe<64;Fe++)R[Fe]=Y[Fe]*ae[Fe];for(Fe=0;Fe<8;++Fe){var Q=8*Fe;if(R[1+Q]==0&&R[2+Q]==0&&R[3+Q]==0&&R[4+Q]==0&&R[5+Q]==0&&R[6+Q]==0&&R[7+Q]==0){H=u*R[0+Q]+512>>10,R[0+Q]=H,R[1+Q]=H,R[2+Q]=H,R[3+Q]=H,R[4+Q]=H,R[5+Q]=H,R[6+Q]=H,R[7+Q]=H;continue}ie=u*R[0+Q]+128>>8,v=u*R[4+Q]+128>>8,W=R[2+Q],Se=R[6+Q],Ie=c*(R[1+Q]-R[7+Q])+128>>8,se=c*(R[1+Q]+R[7+Q])+128>>8,le=R[3+Q]<<4,fe=R[5+Q]<<4,H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=W*a+Se*o+128>>8,W=W*o-Se*a+128>>8,Se=H,H=Ie-fe+1>>1,Ie=Ie+fe+1>>1,fe=H,H=se+le+1>>1,le=se-le+1>>1,se=H,H=ie-Se+1>>1,ie=ie+Se+1>>1,Se=H,H=v-W+1>>1,v=v+W+1>>1,W=H,H=Ie*s+se*i+2048>>12,Ie=Ie*i-se*s+2048>>12,se=H,H=le*r+fe*n+2048>>12,le=le*n-fe*r+2048>>12,fe=H,R[0+Q]=ie+se,R[7+Q]=ie-se,R[1+Q]=v+fe,R[6+Q]=v-fe,R[2+Q]=W+le,R[5+Q]=W-le,R[3+Q]=Se+Ie,R[4+Q]=Se-Ie}for(Fe=0;Fe<8;++Fe){var oe=Fe;if(R[8+oe]==0&&R[16+oe]==0&&R[24+oe]==0&&R[32+oe]==0&&R[40+oe]==0&&R[48+oe]==0&&R[56+oe]==0){H=u*de[Fe+0]+8192>>14,R[0+oe]=H,R[8+oe]=H,R[16+oe]=H,R[24+oe]=H,R[32+oe]=H,R[40+oe]=H,R[48+oe]=H,R[56+oe]=H;continue}ie=u*R[0+oe]+2048>>12,v=u*R[32+oe]+2048>>12,W=R[16+oe],Se=R[48+oe],Ie=c*(R[8+oe]-R[56+oe])+2048>>12,se=c*(R[8+oe]+R[56+oe])+2048>>12,le=R[24+oe],fe=R[40+oe],H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=W*a+Se*o+2048>>12,W=W*o-Se*a+2048>>12,Se=H,H=Ie-fe+1>>1,Ie=Ie+fe+1>>1,fe=H,H=se+le+1>>1,le=se-le+1>>1,se=H,H=ie-Se+1>>1,ie=ie+Se+1>>1,Se=H,H=v-W+1>>1,v=v+W+1>>1,W=H,H=Ie*s+se*i+2048>>12,Ie=Ie*i-se*s+2048>>12,se=H,H=le*r+fe*n+2048>>12,le=le*n-fe*r+2048>>12,fe=H,R[0+oe]=ie+se,R[56+oe]=ie-se,R[8+oe]=v+fe,R[48+oe]=v-fe,R[16+oe]=W+le,R[40+oe]=W-le,R[24+oe]=Se+Ie,R[32+oe]=Se-Ie}for(Fe=0;Fe<64;++Fe){var It=128+(R[Fe]+8>>4);xe[Fe]=It<0?0:It>255?255:It}}m(y*M*8);var A,C;for(var G=0;G<M;G++){var x=G<<3;for(A=0;A<8;A++)S.push(new Uint8Array(y));for(var F=0;F<w;F++){T(k.blocks[G][F],O,N);var J=0,Ee=F<<3;for(C=0;C<8;C++){var be=S[x+C];for(A=0;A<8;A++)be[Ee+A]=O[J++]}}}return S}function g($){return $<0?0:$>255?255:$}l.prototype={load:function(k){var S=new XMLHttpRequest;S.open("GET",k,!0),S.responseType="arraybuffer",S.onload=function(){var w=new Uint8Array(S.response||S.mozResponseArrayBuffer);if(this.parse(w),this.onload)this.onload()}.bind(this),S.send(null)},parse:function(k){var S=this.opts.maxResolutionInMP*1000*1000,w=0,M=k.length;function y(){var q=k[w]<<8|k[w+1];return w+=2,q}function N(){var q=y(),we=k.subarray(w,w+q-2);return w+=we.length,we}function O(q){var we=1,tt=1,Le,Nt;for(Nt in q.components)if(q.components.hasOwnProperty(Nt)){if(Le=q.components[Nt],we<Le.h)we=Le.h;if(tt<Le.v)tt=Le.v}var qt=Math.ceil(q.samplesPerLine/8/we),gr=Math.ceil(q.scanLines/8/tt);for(Nt in q.components)if(q.components.hasOwnProperty(Nt)){Le=q.components[Nt];var Br=Math.ceil(Math.ceil(q.samplesPerLine/8)*Le.h/we),qr=Math.ceil(Math.ceil(q.scanLines/8)*Le.v/tt),ji=qt*Le.h,Ki=gr*Le.v,wo=Ki*ji,Ji=[];m(wo*256);for(var Bi=0;Bi<Ki;Bi++){var qi=[];for(var zi=0;zi<ji;zi++)qi.push(new Int32Array(64));Ji.push(qi)}Le.blocksPerLine=Br,Le.blocksPerColumn=qr,Le.blocks=Ji}q.maxH=we,q.maxV=tt,q.mcusPerLine=qt,q.mcusPerColumn=gr}var T=null,A=null,C=null,G,x,F=[],J=[],Ee=[],be=[],Y=y(),xe=-1;if(this.comments=[],Y!=65496)throw Error("SOI not found");Y=y();while(Y!=65497){var de,ae,ie;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 v=N();if(Y===65534){var W=String.fromCharCode.apply(null,v);this.comments.push(W)}if(Y===65504){if(v[0]===74&&v[1]===70&&v[2]===73&&v[3]===70&&v[4]===0)T={version:{major:v[5],minor:v[6]},densityUnits:v[7],xDensity:v[8]<<8|v[9],yDensity:v[10]<<8|v[11],thumbWidth:v[12],thumbHeight:v[13],thumbData:v.subarray(14,14+3*v[12]*v[13])}}if(Y===65505){if(v[0]===69&&v[1]===120&&v[2]===105&&v[3]===102&&v[4]===0)this.exifBuffer=v.subarray(5,v.length)}if(Y===65518){if(v[0]===65&&v[1]===100&&v[2]===111&&v[3]===98&&v[4]===101&&v[5]===0)A={version:v[6],flags0:v[7]<<8|v[8],flags1:v[9]<<8|v[10],transformCode:v[11]}}break;case 65499:var Se=y(),Ie=Se+w-2;while(w<Ie){var le=k[w++];m(256);var fe=new Int32Array(64);if(le>>4===0)for(ae=0;ae<64;ae++){var se=t[ae];fe[se]=k[w++]}else if(le>>4===1)for(ae=0;ae<64;ae++){var se=t[ae];fe[se]=y()}else throw Error("DQT: invalid table spec");F[le&15]=fe}break;case 65472:case 65473:case 65474:y(),G={},G.extended=Y===65473,G.progressive=Y===65474,G.precision=k[w++],G.scanLines=y(),G.samplesPerLine=y(),G.components={},G.componentsOrder=[];var H=G.scanLines*G.samplesPerLine;if(H>S){var R=Math.ceil((H-S)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${R}MP`)}var Fe=k[w++],Q,oe=0,It=0;for(de=0;de<Fe;de++){Q=k[w];var Ct=k[w+1]>>4,E=k[w+1]&15,_=k[w+2];if(Ct<=0||E<=0)throw Error("Invalid sampling factor, expected values above 0");G.componentsOrder.push(Q),G.components[Q]={h:Ct,v:E,quantizationIdx:_},w+=3}O(G),J.push(G);break;case 65476:var B=y();for(de=2;de<B;){var U=k[w++],te=new Uint8Array(16),ne=0;for(ae=0;ae<16;ae++,w++)ne+=te[ae]=k[w];m(16+ne);var me=new Uint8Array(ne);for(ae=0;ae<ne;ae++,w++)me[ae]=k[w];de+=17+ne,(U>>4===0?be:Ee)[U&15]=f(te,me)}break;case 65501:y(),x=y();break;case 65500:y(),y();break;case 65498:var pe=y(),Ue=k[w++],He=[],P;for(de=0;de<Ue;de++){P=G.components[k[w++]];var L=k[w++];P.huffmanTableDC=be[L>>4],P.huffmanTableAC=Ee[L&15],He.push(P)}var V=k[w++],Ge=k[w++],re=k[w++],ce=d(k,w,G,He,x,V,Ge,re>>4,re&15,this.opts);w+=ce;break;case 65535:if(k[w]!==255)w--;break;default:if(k[w-3]==255&&k[w-2]>=192&&k[w-2]<=254){w-=3;break}else if(Y===224||Y==225){if(xe!==-1)throw Error(`first unknown JPEG marker at offset ${xe.toString(16)}, second unknown JPEG marker ${Y.toString(16)} at offset ${(w-1).toString(16)}`);xe=w-1;let q=y();if(k[w+q-2]===255){w+=q-2;break}}throw Error("unknown JPEG marker "+Y.toString(16))}Y=y()}if(J.length!=1)throw Error("only single frame JPEGs supported");for(var de=0;de<J.length;de++){var Ne=J[de].components;for(var ae in Ne)Ne[ae].quantizationTable=F[Ne[ae].quantizationIdx],delete Ne[ae].quantizationIdx}this.width=G.samplesPerLine,this.height=G.scanLines,this.jfif=T,this.adobe=A,this.components=[];for(var de=0;de<G.componentsOrder.length;de++){var P=G.components[G.componentsOrder[de]];this.components.push({lines:h(G,P),scaleX:P.h/G.maxH,scaleY:P.v/G.maxV})}},getData:function(k,S){var w=this.width/k,M=this.height/S,y,N,O,T,A,C,G,x,F,J,Ee=0,be,Y,xe,de,ae,ie,v,W,Se,Ie,le,fe=k*S*this.components.length;m(fe);var se=new Uint8Array(fe);switch(this.components.length){case 1:y=this.components[0];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M];for(F=0;F<k;F++)be=A[0|F*y.scaleX*w],se[Ee++]=be}break;case 2:y=this.components[0],N=this.components[1];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M];for(F=0;F<k;F++)be=A[0|F*y.scaleX*w],se[Ee++]=be,be=C[0|F*N.scaleX*w],se[Ee++]=be}break;case 3:if(le=!0,this.adobe&&this.adobe.transformCode)le=!0;else if(typeof this.opts.colorTransform<"u")le=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],O=this.components[2];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M],G=O.lines[0|J*O.scaleY*M];for(F=0;F<k;F++){if(!le)W=A[0|F*y.scaleX*w],Se=C[0|F*N.scaleX*w],Ie=G[0|F*O.scaleX*w];else be=A[0|F*y.scaleX*w],Y=C[0|F*N.scaleX*w],xe=G[0|F*O.scaleX*w],W=g(be+1.402*(xe-128)),Se=g(be-0.3441363*(Y-128)-0.71413636*(xe-128)),Ie=g(be+1.772*(Y-128));se[Ee++]=W,se[Ee++]=Se,se[Ee++]=Ie}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(le=!1,this.adobe&&this.adobe.transformCode)le=!0;else if(typeof this.opts.colorTransform<"u")le=!!this.opts.colorTransform;y=this.components[0],N=this.components[1],O=this.components[2],T=this.components[3];for(J=0;J<S;J++){A=y.lines[0|J*y.scaleY*M],C=N.lines[0|J*N.scaleY*M],G=O.lines[0|J*O.scaleY*M],x=T.lines[0|J*T.scaleY*M];for(F=0;F<k;F++){if(!le)ae=A[0|F*y.scaleX*w],ie=C[0|F*N.scaleX*w],v=G[0|F*O.scaleX*w],de=x[0|F*T.scaleX*w];else be=A[0|F*y.scaleX*w],Y=C[0|F*N.scaleX*w],xe=G[0|F*O.scaleX*w],de=x[0|F*T.scaleX*w],ae=255-g(be+1.402*(xe-128)),ie=255-g(be-0.3441363*(Y-128)-0.71413636*(xe-128)),v=255-g(be+1.772*(Y-128));se[Ee++]=255-ae,se[Ee++]=255-ie,se[Ee++]=255-v,se[Ee++]=255-de}}break;default:throw Error("Unsupported color mode")}return se},copyToImageData:function(k,S){var{width:w,height:M,data:y}=k,N=this.getData(w,M),O=0,T=0,A,C,G,x,F,J,Ee,be,Y;switch(this.components.length){case 1:for(C=0;C<M;C++)for(A=0;A<w;A++)if(G=N[O++],y[T++]=G,y[T++]=G,y[T++]=G,S)y[T++]=255;break;case 3:for(C=0;C<M;C++)for(A=0;A<w;A++)if(Ee=N[O++],be=N[O++],Y=N[O++],y[T++]=Ee,y[T++]=be,y[T++]=Y,S)y[T++]=255;break;case 4:for(C=0;C<M;C++)for(A=0;A<w;A++)if(F=N[O++],J=N[O++],G=N[O++],x=N[O++],Ee=255-g(F*(1-x/255)+x),be=255-g(J*(1-x/255)+x),Y=255-g(G*(1-x/255)+x),y[T++]=Ee,y[T++]=be,y[T++]=Y,S)y[T++]=255;break;default:throw Error("Unsupported color mode")}}};var p=0,b=0;function m($=0){var k=p+$;if(k>b){var S=Math.ceil((k-b)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${S}MB`)}p=k}return l.resetMaxMemoryUsage=function($){p=0,b=$},l.getBytesAllocated=function(){return p},l.requestMemoryAllocation=m,l}();if(typeof zu<"u")zu.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 qu;s.opts=r,qu.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{qu.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 sh=Te((WP,ih)=>{var mk=th(),pk=rh();ih.exports={encode:mk,decode:pk}});var Yu=Te((UP,ah)=>{var bk=st("util"),oh=st("stream"),Gt=ah.exports=function(){oh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};bk.inherits(Gt,oh);Gt.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))};Gt.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};Gt.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()};Gt.prototype.destroySoon=Gt.prototype.end;Gt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Gt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Gt.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)};Gt.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)};Gt.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 Qu=Te((wk)=>{var Ln=[{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]}];wk.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<Ln.length;a++){let u=Ln[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};wk.getInterlaceIterator=function(e){return function(t,n,r){let i=t%Ln[r].x.length,s=(t-i)/Ln[r].x.length*8+Ln[r].x[i],o=n%Ln[r].y.length,a=(n-o)/Ln[r].y.length*8+Ln[r].y[o];return s*4+a*e*4}}});var Vu=Te((KP,uh)=>{uh.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 Zu=Te((JP,lh)=>{var yk=Qu(),Ek=Vu();function ch(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var ei=lh.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=yk.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:ch(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:ch(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};ei.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ei.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}};ei.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}};ei.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}};ei.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=Ek(c,u,l);t[o]=a+f}};ei.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 hh=Te((BP,dh)=>{var vk=st("util"),fh=Yu(),Mk=Zu(),Sk=dh.exports=function(e){fh.call(this);let t=[],n=this;this._filter=new Mk(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};vk.inherits(Sk,fh)});var ti=Te((qP,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 ec=Te((zP,mh)=>{var Xu=[];(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;Xu[e]=t}})();var Du=mh.exports=function(){this._crc=-1};Du.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=Xu[(this._crc^e[t])&255]^this._crc>>>8;return!0};Du.prototype.crc32=function(){return this._crc^-1};Du.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=Xu[(t^e[n])&255]^t>>>8;return t^-1}});var tc=Te((YP,ph)=>{var Ze=ti(),Ik=ec(),et=ph.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(){}};et.prototype.start=function(){this.read(Ze.PNG_SIGNATURE.length,this._parseSignature.bind(this))};et.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))};et.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 Ik,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))};et.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};et.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};et.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))};et.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};et.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()};et.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};et.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()};et.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};et.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()};et.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};et.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ze.GAMMA_DIVISION),this._handleChunkEnd()};et.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};et.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()};et.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};et.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var nc=Te((Hk)=>{var bh=Qu(),Nk=[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]}],Pk=[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 Ok(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 Rk(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);Nk[r](t,i,f,s),s+=r}return s}function Fk(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);Pk[r](t,f,d,s)}i.resetAfterLine()}}Hk.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=Ok(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=bh.getImagePasses(n,r),d=bh.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=Rk(f[h],u,d,s,e,l);else Fk(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 rc=Te((VP,wh)=>{function Ak(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 xk(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 Lk(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}}wh.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)Ak(e,c,i,s,u);else{if(a)xk(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);Lk(e,c,i,s,r)}}return c}});var yh=Te((ZP,kh)=>{var Ck=st("util"),ic=st("zlib"),$h=Yu(),_k=hh(),Gk=tc(),Wk=nc(),Uk=rc(),Vt=kh.exports=function(e){$h.call(this),this._parser=new Gk(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()};Ck.inherits(Vt,$h);Vt.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};Vt.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ic.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,ic.Z_MIN_CHUNK);this._inflate=ic.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)};Vt.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new _k(this._bitmapInfo)};Vt.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};Vt.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};Vt.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Vt.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Vt.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};Vt.prototype._complete=function(e){if(this.errord)return;let t;try{let n=Wk.dataToBitMap(e,this._bitmapInfo);t=Uk(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var vh=Te((XP,Eh)=>{var Rt=ti();Eh.exports=function(e,t,n,r){let i=[Rt.COLORTYPE_COLOR_ALPHA,Rt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[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=Rt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=Rt.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,p,b,m=o;switch(r.inputColorType){case Rt.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],p=s[l+1],b=s[l+2];break;case Rt.COLORTYPE_COLOR:g=s[l],p=s[l+1],b=s[l+2];break;case Rt.COLORTYPE_ALPHA:m=s[l+1],g=s[l],p=g,b=g;break;case Rt.COLORTYPE_GRAYSCALE:g=s[l],p=g,b=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),p=Math.min(Math.max(Math.round((1-m)*d.green+m*p),0),o),b=Math.min(Math.max(Math.round((1-m)*d.blue+m*b),0),o)}return{red:g,green:p,blue:b,alpha:m}}for(let g=0;g<n;g++)for(let p=0;p<t;p++){let b=h(s,l);switch(r.colorType){case Rt.COLORTYPE_COLOR_ALPHA:case Rt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[f]=b.red,c[f+1]=b.green,c[f+2]=b.blue,i)c[f+3]=b.alpha}else if(c.writeUInt16BE(b.red,f),c.writeUInt16BE(b.green,f+2),c.writeUInt16BE(b.blue,f+4),i)c.writeUInt16BE(b.alpha,f+6);break;case Rt.COLORTYPE_ALPHA:case Rt.COLORTYPE_GRAYSCALE:{let m=(b.red+b.green+b.blue)/3;if(r.bitDepth===8){if(c[f]=m,i)c[f+1]=b.alpha}else if(c.writeUInt16BE(m,f),i)c.writeUInt16BE(b.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=u}return c}});var Ih=Te((DP,Sh)=>{var Mh=Vu();function jk(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Kk(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Jk(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 Bk(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 qk(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 zk(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 Yk(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 Qk(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 Vk(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]-Mh(a,u,c);r[i+o]=l}}function Zk(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]-Mh(o,a,u);i+=Math.abs(c)}return i}var Xk={0:jk,1:Jk,2:qk,3:Yk,4:Vk},Dk={0:Kk,1:Bk,2:zk,3:Qk,4:Zk};Sh.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=Dk[s[h]](e,u,o,i);if(g<d)l=s[h],d=g}}c[a]=l,a++,Xk[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var sc=Te((eO,Nh)=>{var ut=ti(),ey=ec(),ty=vh(),ny=Ih(),ry=st("zlib"),Cn=Nh.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||ry.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")};Cn.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Cn.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Cn.prototype.filterData=function(e,t,n){let r=ty(e,t,n,this._options),i=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ny(r,t,n,this._options,i)};Cn.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(ey.crc32(r.slice(4,r.length-4)),r.length-4),r};Cn.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)};Cn.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)};Cn.prototype.packIDAT=function(e){return this._packChunk(ut.TYPE_IDAT,e)};Cn.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var Fh=Te((tO,Rh)=>{var iy=st("util"),Ph=st("stream"),sy=ti(),oy=sc(),Oh=Rh.exports=function(e){Ph.call(this);let t=e||{};this._packer=new oy(t),this._deflate=this._packer.createDeflate(),this.readable=!0};iy.inherits(Oh,Ph);Oh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(sy.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 Ch=Te((ts,Lh)=>{var Hh=st("assert").ok,ni=st("zlib"),ay=st("util"),Th=st("buffer").kMaxLength;function $r(e){if(!(this instanceof $r))return new $r(e);if(e&&e.chunkSize<ni.Z_MIN_CHUNK)e.chunkSize=ni.Z_MIN_CHUNK;if(ni.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 uy(e){return new $r(e)}function Ah(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}$r.prototype._processChunk=function(e,t,n){if(typeof n==="function")return ni.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,p){if(r._hadError)return;let b=s-p;if(Hh(b>=0,"have should not go down"),b>0){let m=r._buffer.slice(r._offset,r._offset+b);if(r._offset+=b,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(p===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(p===0)return a+=i-g,i=g,!0;return!1}Hh(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>=Th)throw Ah(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Th.toString(16)+" bytes");let h=Buffer.concat(u,c);return Ah(this),h};ay.inherits($r,ni.Inflate);function cy(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=ni.Z_FINISH;return e._processChunk(t,n)}function xh(e,t){return cy(new $r(t),e)}Lh.exports=ts=xh;ts.Inflate=$r;ts.createInflate=uy;ts.inflateSync=xh});var oc=Te((nO,Gh)=>{var _h=Gh.exports=function(e){this._buffer=e,this._reads=[]};_h.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};_h.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 Wh=Te((dy)=>{var ly=oc(),fy=Zu();dy.process=function(e,t){let n=[],r=new ly(e);return new fy(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Jh=Te((iO,Kh)=>{var Uh=!0,jh=st("zlib"),gy=Ch();if(!jh.deflateSync)Uh=!1;var my=oc(),py=Wh(),by=tc(),wy=nc(),$y=rc();Kh.exports=function(e,t){if(!Uh)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(S){n=S}let i;function s(S){i=S}function o(S){i.transColor=S}function a(S){i.palette=S}function u(){i.alpha=!0}let c;function l(S){c=S}let f=[];function d(S){f.push(S)}let h=new my(e);if(new by(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 p=Buffer.concat(f);f.length=0;let b;if(i.interlace)b=jh.inflateSync(p);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;b=gy(p,{chunkSize:w,maxLength:w})}if(p=null,!b||!b.length)throw Error("bad png - invalid inflate data response");let m=py.process(b,i);p=null;let $=wy.dataToBitMap(m,i);m=null;let k=$y($,i,t.skipRescale);return i.data=k,i.gamma=c||0,i}});var Yh=Te((sO,zh)=>{var Bh=!0,qh=st("zlib");if(!qh.deflateSync)Bh=!1;var ky=ti(),yy=sc();zh.exports=function(e,t){if(!Bh)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new yy(t||{}),i=[];if(i.push(Buffer.from(ky.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=qh.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 Qh=Te((My)=>{var Ey=Jh(),vy=Yh();My.read=function(e,t){return Ey(e,t||{})};My.write=function(e,t){return vy(e,t)}});var Zh=Te((Fy)=>{var Ny=st("util"),Vh=st("stream"),Py=yh(),Oy=Fh(),Ry=Qh(),lt=Fy.PNG=function(e){if(Vh.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 Py(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 Oy(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"))};Ny.inherits(lt,Vh);lt.sync=Ry;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 qN}from"node:child_process";import{isMainThread as zN}from"node:worker_threads";import{parseArgs as WN}from"node:util";var ot={name:"@kecan0406/ttheme",version:"1.2.1",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal, 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","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 oN,readFileSync as N0}from"node:fs";import{styleText as No}from"node:util";import{stdout as Sd,stdin as y$}from"node:process";import E$ from"node:readline";var ud=(()=>{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}})(),cd=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},ld=(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 o$=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,a$=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fd=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,u$=/\t{1,1000}/y,dd=/[\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,c$=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,l$=/\p{M}+/gu,f$={limit:1/0,ellipsis:""},hd=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?hd(i,f$,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=[[c$,f],[o$,0],[a$,a],[u$,u],[dd,c],[fd,d]],g=0,p=0,b=e.length,m=0,$=!1,k=b,S=Math.max(0,r-s),w=0,M=0,y=0,N=0;e:while(!0){if(M>w||p>=b&&p>g){let O=e.slice(w,M)||e.slice(g,p);m=0;for(let T of O.replaceAll(l$,"")){let A=T.codePointAt(0)||0;if(cd(A))N=2;else if(ld(A))N=d;else N=f;if(y+N>S)k=Math.min(k,Math.max(w,g)+m);if(y+N>r){$=!0;break e}m+=T.length,y+=N}w=M=0}if(p>=b)break e;for(let O=0,T=h.length;O<T;O++){let[A,C]=h[O];if(A.lastIndex=p,A.test(e)){if(m=A===fd?ud(e.slice(p,A.lastIndex)):A===dd?1:A.lastIndex-p,N=m*C,y+N>S)k=Math.min(k,p+Math.floor((S-y)/C));if(y+N>r){$=!0;break e}y+=N,w=g,M=p,p=g=A.lastIndex;continue e}}p+=1}return{width:$?S:y,index:$?k:b,truncated:$,ellipsed:$&&r>=s}},gd=hd;var d$={limit:1/0,ellipsis:"",ellipsisWidth:0},h$=(e,t={})=>{return gd(e,d$,t).width},$e=h$;var vo="\x1B",$d="›",g$=39,Mu="\x07",kd="[",m$="]",yd="m",Su=`${m$}8;;`,md=new RegExp(`(?:\\${kd}(?<code>\\d+)m|\\${Su}(?<uri>.*)${Mu})`,"y"),pd=(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},bd=(e)=>`${vo}${kd}${e}${yd}`,wd=(e)=>`${vo}${Su}${e}${Mu}`,vu=(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===vo||f===$d)i=!0,s=t.startsWith(Su,l+1);if(i){if(s){if(f===Mu)i=!1,s=!1}else if(f===yd)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()},p$=(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("")},b$=(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)??"",p=g.trimStart();if(g.length!==p.length)a[a.length-1]=p,u=$e(p)}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,p=1+Math.floor((h-g-1)/t);if(Math.floor((h-1)/t)<p)a.push("");vu(a,d,t),u=$e(a.at(-1)??"");continue}if(u+h>t&&u&&h){if(n.wordWrap===!1&&u<t){vu(a,d,t),u=$e(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>t&&n.wordWrap===!1){vu(a,d,t),u=$e(a.at(-1)??"");continue}a[a.length-1]+=d,u+=h}if(n.trim!==!1)a=a.map((f)=>p$(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===vo||d===$d){md.lastIndex=f+1;let g=md.exec(c)?.groups;if(g?.code!==void 0){let p=Number.parseFloat(g.code);i=p===g$?void 0:p}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[f+1]===`
4
+ `){if(s)r+=wd("");let h=i?pd(i):void 0;if(i&&h)r+=bd(h)}else if(d===`
5
+ `){if(i&&pd(i))r+=bd(i);if(s)r+=wd(s)}}return r},w$=/\r?\n/;function Nn(e,t,n){return String(e).normalize().split(w$).map((r)=>b$(r,t,n)).join(`
6
+ `)}var mt=Eo(Nu(),1);function zr(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?zr(s,t<0?-1:1,n):s}function Mo(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 v$=["up","down","left","right","space","enter","cancel"],M$=["January","February","March","April","May","June","July","August","September","October","November","December"],at={actions:new Set(v$),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:[...M$],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 Id(e,t){if(typeof e=="string")return at.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Id(n,t))return!0;return!1}function S$(e,t){if(e===t)return;let n=e.split(`
8
8
  `),r=t.split(`
9
- `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var BN=globalThis.process.platform.startsWith("win"),Eu=Symbol("clack:cancel");function ht(e){return e===Eu}function ko(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var vo=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Su=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function zi(e,t,n,r=n,i=n,s){let o=vo(e??hd);return Nn(t,o-n.length,{hard:!0,trim:!1}).split(`
9
+ `),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var cP=globalThis.process.platform.startsWith("win"),Ou=Symbol("clack:cancel");function ht(e){return e===Ou}function So(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Po=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Fu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Qi(e,t,n,r=n,i=n,s){let o=Po(e??Sd);return Nn(t,o-n.length,{hard:!0,trim:!1}).split(`
10
10
  `).map((a,u,c)=>{let l=s?s(a,u):a;return u===0?`${r}${l}`:u===c.length-1?`${i}${l}`:`${n}${l}`}).join(`
11
- `)}function md(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 Nt{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=e$,output:r=hd,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(Eu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=t$.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),ko(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(mt.cursor.show),this.output.off("resize",this.render),ko(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(mt.cursor.show),this.output.off("resize",this.render),ko(this.input,!1),e(Eu)})})}_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=md(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")}gd([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
- `),ko(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Nn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(mt.cursor.move(-999,e*-1))}render(){let e=Nn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(mt.cursor.hide);else{let t=i$(this._prevFrame,e),n=Su(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(mt.cursor.move(0,s-i)),this.output.write(mt.erase.lines(1));let o=e.split(`
11
+ `)}function Nd(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class Pt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=y$,output:r=Sd,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(Ou);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=E$.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),So(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(mt.cursor.show),this.output.off("resize",this.render),So(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(mt.cursor.show),this.output.off("resize",this.render),So(this.input,!1),e(Ou)})})}_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=Nd(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")}Id([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
+ `),So(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Nn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(mt.cursor.move(-999,e*-1))}render(){let e=Nn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(mt.cursor.hide);else{let t=S$(this._prevFrame,e),n=Fu(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(mt.cursor.move(0,s-i)),this.output.write(mt.erase.lines(1));let o=e.split(`
14
14
  `);this.output.write(o[s]),this._prevFrame=e,this.output.write(mt.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(mt.cursor.move(0,a))}this.output.write(mt.erase.down());let o=e.split(`
15
15
  `).slice(s);this.output.write(o.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(mt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function s$(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 o$(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function a$(e,t){if(t)return e?t:t[0]}var u$=class extends Nt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Eo(["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}${Eo("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??o$;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=jr(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=a$(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=s$(this.focusedValue,this.filteredOptions);this.#t=jr(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 Mu extends Nt{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(mt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var c$={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function fd(e){return[...e].map((t)=>c$[t])}function l$(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 yu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function yo(e){return{year:yu(e.year),month:yu(e.month),day:yu(e.day)}}function vu(e,t){return new Date(e||2001,t||1,0).getDate()}function pd(e){let{year:t,month:n,day:r}=yo(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 dd(e){let t=pd(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function f$(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:vu(t.year,t.month)}}class bd extends Nt{#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(dd(this.#e)??void 0)}constructor(e){let t=e.format?{segments:fd(e.format),separator:e.separator??"/"}:l$(e.locale),n=e.separator??t.separator,r=e.format?fd(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=f$(n.type,yo(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:pd(this.#e);if(l){let{year:d,month:h}=l,g=vu(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}=yo(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}=yo(this.#e);if(t&&n&&r){let i=vu(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=dd(this.#e)??e.defaultValue??void 0}}var d$=class extends Nt{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}})}},h$=new Set(["up","down","left","right"]);class wd extends Nt{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
16
+ `)),this._prevFrame=e;return}}this.output.write(mt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function I$(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 N$(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function P$(e,t){if(t)return e?t:t[0]}var O$=class extends Pt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return No(["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}${No("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??N$;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=zr(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=P$(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=I$(this.focusedValue,this.filteredOptions);this.#t=zr(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 Hu extends Pt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(mt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var R$={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function vd(e){return[...e].map((t)=>R$[t])}function F$(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 Pu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Io(e){return{year:Pu(e.year),month:Pu(e.month),day:Pu(e.day)}}function Ru(e,t){return new Date(e||2001,t||1,0).getDate()}function Pd(e){let{year:t,month:n,day:r}=Io(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 Md(e){let t=Pd(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function H$(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:Ru(t.year,t.month)}}class Od extends Pt{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#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(Md(this.#e)??void 0)}constructor(e){let t=e.format?{segments:vd(e.format),separator:e.separator??"/"}:F$(e.locale),n=e.separator??t.separator,r=e.format?vd(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=H$(n.type,Io(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:Pd(this.#e);if(l){let{year:d,month:h}=l,g=Ru(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}=Io(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}=Io(this.#e);if(t&&n&&r){let i=Ru(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Md(this.#e)??e.defaultValue??void 0}}var T$=class extends Pt{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},A$=new Set(["up","down","left","right"]);class Rd extends Pt{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
17
17
  `?`${t}█
18
- ${r}`:`${t}${Eo("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=$o(this._cursor,0,-1,t);return;case"down":this._cursor=$o(this._cursor,0,1,t);return;case"left":this._cursor=$o(this._cursor,-1,0,t);return;case"right":this._cursor=$o(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
18
+ ${r}`:`${t}${No("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=Mo(this._cursor,0,-1,t);return;case"down":this._cursor=Mo(this._cursor,0,1,t);return;case"left":this._cursor=Mo(this._cursor,-1,0,t);return;case"right":this._cursor=Mo(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
19
19
  `),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
20
20
  `&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
21
- `),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#n=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&h$.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 Iu extends Nt{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?jr(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=jr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=jr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Nu extends Nt{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}${Eo("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 I,stripVTControlCharacters as eP}from"node:util";import Pt from"node:process";var Id=bo(ku(),1);function g$(){if(Pt.platform!=="win32")return Pt.env.TERM!=="linux";return Boolean(Pt.env.CI)||Boolean(Pt.env.WT_SESSION)||Boolean(Pt.env.TERMINUS_SUBLIME)||Pt.env.ConEmuTask==="{cmd::Cmder}"||Pt.env.TERM_PROGRAM==="Terminus-Sublime"||Pt.env.TERM_PROGRAM==="vscode"||Pt.env.TERM==="xterm-256color"||Pt.env.TERM==="alacritty"||Pt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var m$=g$();var Ne=(e,t)=>m$?e:t,p$=Ne("◆","*"),b$=Ne("■","x"),w$=Ne("▲","x"),Pu=Ne("◇","o"),$$=Ne("┌","T"),ke=Ne("│","|"),On=Ne("└","—"),iP=Ne("┐","T"),sP=Ne("┘","—"),$d=Ne("●",">"),kd=Ne("○"," "),k$=Ne("◻","[•]"),yd=Ne("◼","[+]"),Ed=Ne("◻","[ ]"),oP=Ne("▪","•"),vd=Ne("─","-"),y$=Ne("╮","+"),E$=Ne("├","+"),v$=Ne("╯","+"),S$=Ne("╰","+"),aP=Ne("╭","+"),M$=Ne("●","•"),I$=Ne("◆","*"),N$=Ne("▲","!"),P$=Ne("■","x"),Ou=(e)=>{switch(e){case"initial":case"active":return I("cyan",p$);case"cancel":return I("red",b$);case"error":return I("yellow",w$);case"submit":return I("green",Pu)}},O$=(e)=>{switch(e){case"initial":case"active":return I("cyan",ke);case"cancel":return I("red",ke);case"error":return I("yellow",ke);case"submit":return I("green",ke)}};function F$(e,t){let n=[`${t?`${I("cyan",ke)} `:""}${e.join(" • ")}`];return t&&n.push(I("cyan",On)),n}var Sd=(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}},Md=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=vo(r)-s,u=Su(r),c=I("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,p=Math.min(d+f,t.length),b=[],m=0;h&&m++,g&&m++;let $=d+(h?1:0),k=p-(g?1:0);for(let w=$;w<k;w++){let S=t[w],y=S?n(S,w===e):"",N=Nn(y,a,{hard:!0,trim:!1}).split(`
22
- `);b.push(N),m+=N.length}if(m>l){let w=0,S=0,y=m,N=e-$,O=l,T=()=>Sd(b,y,0,N,O),A=()=>Sd(b,y,N+1,b.length,O,!0);h?({lineCount:y,removals:w}=T(),y>O&&(g||(O-=1),{lineCount:y,removals:S}=A())):(g||(O-=1),{lineCount:y,removals:S}=A(),y>O&&(O-=1,{lineCount:y,removals:w}=T())),w>0&&(h=!0,b.splice(0,w)),S>0&&(g=!0,b.splice(b.length-S,S))}let M=[];h&&M.push(c);for(let w of b)for(let S of w)M.push(S);return g&&M.push(c),M};var Fn=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Mu({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=`${Ou(this.state)} `,s=r?`${I("gray",ke)} `:"",o=zi(e.output,e.message,s,i),a=`${r?`${I("gray",ke)}
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&&A$.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 Tu extends Pt{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?zr(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=zr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=zr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Au extends Pt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${No("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 I,stripVTControlCharacters as wP}from"node:util";import Ot from"node:process";var _d=Eo(Nu(),1);function x$(){if(Ot.platform!=="win32")return Ot.env.TERM!=="linux";return Boolean(Ot.env.CI)||Boolean(Ot.env.WT_SESSION)||Boolean(Ot.env.TERMINUS_SUBLIME)||Ot.env.ConEmuTask==="{cmd::Cmder}"||Ot.env.TERM_PROGRAM==="Terminus-Sublime"||Ot.env.TERM_PROGRAM==="vscode"||Ot.env.TERM==="xterm-256color"||Ot.env.TERM==="alacritty"||Ot.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var L$=x$();var Pe=(e,t)=>L$?e:t,C$=Pe("◆","*"),_$=Pe("■","x"),G$=Pe("▲","x"),xu=Pe("◇","o"),W$=Pe("┌","T"),ke=Pe("│","|"),On=Pe("└","—"),EP=Pe("┐","T"),vP=Pe("┘","—"),Fd=Pe("●",">"),Hd=Pe("○"," "),U$=Pe("◻","[•]"),Td=Pe("◼","[+]"),Ad=Pe("◻","[ ]"),MP=Pe("▪","•"),xd=Pe("─","-"),j$=Pe("╮","+"),K$=Pe("├","+"),J$=Pe("╯","+"),B$=Pe("╰","+"),SP=Pe("╭","+"),q$=Pe("●","•"),z$=Pe("◆","*"),Y$=Pe("▲","!"),Q$=Pe("■","x"),Lu=(e)=>{switch(e){case"initial":case"active":return I("cyan",C$);case"cancel":return I("red",_$);case"error":return I("yellow",G$);case"submit":return I("green",xu)}},V$=(e)=>{switch(e){case"initial":case"active":return I("cyan",ke);case"cancel":return I("red",ke);case"error":return I("yellow",ke);case"submit":return I("green",ke)}};function Z$(e,t){let n=[`${t?`${I("cyan",ke)} `:""}${e.join(" • ")}`];return t&&n.push(I("cyan",On)),n}var Ld=(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}},Cd=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Po(r)-s,u=Fu(r),c=I("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,p=Math.min(d+f,t.length),b=[],m=0;h&&m++,g&&m++;let $=d+(h?1:0),k=p-(g?1:0);for(let w=$;w<k;w++){let M=t[w],y=M?n(M,w===e):"",N=Nn(y,a,{hard:!0,trim:!1}).split(`
22
+ `);b.push(N),m+=N.length}if(m>l){let w=0,M=0,y=m,N=e-$,O=l,T=()=>Ld(b,y,0,N,O),A=()=>Ld(b,y,N+1,b.length,O,!0);h?({lineCount:y,removals:w}=T(),y>O&&(g||(O-=1),{lineCount:y,removals:M}=A())):(g||(O-=1),{lineCount:y,removals:M}=A(),y>O&&(O-=1,{lineCount:y,removals:w}=T())),w>0&&(h=!0,b.splice(0,w)),M>0&&(g=!0,b.splice(b.length-M,M))}let S=[];h&&S.push(c);for(let w of b)for(let M of w)S.push(M);return g&&S.push(c),S};var Rn=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Hu({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=`${Lu(this.state)} `,s=r?`${I("gray",ke)} `:"",o=Qi(e.output,e.message,s,i),a=`${r?`${I("gray",ke)}
23
23
  `:""}${o}
24
24
  `,u=this.value?t:n;switch(this.state){case"submit":{let c=r?`${I("gray",ke)} `:"";return`${a}${c}${I("dim",u)}`}case"cancel":{let c=r?`${I("gray",ke)} `:"";return`${a}${c}${I(["strikethrough","dim"],u)}${r?`
25
- ${I("gray",ke)}`:""}`}default:{let c=r?`${I("cyan",ke)} `:"",l=r?I("cyan",On):"";return`${a}${c}${this.value?`${I("green",$d)} ${t}`:`${I("dim",kd)} ${I("dim",t)}`}${e.vertical?r?`
25
+ ${I("gray",ke)}`:""}`}default:{let c=r?`${I("cyan",ke)} `:"",l=r?I("cyan",On):"";return`${a}${c}${this.value?`${I("green",Fd)} ${t}`:`${I("dim",Hd)} ${I("dim",t)}`}${e.vertical?r?`
26
26
  ${I("cyan",ke)} `:`
27
- `:` ${I("dim","/")} `}${this.value?`${I("dim",kd)} ${I("dim",n)}`:`${I("green",$d)} ${n}`}
27
+ `:` ${I("dim","/")} `}${this.value?`${I("dim",Hd)} ${I("dim",n)}`:`${I("green",Fd)} ${n}`}
28
28
  ${l}
29
- `}}}}).prompt()};var R$=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Space:")} select`,`${I("dim","Enter:")} confirm`],Yi=(e,t)=>e.split(`
29
+ `}}}}).prompt()};var X$=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Space:")} select`,`${I("dim","Enter:")} confirm`],Vi=(e,t)=>e.split(`
30
30
  `).map((n)=>t(n)).join(`
31
- `),Nd=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${I("gray",Ed)} ${Yi(o,(a)=>I(["strikethrough","gray"],a))}${i.hint?` ${I("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${I("cyan",k$)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${I("green",yd)} ${Yi(o,(a)=>I("dim",a))}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Yi(o,(a)=>I(["strikethrough","dim"],a))}`:s==="active-selected"?`${I("green",yd)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Yi(o,(a)=>I("dim",a))}`:`${I("dim",Ed)} ${Yi(o,(a)=>I("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Iu({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
- ${I("reset",I("dim",`Press ${I(["gray","bgWhite","inverse"]," space ")} to select, ${I("gray",I("bgWhite",I("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??at.withGuide,s=zi(e.output,e.message,i?`${O$(this.state)} `:"",`${Ou(this.state)} `),o=`${i?`${I("gray",ke)}
31
+ `),Gd=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${I("gray",Ad)} ${Vi(o,(a)=>I(["strikethrough","gray"],a))}${i.hint?` ${I("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${I("cyan",U$)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${I("green",Td)} ${Vi(o,(a)=>I("dim",a))}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Vi(o,(a)=>I(["strikethrough","dim"],a))}`:s==="active-selected"?`${I("green",Td)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Vi(o,(a)=>I("dim",a))}`:`${I("dim",Ad)} ${Vi(o,(a)=>I("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Tu({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
+ ${I("reset",I("dim",`Press ${I(["gray","bgWhite","inverse"]," space ")} to select, ${I("gray",I("bgWhite",I("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??at.withGuide,s=Qi(e.output,e.message,i?`${V$(this.state)} `:"",`${Lu(this.state)} `),o=`${i?`${I("gray",ke)}
33
33
  `:""}${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(I("dim",", "))||I("dim","none"),l=zi(e.output,c,i?`${I("gray",ke)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"cancelled")).join(I("dim",", "));if(c.trim()==="")return`${o}${I("gray",ke)}`;let l=zi(e.output,c,i?`${I("gray",ke)} `:"");return`${o}${l}${i?`
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(I("dim",", "))||I("dim","none"),l=Qi(e.output,c,i?`${I("gray",ke)} `:"");return`${o}${l}`}case"cancel":{let c=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"cancelled")).join(I("dim",", "));if(c.trim()==="")return`${o}${I("gray",ke)}`;let l=Qi(e.output,c,i?`${I("gray",ke)} `:"");return`${o}${l}${i?`
35
35
  ${I("gray",ke)}`:""}`}case"error":{let c=i?`${I("yellow",ke)} `:"",l=this.error.split(`
36
36
  `).map((h,g)=>g===0?`${i?`${I("yellow",On)} `:""}${I("yellow",h)}`:` ${h}`).join(`
37
37
  `),f=o.split(`
38
38
  `).length,d=l.split(`
39
- `).length+1;return`${o}${c}${Md({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:f+d,style:u}).join(`
39
+ `).length+1;return`${o}${c}${Cd({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:f+d,style:u}).join(`
40
40
  ${c}`)}
41
41
  ${l}
42
42
  `}default:{let c=i?`${I("cyan",ke)} `:"",l=o.split(`
43
- `).length,f=r?F$(R$,i):i?[I("cyan",On)]:[],d=f.join(`
44
- `),h=f.length+1;return`${o}${c}${Md({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+h,style:u}).join(`
43
+ `).length,f=r?Z$(X$,i):i?[I("cyan",On)]:[],d=f.join(`
44
+ `),h=f.length+1;return`${o}${c}${Cd({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+h,style:u}).join(`
45
45
  ${c}`)}
46
46
  ${d}
47
47
  `}}}}).prompt()};var Pn={message:(e=[],{symbol:t=I("gray",ke),secondarySymbol:n=I("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
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(`
49
49
  `)}
50
- `)},info:(e,t)=>{Pn.message(e,{...t,symbol:I("blue",M$)})},success:(e,t)=>{Pn.message(e,{...t,symbol:I("green",I$)})},step:(e,t)=>{Pn.message(e,{...t,symbol:I("green",Pu)})},warn:(e,t)=>{Pn.message(e,{...t,symbol:I("yellow",N$)})},warning:(e,t)=>{Pn.warn(e,t)},error:(e,t)=>{Pn.message(e,{...t,symbol:I("red",P$)})}},Kr=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",On)} `:"";n.write(`${r}${I("red",e)}
50
+ `)},info:(e,t)=>{Pn.message(e,{...t,symbol:I("blue",q$)})},success:(e,t)=>{Pn.message(e,{...t,symbol:I("green",z$)})},step:(e,t)=>{Pn.message(e,{...t,symbol:I("green",xu)})},warn:(e,t)=>{Pn.message(e,{...t,symbol:I("yellow",Y$)})},warning:(e,t)=>{Pn.warn(e,t)},error:(e,t)=>{Pn.message(e,{...t,symbol:I("red",Q$)})}},Yr=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",On)} `:"";n.write(`${r}${I("red",e)}
51
51
 
52
- `)},So=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",$$)} `:"";n.write(`${r}${e}
53
- `)},Fu=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",ke)}
52
+ `)},Oo=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",W$)} `:"";n.write(`${r}${e}
53
+ `)},Cu=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",ke)}
54
54
  ${I("gray",On)} `:"";n.write(`${r}${e}
55
55
 
56
- `)};var H$=(e)=>e,T$=(e,t,n)=>{let r={hard:!0,trim:!1},i=Nn(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 Nn(e,a,r)},hr=(e="",t="",n)=>{let r=n?.output??Pt.stdout,i=n?.withGuide??at.withGuide,s=n?.format??H$,o=["",...T$(e,vo(r)-6,s).split(`
56
+ `)};var D$=(e)=>e,ek=(e,t,n)=>{let r={hard:!0,trim:!1},i=Nn(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 Nn(e,a,r)},mr=(e="",t="",n)=>{let r=n?.output??Ot.stdout,i=n?.withGuide??at.withGuide,s=n?.format??D$,o=["",...ek(e,Po(r)-6,s).split(`
58
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)=>`${I("gray",ke)} ${d}${" ".repeat(u-$e(d))}${I("gray",ke)}`).join(`
59
59
  `),l=i?`${I("gray",ke)}
60
- `:"",f=i?E$:S$;r.write(`${l}${I("green",Pu)} ${I("reset",t)} ${I("gray",vd.repeat(Math.max(u-a-1,1))+y$)}
60
+ `:"",f=i?K$:B$;r.write(`${l}${I("green",xu)} ${I("reset",t)} ${I("gray",xd.repeat(Math.max(u-a-1,1))+j$)}
61
61
  ${c}
62
- ${I("gray",f+vd.repeat(u+2)+v$)}
63
- `)};var uP={light:Ne("─","-"),heavy:Ne("━","="),block:Ne("█","#")};var cP=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Enter:")} confirm`];var lP=`${I("gray",ke)} `;var Ru=(e)=>new Nu({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?`${I("gray",ke)}
64
- `:""}${Ou(this.state)} `}${e.message}
62
+ ${I("gray",f+xd.repeat(u+2)+J$)}
63
+ `)};var IP={light:Pe("─","-"),heavy:Pe("━","="),block:Pe("█","#")};var NP=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Enter:")} confirm`];var PP=`${I("gray",ke)} `;var _u=(e)=>new Au({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?`${I("gray",ke)}
64
+ `:""}${Lu(this.state)} `}${e.message}
65
65
  `,r=e.placeholder&&e.placeholder.length>0?I("inverse",e.placeholder[0])+I("dim",e.placeholder.slice(1)):I(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${I("yellow",this.error)}`:"",a=t?`${I("yellow",ke)} `:"",u=t?I("yellow",On):"";return`${n.trim()}
66
66
  ${a}${i}
67
67
  ${u}${o}
68
68
  `}case"submit":{let o=s?` ${I("dim",s)}`:"",a=t?I("gray",ke):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${I(["strikethrough","dim"],s)}`:"",a=t?I("gray",ke):"";return`${n}${a}${o}${s.trim()?`
69
69
  ${a}`:""}`}default:{let o=t?`${I("cyan",ke)} `:"",a=t?I("cyan",On):"";return`${n}${o}${i}
70
70
  ${a}
71
- `}}}}).prompt();function Hu(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 zt(e){return`\x1B[38;2;${Hu(e)}m`}function Mo(e,t){return`\x1B[48;2;${Hu(e)};38;2;${Hu(t)}m`}function Pd(e,t="\x1B[39m"){return`${e.map((n)=>`${zt(n)}■`).join(" ")}${t}`}var Vi="⧉";function Io(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function A$(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 Od(e,t){let n="",r=0,i=0;while(i<e.length){let s=A$(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 nt(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}=Od(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function fn(e,t,n){let r=n-$e(t)-1;return r<=0?nt(e,n):`${nt(e,r)} ${t}`}function Ve(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}=Od(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 ym,readFileSync as Cc}from"node:fs";import{join as Em}from"node:path";var L$=/^#[0-9a-f]{6}$/;function Yt(e){return L$.test(e)}function Pe(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function rt(e,t,n){let r=Pe(e),i=Pe(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function Ye(e){let[t,n,r]=Pe(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 Ke(e,t){let n=Ye(e),r=Ye(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function No(e,t){return Math.round(Ke(e,t)*100)/100}function x$(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]=Pe(e).map(x$),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 Rn=7,Fd=3,Tu=0.15,Rd=1.6,Lu=[1,2,3,4,5,6,9,10,11,12,13,14],Hd=[7,15],Hn=[1,2,3,4,5,6],hn={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}},Xi=0.03,Gt=25,Br=15,qr=0.08;function dn(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function Au(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=dn(e,i);return Ke(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${No(s,r)}:1, needs ${n}:1`]:[]})}function Td(e,t){return Math.min(...t.map((n)=>Ke(dn(e,n),e.background)))}var Ad=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Rn,measure:({foreground:e,background:t})=>Ke(e,t),check:({foreground:e,background:t})=>Ke(e,t)<Rn?[`foreground ${e} on ${t} is ${No(e,t)}:1, needs ${Rn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:Fd,measure:(e)=>Td(e,Lu),check:(e)=>Au(e,Lu,Fd)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Tu,measure:(e)=>Ye(dn(e,0)),check:(e)=>{let t=dn(e,0);return Ye(t)>Tu?[`ANSI 0 ${t} has luminance ${Ye(t).toFixed(3)}, needs <= ${Tu}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Rn,measure:(e)=>Td(e,Hd),check:(e)=>Au(e,Hd,Rn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Rd,measure:(e)=>Ke(dn(e,8),e.background),check:(e)=>Au(e,[8],Rd)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Rn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Ke(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Ke(e,t)<Rn?[`foreground ${e} on selection ${t} is ${No(e,t)}:1, needs ${Rn}:1`]:[]}];function Qt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var Tn=(e)=>e>8?e-8:e;function zr(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Hn.includes(Tn(n))?[n,n>8?n-8:n+8]:[n]))}function Zi(e,t){let n=Je(dn(e,t));return n.c<Xi?void 0:n}function Jr(e){let t=zr(e);return Lu.flatMap((n)=>{let r=Zi(e,n),i=hn[Tn(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Qt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function gr(e){let t=new Set(e.signatureSlots);return Hn.flatMap((n)=>{let r=Zi(e,n),i=Zi(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Qt(r.h,i.h)}]})}function mr(e){let t=zr(e);return[0,8].flatMap((n)=>Hn.flatMap((r)=>Hn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=Zi(e,s),u=Zi(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Qt(a.h,u.h)<Br&&Math.abs(a.l-u.l)<qr?[[s,o]]:[]})))}var C$=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Jr(e).map((t)=>t.over)),check:(e)=>Jr(e).map(({slot:t,hue:n,over:r})=>{let i=hn[Tn(t)];return`ANSI ${t} ${dn(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:Gt,measure:(e)=>Math.max(0,...gr(e).map((t)=>t.gap)),check:(e)=>gr(e).filter((t)=>t.gap>Gt).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${Gt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>mr(e).length,check:(e)=>mr(e).map(([t,n])=>`ANSI ${t} ${dn(e,t)} and ANSI ${n} ${dn(e,n)} are within ${Br}° hue and ${qr} lightness`)}],Po=[...Ad,...C$],xu=Po.map((e)=>e.rule),pt=Po.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 An(e){return Po.map((t)=>Math.round(t.measure(e)*1000)/1000)}function Ld(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 pr(e){return Ld(Po,e)}function xd(e){return Ld(Ad,e)}function Cd(e){return e.flatMap(pr)}import{chmodSync as G$,copyFileSync as _$,existsSync as Yr,mkdirSync as W$,readFileSync as Cu,realpathSync as U$,renameSync as j$,rmSync as Gd,statSync as K$,writeFileSync as J$}from"node:fs";import{dirname as B$}from"node:path";function _d(e){return`${e}.ttheme.bak`}var q$=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function Gu(e){let t=_d(e);if(Yr(e)&&!Yr(t)&&!q$.test(Cu(e,"utf8")))_$(e,t)}function Z(e,t){let n=Yr(e)?U$(e):e;W$(B$(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(J$(r,t),Yr(n))G$(r,K$(n).mode&4095);j$(r,n)}function Ln(e,t){if((Yr(e)?Cu(e,"utf8"):void 0)===t)return!1;return Gu(e),Z(e,t),!0}function Wd(e,t){let n=_d(e),r=Yr(n)?Cu(n,"utf8"):void 0;if(t===""&&r===void 0)return Gd(e,{force:!0}),"removed";if(Z(e,t),r===void 0||r===t)return Gd(n,{force:!0}),"restored";return"kept backup"}import{createHash as Kg}from"node:crypto";import{copyFileSync as M1,existsSync as yc,mkdirSync as I1,readdirSync as N1,readFileSync as Zo,renameSync as Jg,rmSync as oi}from"node:fs";import{basename as Bg,isAbsolute as P1,join as D}from"node:path";var Uh=bo(zd(),1),Fo=bo(_h(),1);import{deflateSync as fy}from"node:zlib";var ts=[137,80,78,71,13,10,26,10],jh=13,Kh=3;function Xr(e){return e.length>=ts.length&&ts.every((t,n)=>e[n]===t)}function wr(e){let t=Fo.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Gn(e,t){if(Xr(e)){let n=_n(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return wr(e)}if(e[0]===255&&e[1]===216){let n=Uh.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 Ro(e){let t=new Fo.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Fo.PNG.sync.write(t)}function Wh(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function _n(e){if(e.length<33||!Xr(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=Wh(e,"IDAT");return{width:n,height:r,alpha:Wh(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function Jh(e,t=jh){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 gn(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)<jh)n++;return Math.round(n*100/(t.w*t.h))}function Bh(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=hy(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 dy(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 ec(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 p=d;p<=Math.ceil(f+o-0.5);p++){let b=dy((p+0.5-f)/s),m=l*a+Math.min(e-1,Math.max(0,p))-h;c[m]=(c[m]??0)+b,g+=b}for(let p=l*a;p<(l+1)*a;p++)c[p]=(c[p]??0)/g}return{first:u,size:a,weights:c}}function qh(e,t,n,r,i,s){let o=ec(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 p=c.get(f+h);if(!p)p=new Float32Array(a),s(f+h,p),c.set(f+h,p);for(let b=0;b<a;b++)u[d+b]=(u[d+b]??0)+(p[b]??0)*g}}return u}function hy(e,t,n,r){let i=ec(e.width,t.x,t.w,n),s=e.data,o=qh(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,p=0,b=0,m=0;for(let $=0;$<i.size;$++){let k=(d+$)*4,M=(i.weights[h+$]??0)*(s[k+3]??0);g+=(s[k]??0)*M,p+=(s[k+1]??0)*M,b+=(s[k+2]??0)*M,m+=M}c[f*4]=g,c[f*4+1]=p,c[f*4+2]=b,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 zh(e,t,n,r){let i=ec(e.width,t.x,t.w,n),s=e.data,o=qh(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 Ho(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 p=0;p<s;p++)c[f+p]=(c[f+p]??0)+(u[g+p]??0)*h}}return{width:s,height:o,data:c}}function ns(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 rs(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 gy=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 my(e){let t=4294967295;for(let n of e)t=(gy[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function es(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(my(n.subarray(4,8+t.length)),8+t.length),n}function py(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),p=Math.abs(l+f-2*d);i[o+1+c]=(e[a+c]??0)-(h<=g&&h<=p?l:g<=p?f:d)&255}}return i}function Yh(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(ts),es("IHDR",r),...n,es("IDAT",fy(py(e.data,e.width,e.height))),es("IEND",new Uint8Array)])}function Qh(e){let[t,n,r]=Pe(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return es("PLTE",i)}function is(e,t){return Yh(e,Kh,[Qh(t),es("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function tc(e){return Yh(e,0,[])}function Vh(e,t){if(!Xr(e)||e[25]!==Kh)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(ts)],i=ts.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?Qh(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as h1,readFileSync as Rg}from"node:fs";import{basename as g1,join as Hg}from"node:path";/*!
71
+ `}}}}).prompt();function Gu(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 zt(e){return`\x1B[38;2;${Gu(e)}m`}function Ro(e,t){return`\x1B[48;2;${Gu(e)};38;2;${Gu(t)}m`}function Wd(e,t="\x1B[39m"){return`${e.map((n)=>`${zt(n)}■`).join(" ")}${t}`}var Xi="⧉";function Fo(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function tk(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 Ud(e,t){let n="",r=0,i=0;while(i<e.length){let s=tk(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 nt(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}=Ud(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function dn(e,t,n){let r=n-$e(t)-1;return r<=0?nt(e,n):`${nt(e,r)} ${t}`}function Ve(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}=Ud(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 Gm,readFileSync as Qc}from"node:fs";import{join as Wm}from"node:path";var nk=/^#[0-9a-f]{6}$/;function Yt(e){return nk.test(e)}function Me(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function rt(e,t,n){let r=Me(e),i=Me(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function Ye(e){let[t,n,r]=Me(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 Ke(e,t){let n=Ye(e),r=Ye(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Ho(e,t){return Math.round(Ke(e,t)*100)/100}function rk(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]=Me(e).map(rk),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 Fn=7,jd=3,Wu=0.15,Kd=1.6,ju=[1,2,3,4,5,6,9,10,11,12,13,14],Jd=[7,15],Hn=[1,2,3,4,5,6],gn={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}},es=0.03,_t=25,Vr=15,Zr=0.08;function hn(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function Uu(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=hn(e,i);return Ke(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Ho(s,r)}:1, needs ${n}:1`]:[]})}function Bd(e,t){return Math.min(...t.map((n)=>Ke(hn(e,n),e.background)))}var qd=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Fn,measure:({foreground:e,background:t})=>Ke(e,t),check:({foreground:e,background:t})=>Ke(e,t)<Fn?[`foreground ${e} on ${t} is ${Ho(e,t)}:1, needs ${Fn}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:jd,measure:(e)=>Bd(e,ju),check:(e)=>Uu(e,ju,jd)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:Wu,measure:(e)=>Ye(hn(e,0)),check:(e)=>{let t=hn(e,0);return Ye(t)>Wu?[`ANSI 0 ${t} has luminance ${Ye(t).toFixed(3)}, needs <= ${Wu}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Fn,measure:(e)=>Bd(e,Jd),check:(e)=>Uu(e,Jd,Fn)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:Kd,measure:(e)=>Ke(hn(e,8),e.background),check:(e)=>Uu(e,[8],Kd)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Fn,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Ke(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Ke(e,t)<Fn?[`foreground ${e} on selection ${t} is ${Ho(e,t)}:1, needs ${Fn}:1`]:[]}];function Qt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var Tn=(e)=>e>8?e-8:e;function Xr(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Hn.includes(Tn(n))?[n,n>8?n-8:n+8]:[n]))}function Di(e,t){let n=Je(hn(e,t));return n.c<es?void 0:n}function Qr(e){let t=Xr(e);return ju.flatMap((n)=>{let r=Di(e,n),i=gn[Tn(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Qt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function pr(e){let t=new Set(e.signatureSlots);return Hn.flatMap((n)=>{let r=Di(e,n),i=Di(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Qt(r.h,i.h)}]})}function br(e){let t=Xr(e);return[0,8].flatMap((n)=>Hn.flatMap((r)=>Hn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=Di(e,s),u=Di(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Qt(a.h,u.h)<Vr&&Math.abs(a.l-u.l)<Zr?[[s,o]]:[]})))}var ik=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...Qr(e).map((t)=>t.over)),check:(e)=>Qr(e).map(({slot:t,hue:n,over:r})=>{let i=gn[Tn(t)];return`ANSI ${t} ${hn(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:_t,measure:(e)=>Math.max(0,...pr(e).map((t)=>t.gap)),check:(e)=>pr(e).filter((t)=>t.gap>_t).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${_t}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>br(e).length,check:(e)=>br(e).map(([t,n])=>`ANSI ${t} ${hn(e,t)} and ANSI ${n} ${hn(e,n)} are within ${Vr}° hue and ${Zr} lightness`)}],To=[...qd,...ik],Ku=To.map((e)=>e.rule),pt=To.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 An(e){return To.map((t)=>Math.round(t.measure(e)*1000)/1000)}function zd(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 wr(e){return zd(To,e)}function Yd(e){return zd(qd,e)}function Qd(e){return e.flatMap(wr)}import{chmodSync as sk,copyFileSync as ok,existsSync as Dr,mkdirSync as ak,readFileSync as Ju,realpathSync as uk,renameSync as ck,rmSync as Vd,statSync as lk,writeFileSync as fk}from"node:fs";import{dirname as dk}from"node:path";function Zd(e){return`${e}.ttheme.bak`}var hk=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function Bu(e){let t=Zd(e);if(Dr(e)&&!Dr(t)&&!hk.test(Ju(e,"utf8")))ok(e,t)}function Z(e,t){let n=Dr(e)?uk(e):e;ak(dk(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(fk(r,t),Dr(n))sk(r,lk(n).mode&4095);ck(r,n)}function xn(e,t){if((Dr(e)?Ju(e,"utf8"):void 0)===t)return!1;return Bu(e),Z(e,t),!0}function Xd(e,t){let n=Zd(e),r=Dr(n)?Ju(n,"utf8"):void 0;if(t===""&&r===void 0)return Vd(e,{force:!0}),"removed";if(Z(e,t),r===void 0||r===t)return Vd(n,{force:!0}),"restored";return"kept backup"}import{createHash as nm}from"node:crypto";import{copyFileSync as B1,existsSync as Rc,mkdirSync as q1,readdirSync as z1,readFileSync as ta,renameSync as rm,rmSync as fi}from"node:fs";import{basename as im,isAbsolute as Y1,join as D}from"node:path";var Dh=Eo(sh(),1),xo=Eo(Zh(),1);import{deflateSync as Hy}from"node:zlib";var rs=[137,80,78,71,13,10,26,10],eg=13,tg=3;function ri(e){return e.length>=rs.length&&rs.every((t,n)=>e[n]===t)}function kr(e){let t=xo.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function _n(e,t){if(ri(e)){let n=Wn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return kr(e)}if(e[0]===255&&e[1]===216){let n=Dh.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 Gn(e){let t=new xo.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),xo.PNG.sync.write(t)}function Xh(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 Wn(e){if(e.length<33||!ri(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=Xh(e,"IDAT");return{width:n,height:r,alpha:Xh(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function ng(e,t=eg){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 mn(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)<eg)n++;return Math.round(n*100/(t.w*t.h))}function rg(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=Lo(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 Ty(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 ac(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 p=d;p<=Math.ceil(f+o-0.5);p++){let b=Ty((p+0.5-f)/s),m=l*a+Math.min(e-1,Math.max(0,p))-h;c[m]=(c[m]??0)+b,g+=b}for(let p=l*a;p<(l+1)*a;p++)c[p]=(c[p]??0)/g}return{first:u,size:a,weights:c}}function ig(e,t,n,r,i,s){let o=ac(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 p=c.get(f+h);if(!p)p=new Float32Array(a),s(f+h,p),c.set(f+h,p);for(let b=0;b<a;b++)u[d+b]=(u[d+b]??0)+(p[b]??0)*g}}return u}function Lo(e,t,n,r){let i=ac(e.width,t.x,t.w,n),s=e.data,o=ig(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,p=0,b=0,m=0;for(let $=0;$<i.size;$++){let k=(d+$)*4,S=(i.weights[h+$]??0)*(s[k+3]??0);g+=(s[k]??0)*S,p+=(s[k+1]??0)*S,b+=(s[k+2]??0)*S,m+=S}c[f*4]=g,c[f*4+1]=p,c[f*4+2]=b,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 sg(e,t,n,r){let i=ac(e.width,t.x,t.w,n),s=e.data,o=ig(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 is(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 p=0;p<s;p++)c[f+p]=(c[f+p]??0)+(u[g+p]??0)*h}}return{width:s,height:o,data:c}}function ss(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 os(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 Ay=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 xy(e){let t=4294967295;for(let n of e)t=(Ay[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function ns(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(xy(n.subarray(4,8+t.length)),8+t.length),n}function Ly(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),p=Math.abs(l+f-2*d);i[o+1+c]=(e[a+c]??0)-(h<=g&&h<=p?l:g<=p?f:d)&255}}return i}function og(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(rs),ns("IHDR",r),...n,ns("IDAT",Hy(Ly(e.data,e.width,e.height))),ns("IEND",new Uint8Array)])}function ag(e){let[t,n,r]=Me(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return ns("PLTE",i)}function as(e,t){return og(e,tg,[ag(t),ns("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function uc(e){return og(e,0,[])}function ug(e,t){if(!ri(e)||e[25]!==tg)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(rs)],i=rs.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 T1,readFileSync as Kg}from"node:fs";import{basename as A1,join as Jg}from"node:path";/*!
72
72
  * Copyright (c) Squirrel Chat et al., All rights reserved.
73
73
  * SPDX-License-Identifier: BSD-3-Clause
74
74
  *
@@ -94,9 +94,9 @@ ${a}
94
94
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
95
95
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
96
96
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97
- */function by(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function wy(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
97
+ */function Cy(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function _y(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
98
98
  `,o===t)i+=" ".repeat(s+n+2),i+=`^
99
- `}return i}class j extends Error{line;column;codeblock;constructor(e,t){let[n,r]=by(t.toml,t.ptr),i=wy(t.toml,n,r);super(`Invalid TOML document: ${e}
99
+ `}return i}class j extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Cy(t.toml,t.ptr),i=_y(t.toml,n,r);super(`Invalid TOML document: ${e}
100
100
 
101
101
  ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(e,{toml:t.s,ptr:n??t.p})}}/*!
102
102
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -124,7 +124,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
124
124
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
125
125
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
126
126
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
127
- */function To(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)j.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)j.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)j.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
127
+ */function Co(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)j.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)j.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)j.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
128
128
  `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else j.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)j.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}j.x("unfinished string",e,t)}/*!
129
129
  * Copyright (c) Squirrel Chat et al., All rights reserved.
130
130
  * SPDX-License-Identifier: BSD-3-Clause
@@ -151,7 +151,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
151
151
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
152
152
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
153
153
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
154
- */var $y=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Wn 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($y);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 Wn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new Wn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new Wn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new Wn(e);return t.#t=!1,t.#e=null,t}}/*!
154
+ */var Gy=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class Un 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(Gy);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 Un(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new Un(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new Un(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new Un(e);return t.#t=!1,t.#e=null,t}}/*!
155
155
  * Copyright (c) Squirrel Chat et al., All rights reserved.
156
156
  * SPDX-License-Identifier: BSD-3-Clause
157
157
  *
@@ -177,7 +177,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
177
177
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
178
178
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
179
179
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
180
- */function bt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function rc(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function os(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||j.x("document contains excessively nested structures. aborting.",e);let i=r===91?Dh(e):Xh(e);return e.d++,i}if(r===34||r===39)return To(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)j.x("invalid value",e,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)j.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Ao(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 ky(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return yy(e,r,t);return Ao(e,e.p,r,0,t)}function Ao(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)j.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)j.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||rc(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return nc(e,t,16,i);else if(s===98)return nc(e,t,2,i);else if(s===111)return nc(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else j.x("illegal leading zero",e,t)}else if(!bt(s))j.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!rc(s,i))){if(!o)o=1;if(s===95){if(!(o&1))j.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(!bt(s))j.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))j.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):Zh(e,u,10,t)}function nc(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!rc(i,r)))if(i===95){if(s&1)j.x("illegal underscore",e);s=3}else if(!bt(i,n))j.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)j.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return Zh(e,o,n,t)}function Zh(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;j.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 ky(e,t,n){let r=e.p++,i;if(!bt(t)||!bt(e.s.charCodeAt(e.p++))||!bt(e.s.charCodeAt(e.p++))||!bt(e.s.charCodeAt(e.p++)))return Ao(e,e.p=r,t,0,n);if(e.p+=5,!bt(e.s.charCodeAt(e.p++)))j.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,!bt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return ss(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)j.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(bt(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 ss(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return ss(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return ss(e,s,2,i,r)}function yy(e,t,n){let r=e.p;if(!bt(t)||!bt(e.s.charCodeAt(++e.p)))return Ao(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(bt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return ss(e,i,4,!1,r)}function ss(e,t,n,r,i,s){if(e.ld){let o=new Wn(t,n,r);if(!o.isValid())j.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){j.x(o instanceof Error?o.message:""+o,e,i)}}/*!
180
+ */function bt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function lc(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function cs(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||j.x("document contains excessively nested structures. aborting.",e);let i=r===91?fg(e):lg(e);return e.d++,i}if(r===34||r===39)return Co(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)j.x("invalid value",e,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)j.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return _o(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 Wy(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return Uy(e,r,t);return _o(e,e.p,r,0,t)}function _o(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)j.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)j.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||lc(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return cc(e,t,16,i);else if(s===98)return cc(e,t,2,i);else if(s===111)return cc(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else j.x("illegal leading zero",e,t)}else if(!bt(s))j.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!lc(s,i))){if(!o)o=1;if(s===95){if(!(o&1))j.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(!bt(s))j.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))j.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):cg(e,u,10,t)}function cc(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!lc(i,r)))if(i===95){if(s&1)j.x("illegal underscore",e);s=3}else if(!bt(i,n))j.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)j.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return cg(e,o,n,t)}function cg(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;j.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 Wy(e,t,n){let r=e.p++,i;if(!bt(t)||!bt(e.s.charCodeAt(e.p++))||!bt(e.s.charCodeAt(e.p++))||!bt(e.s.charCodeAt(e.p++)))return _o(e,e.p=r,t,0,n);if(e.p+=5,!bt(e.s.charCodeAt(e.p++)))j.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,!bt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return us(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)j.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(bt(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 us(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return us(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return us(e,s,2,i,r)}function Uy(e,t,n){let r=e.p;if(!bt(t)||!bt(e.s.charCodeAt(++e.p)))return _o(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(bt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return us(e,i,4,!1,r)}function us(e,t,n,r,i,s){if(e.ld){let o=new Un(t,n,r);if(!o.isValid())j.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){j.x(o instanceof Error?o.message:""+o,e,i)}}/*!
181
181
  * Copyright (c) Squirrel Chat et al., All rights reserved.
182
182
  * SPDX-License-Identifier: BSD-3-Clause
183
183
  *
@@ -203,7 +203,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
203
203
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
204
204
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
205
205
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
206
- */function Ey(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)j.x("control characters are not allowed in comments",e)}}function Wt(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;Ey(e)}}/*!
206
+ */function jy(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)j.x("control characters are not allowed in comments",e)}}function Wt(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;jy(e)}}/*!
207
207
  * Copyright (c) Squirrel Chat et al., All rights reserved.
208
208
  * SPDX-License-Identifier: BSD-3-Clause
209
209
  *
@@ -229,7 +229,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
229
229
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
230
230
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
231
231
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
232
- */function Lo(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)j.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)j.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))j.x("illegal quoted key: multiline strings are not allowed",e);i.push(To(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)j.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));j.x("incomplete key-value: cannot find end of key",e,n)}function Xh(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Wt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Lo(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])))j.x("trying to redefine an already defined value",e,u);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&j.x("document contains an unsafe property",e,u);break}if(!a&&d)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)j.x("trying to redefine an already defined value",e,u);Wt(e,!0,!0);let l=os(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Wt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished table",e,t)}function Dh(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Wt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(os(e,93)),Wt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished array",e,t)}/*!
232
+ */function Go(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)j.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)j.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))j.x("illegal quoted key: multiline strings are not allowed",e);i.push(Co(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)j.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));j.x("incomplete key-value: cannot find end of key",e,n)}function lg(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Wt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Go(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])))j.x("trying to redefine an already defined value",e,u);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&j.x("document contains an unsafe property",e,u);break}if(!a&&d)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)j.x("trying to redefine an already defined value",e,u);Wt(e,!0,!0);let l=cs(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Wt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished table",e,t)}function fg(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Wt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(cs(e,93)),Wt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)j.x("expected comma or end of structure",e,e.p-1)}j.x("unfinished array",e,t)}/*!
233
233
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
234
  * SPDX-License-Identifier: BSD-3-Clause
235
235
  *
@@ -255,7 +255,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
255
255
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
256
256
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
257
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
- */function eg(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 tg(e,t,n){if(t===null||e.uk===2)j.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function ic(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++;Wt(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=Lo(n,93);if(c){if(e.charCodeAt(n.p)!==93)j.x("expected end of table array declaration",n);n.p++}let f=eg(n,l,r,i,c?2:1);if(!f)tg(n,f,s),o=!0;else u=f[2],a=f[1]}else{s=n.p;let c=Lo(n),l=eg(n,c,a,u,0);if(!l&&!o)tg(n,l,s);Wt(n,!0,!0);let f=os(n,void 0);if(l&&!o)l[1][l[0]]=f}if(Wt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))j.x("each key-value declaration must be followed by an end-of-line",n);Wt(n)}return r}/*!
258
+ */function dg(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 hg(e,t,n){if(t===null||e.uk===2)j.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++;Wt(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=Go(n,93);if(c){if(e.charCodeAt(n.p)!==93)j.x("expected end of table array declaration",n);n.p++}let f=dg(n,l,r,i,c?2:1);if(!f)hg(n,f,s),o=!0;else u=f[2],a=f[1]}else{s=n.p;let c=Go(n),l=dg(n,c,a,u,0);if(!l&&!o)hg(n,l,s);Wt(n,!0,!0);let f=cs(n,void 0);if(l&&!o)l[1][l[0]]=f}if(Wt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))j.x("each key-value declaration must be followed by an end-of-line",n);Wt(n)}return r}/*!
259
259
  * Copyright (c) Squirrel Chat et al., All rights reserved.
260
260
  * SPDX-License-Identifier: BSD-3-Clause
261
261
  *
@@ -281,7 +281,7 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
281
281
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
282
282
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
283
283
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284
- */var mO=!!"".isWellFormed;/*!
284
+ */var TO=!!"".isWellFormed;/*!
285
285
  * Copyright (c) Squirrel Chat et al., All rights reserved.
286
286
  * SPDX-License-Identifier: BSD-3-Clause
287
287
  *
@@ -307,91 +307,91 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new j(
307
307
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
308
308
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
309
309
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
310
- */import{readdirSync as vy,rmSync as Sy,statSync as My}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Iy}from"node:net";import{homedir as Ny}from"node:os";import{join as us}from"node:path";import{setTimeout as Py}from"node:timers/promises";var Un=100,wt=25000000,Oy=536870912,Dr=["safe","questionable","explicit"],$r=["nudity","underwear"],uc=["comic","monochrome","sketch","chibi"],lg=["off","5","10","25","50","100"],fg=["off","720","1080","1440","1800","2560"],dg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Fy={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},Ry=/^(?:rating|score|width|height|filetype|dimension):/,as={safe:"s",questionable:"q",explicit:"e"},hg=8191,Hy=20000,Ty=5000,ng=3000,rg=8,Ay=3000,gg=60000,ig=3,Ly=3,xy="https://static.zerochan.net",mg="https://s1.zerochan.net",cc=`ttheme/${ot.version} (+${ot.homepage})`,Cy=["orig","tile","thumb","cut"],pg=new Map,Gy=t1(process.env.TTHEME_FIND_HOSTS),_y=e1(process.env.TTHEME_FIND_CUTOUTS);Iy(Ay);var Wy=["artist","character","copyright"];function sg(e){try{return vy(e)}catch{return[]}}function ei(e){return e.startsWith("//")?`https:${e}`:e}function Kn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function cs(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 Uy(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function oc(e,t,n){let r=ei(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Kn(r)}}function mn(e){return String(e??"").split(/\s+/).filter(Boolean)}function ac(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 bg(e,t){let n=ei(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:mn(t.tags),named:t.named,...ac(e.created_at)?{posted:ac(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 jy(e){let t=Uy(e);return cs(e).flatMap((n)=>{let r=ei(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>mn(i).filter((a)=>t.get(a)===o);return bg(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Kn(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:s("artist"),character:s("character"),copyright:s("copyright")},solo:void 0,versions:[oc(n.jpeg_url,n.jpeg_width,n.jpeg_height),oc(n.sample_url,n.sample_width,n.sample_height)]})})}function Ky(e){return cs(e).flatMap((t)=>{let n=ei(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return bg(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Kn(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:mn(t.tag_string_artist),character:mn(t.tag_string_character),copyright:mn(t.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>oc(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 wg(e){return e.toLowerCase().replace(/\s+/g,"_")}function Jy(e){return(Array.isArray(e)?e:[]).map((t)=>wg(String(t)))}function By(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function qy(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=Jy(i.tags),a=ei(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Kn(a),preview:`${mg}/${By(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>dg.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 zy={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function og(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 Yy(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=zy[r],o=wg(og(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=ac(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:og(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function Qy(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function Vy(e){return cs(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function Zy(e){return cs(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function Xy(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function Dy(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function e1(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 t1(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 yr(e){return xo(e,Dr,["safe"])}function ti(e){return xo(e,$r,$r,"none")}function Co(e){return xo(e,uc,[],"none")}function ls(e){let t=X.map((n)=>n.name);return xo(e,t,t)}function lc(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function fs(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function fc(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function dc(e){let t=Gy.get(e.key),n=_y.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 $g(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function kg(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function ag(e){let t=dc(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}`]:[],...kg(i)],cutouts:$g(t.cutouts),ratings:fc([as.safe],[as.questionable],[as.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${as[i]}`;let s=Dr.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${as[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(Un),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:jy,count:Xy,uploadedBy:(r)=>`user:${r}`}}function n1(e){let t=dc(e),n=fc(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...kg(i),...s?["filetype:png"]:[]],cutouts:$g(t.cutouts),ratings:n,rate:(r)=>r.length===Dr.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(Un),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:Ky,count:Dy,uploadedBy:(r)=>`user:${r}`}}function sc(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function ug(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 r1(e){let t=dc(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:fc(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${sc(n)}?${new URLSearchParams({json:"",l:String(Un),p:String(r+1),...ug(n)})}`,countUrl:(n)=>`${t.origin}/${sc(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:qy,count:Qy,credits:Yy,counts:(n)=>sc(n).split(",").length===1&&!("d"in ug(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(mg,xy).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function i1(e){let t=cg(`https://${e}`);return X.find((n)=>cg(n.origin)===t)}function hc(e){return e.split(/\s+/).filter((t)=>t&&!Ry.test(t)).length}function Go(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=i1(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=[n1({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),ag({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),ag({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),r1({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ft=X.find((e)=>e.key==="danbooru"),Jn=134217728;function Rt(e,t){let n=X.indexOf(e);return(n===-1?X.length:n)*Jn+t}function cg(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function ni(e,t,n=t){return t.mirror&&n===t?{site:Ft,url:t.mirror.file}:{site:e,url:n.file}}function _o(e,t){return t.mirror?{site:Ft,url:t.mirror.preview}:{site:e,url:t.preview}}function Wo(e,t=$r){return e.tags.filter((n)=>t.some((r)=>dg[r].has(n)))}function yg(e,t){return e.tags.filter((n)=>t.some((r)=>Fy[r].has(n)))}function Uo(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function Eg(e,t){return e.rate(["safe"])===""?void 0:Dr.find((n)=>e.ratings[n].has(t.rating))}function Zt(e){return[e,...e.smaller].find((t)=>t.width*t.height<=wt)}function vg(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 ri(){return us(process.env.XDG_CACHE_HOME??us(Ny(),".cache"),"ttheme")}function Xt(e){return us(ri(),e.key)}function Sg(e=Oy,t=ri()){let n=[],r=0;for(let i of sg(t))for(let s of Cy){let o=us(t,i,s);for(let a of sg(o)){let u=us(o,a);try{let{size:c,mtimeMs:l}=My(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{Sy(i.path,{force:!0}),r-=i.size}catch{}}}function s1(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)?gg:Math.max(0,n-t)}function jn(e){return pg.get(e.key)??0}function o1(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function a1(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function u1(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function kr(e,t,n,r={},i=Hy){let s=t;for(let o=1,a=0;;o++){let u=jn(e)-Date.now();if(u>0)await Py(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":cc,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(o<ig&&!n.aborted&&o1(f))continue;throw f}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<Ly){await c.body?.cancel(),s=u1(s,l),a++,o--;continue}if(c.status===429&&o<ig){await c.body?.cancel();let f=s1(c.headers.get("retry-after"),Date.now());if(f>gg)throw Error(`${e.name} asks to wait ${Math.ceil(f/1000)}s`);pg.set(e.key,Math.max(jn(e),Date.now()+f));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(a1(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function jo(e,t,n){try{return await(await kr(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function Mg(e,t,n,r){return e.parse(await jo(e,e.postsUrl(t,n),r))}async function gc(e,t,n){return e.count(await jo(e,e.countUrl(t),n))}async function ds(e,t,n){let[r]=e.parse(await jo(e,e.postUrl(t),n));return r}async function Ko(e,t,n){return e.credits?.(await jo(e,e.pageUrl(t),n))}var c1=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,l1=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function hs(e){let t=c1.exec(e)?.[1]??l1.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function Jo(e,t){return e.credits!==void 0&&t.named.artist.length===0}function gs(e,t){for(let n of Wy){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 f1(e){let t=new URLSearchParams({limit:String(2*Un),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${Ft.origin}/posts.json?${t}`}function d1(e){return new Map(cs(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:mn(t.tag_string),named:{artist:mn(t.tag_string_artist),character:mn(t.tag_string_character),copyright:mn(t.tag_string_copyright)},source:String(t.source??""),file:ei(String(t.file_url??""))}]]:[]}))}function Bo(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])],gs(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=Kn(r.file)}}}async function qo(e,t){let n=new Map;if(jn(Ft)>Date.now())return n;for(let r=0;r<e.length;r+=Un){let i=await(await kr(Ft,f1(e.slice(r,r+Un)),t,{},Ty)).text();for(let[s,o]of d1(i))n.set(s,o)}return n}async function zo(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await kr(e,r,n,{Range:`bytes=0-${hg}`}),s=_n(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Kn(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 Ig(e,t){if(jn(Ft)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(rg)}),s=`${Ft.origin}/autocomplete.json?${i}`;return Vy(await(await kr(Ft,s,t,{},ng)).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(rg)});return Zy(await(await kr(n,`${n.origin}/tag.json?${r}`,t,{},ng)).text())}async function Ng(e,t,n){let r=await kr(e,t,n,{Range:`bytes=0-${hg}`});return _n(new Uint8Array(await r.arrayBuffer()))}async function Yo(e,t,n,r){let i=await kr(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 $t=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],ms="Original",m1=1e6,Dt="_groups.toml",Pg=3,Og=8,mc="[a-z0-9]+(?:-[a-z0-9]+)*",p1=new RegExp(`^(?:(${mc})@(${mc})/)?(${mc})$`),Tg=["background","foreground","cursor","selection"];function he(e,t){throw Error(`${e}: ${t}`)}function Er(e,t,n){if(typeof n!=="string"||!Yt(n))he(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function bs(e,t,n){if(typeof n!=="string"||n.length===0)he(e,`${t} must be a non-empty string`);return n}function pn(e){return e.replace("@","--").replace("/","--")}function z(e){return`ttheme-${pn(e)}`}function ve(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function si(e){return e.slice(e.indexOf("/")+1)}function en(e){let t=p1.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 ws(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function ps(e,t,n){let r=bs(e,t,n),i=ws(r);if(i)he(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function Fg(e,t,n){let r=bs(e,t,n),i=en(r);if(i)he(e,`${t} "${r}" ${i}`);return r}function ii(e){return e&&typeof e==="object"?e:{}}function b1(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)he(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Er(e,`ghostty.icon_screen[${s}]`,i))}function w1(e,t,n){let r=ii(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Er(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:b1(e,r.icon_screen,n)}}function $1(e){return new Map([...Tg.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function k1(e,t,n){if(!Array.isArray(t)||t.length!==Pg)he(e,`meta.signature must name exactly ${Pg} palette slots`);let r=$1(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=bs(e,u,a),l=r.get(c);if(l===void 0)he(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${Tg.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)he(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function y1(e,t,n){if(t===void 0)return;if(!n)he(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))he(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)he(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)))he(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))he(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function E1(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>Og)he(e,`[[picture]] holds 1 to ${Og} pictures`);return t.map((n,r)=>{let i=ii(n),s=`picture[${r}]`,o=X.find((l)=>l.key===i.site);if(!o)he(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)he(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))he(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!$t.includes(u))he(e,`${s}.position must be one of ${$t.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))he(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 Ag(e,t){try{return ic(t)}catch(n){he(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
- `)[0]}`)}}function v1(e){let n=Ag(Dt,Rg(Hg(e,Dt),"utf8")).group;if(!Array.isArray(n)||n.length===0)he(Dt,"needs at least one [[group]] table");return n.map((r)=>{let i=ii(r);return{name:ps(Dt,"group.name",i.name),native:i.native===void 0?void 0:ps(Dt,"group.native",i.native),lead:bs(Dt,"group.lead",i.lead)}})}function S1(e,t){if(!Array.isArray(t)||t.length===0)he(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=ps(e,`meta.native_names[${r}]`,n);if(i.includes("|"))he(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function pc(e,t,n){let r=Ag(e,t),i=ii(r.meta),s=ii(r.colors),o=ii(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)he(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=Fg(e,"meta.name",i.name);if(u!==n.name)he(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let T of["order","role"])if(c&&i[T]!==void 0)he(e,`meta.${T} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")he(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:Fg(e,"meta.base",i.base);if(f!==void 0&&!c)he(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:ps(e,"meta.group",i.group),g=n.groups.get(h);if(!g&&!(c&&(h===ms||n.open)))he(e,`meta.group "${h}" has no [[group]] table in ${Dt}`);let p=Er(e,"colors.background",s.background),b=Er(e,"colors.foreground",s.foreground),m=Er(e,"colors.cursor",s.cursor),$=Er(e,"colors.selection_background",s.selection_background),k=a.map((T,A)=>Er(e,`colors.ansi[${A}]`,T)),M=k1(e,i.signature,{background:p,foreground:b,cursor:m,selection:$,ansi:k}),w=i.booru===void 0?void 0:bs(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))he(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let S=y1(e,i.booru_sites,w),y=i.native_names===void 0?void 0:S1(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")he(e,"contrast.waive needs a contrast.reason explaining why");let O=E1(e,r.picture);return{name:u,...f?{base:f}:{},group:h,native:g?.native,...y?{nativeNames:y}:{},lead:!c&&g?.lead===u,order:c?d?.order??m1:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?f??"original":ps(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...S?{booruSites:S}:{},background:p,foreground:b,cursor:m,selectionBackground:$,ansi:k,signature:M.colors,signatureSlots:M.names,ghostty:w1(e,r.ghostty,{background:p,cursor:m,selectionBackground:$}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...O?{pictures:O}:{}}}function Lg(e){let t=v1(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)he(Dt,"group.name must be unique");let r=h1(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>pc(s,Rg(Hg(e,s),"utf8"),{name:g1(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)he(Dt,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))he(Dt,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function xg(e){return e.filter((t)=>t.role===void 0)}function vr(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>ve(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(ve(r.name)!==void 0)-Number(ve(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 Qo={width:2560,height:1550},O1=2560,F1=0.1,R1=0.99,H1=2,bn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},T1=Ye(rt("#19161e","#9b86c8",0.2)),A1="shelf",Xo="originals",L1="images.json",bc=1;function x1(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 Cg(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 Gg(e,t){let n=x1(e,t),i=Cg((c)=>xd({name:e.name,background:rt(e.background,n,c),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),s=Cg((c)=>Ye(rt(e.background,n,c))<=T1),o=Math.floor(Math.min(i,s)*100)/100,a=Pe(e.background),u=Math.hypot(...Pe(n).map((c,l)=>(c-(a[l]??0))*o));return{slot:t,color:n,cap:i,matched:s,opacity:o,reach:u}}function ai(e,t){let n=Gg(e,"cursor");if(n.opacity>=F1)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Gg(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function C1(e){return Jh(e)??{x:0,y:0,w:e.width,h:e.height}}function Ec(e,t){if(e<=0||t<=0)return Qo;let n=Math.min(1,Qo.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function qg(e,t,n,r){if(r<bn.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(bn.tall*n,bn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>bn.widest*t)s=bn.widest*t,i=s*e.h/e.w;let o=bn.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-bn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function zg(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function G1(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(zg(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*R1)return Math.min(H1,Math.max(1,255/Math.max(1,o)));return 1}function _1(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,zg(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function Vo(e,t,n,r){let i=new Float32Array(n*r),s=Math.max(0,Math.round(t.at.x)),o=Math.max(0,Math.round(t.at.y)),a=Math.min(n,Math.round(t.at.x+t.at.w)),u=Math.min(r,Math.round(t.at.y+t.at.h));if(a>s&&u>o){let c=t.crop.w/t.at.w,l=t.crop.h/t.at.h,f={x:t.crop.x+(s-t.at.x)*c,y:t.crop.y+(o-t.at.y)*l,w:(a-s)*c,h:(u-o)*l},d=zh(e,f,a-s,u-o);for(let h=o;h<u;h++)i.set(d.data.subarray((h-o)*(a-s),(h-o+1)*(a-s)),h*n+s)}return{width:n,height:r,data:i}}function vc(e){let t=C1(e);return{box:t,clear:gn(e,t),ink:_1(e,G1(e,t))}}function Yg(e,t,n,r){let{box:i,clear:s,ink:o}=vc(e),a=qg(i,t,n,s),u=Math.min(1,O1/Math.max(i.w,i.h)),c={x:0,y:0,w:Math.round(i.w*u),h:Math.round(i.h*u)},l=Vo(o,{crop:i,at:c,focus:a.focus},c.w,c.h),f=Vo(o,a,t,n);return{figure:ns(Ho(l,r*c.w*a.crop.w/(i.w*a.at.w))),fill:ns(Ho(f,r)),focus:a.focus}}function W1(e,t,n,r){let i=Pe(t),s=Pe(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 Qg(e,t,n,r,i,s,o){let{box:a,clear:u,ink:c}=e,l=qg(a,r,i,u),f=Math.round(100*l.at.w/l.crop.w/Math.min(r/a.w,i/a.h)),d=o?.size??"fill",h=d==="fill"?l:{crop:a,at:nm(a.w,a.h,r,i,d,o?.at??5,!1,d>100?Math.round(l.focus*100):-1),focus:l.focus};return{image:W1(ns(Ho(Vo(c,h,r,i),s)),t.background,n.color,o?.opacity??n.opacity),fill:f}}function Te(e){return D(e,"ttheme","backgrounds")}function wc(e){return D(e,L1)}function qn(e){try{return Zo(e,"utf8")}catch{return}}function Bn(e){try{return N1(e)}catch{return[]}}function lt(e){let t=qn(wc(e));if(t===void 0)return U1(e);let n=JSON.parse(t);if(n.version!==bc)throw Error(`${wc(e)} is version ${n.version} — this ttheme reads version ${bc}`);return n}function _g(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function Vg(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${_g(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?_g(i):"-"}`,...i.from?[i.from]:[]].join(" ")),`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 Zg(e){let t=Te(e);for(let[n,r]of Object.entries(lt(t).palettes)){let i=D(t,`${pn(n)}.conf`),s=Vg(t,r);if(qn(i)!==s)Z(i,s)}}function ui(e,t,n){Z(wc(e),`${JSON.stringify(t,null,2)}
313
- `);for(let r of n){let i=t.palettes[r],s=D(e,`${pn(r)}.conf`);if(i)Z(s,Vg(e,i));else oi(s,{force:!0})}}function Xg(e,t){return Bn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function Sc(e,t){for(let n of Xg(e,t))oi(D(e,n),{force:!0})}function Dg(e,t){Sc(e,t.stem);for(let n of[t.original,t.cut])if(n)oi(D(e,n),{force:!0})}function Wg(e,t,n,r){let i=Bg(/^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(Xo,c)}:{}}}function Ug(e,t){if(yc(e))Jg(e,t)}function U1(e){let t={version:bc,palettes:{}};if(!yc(e))return t;let n=Bn(D(e,Xo)),r=Bn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=D(e,A1);for(let s of new Set([...r,...Bn(i)])){let o=[],a=Wg(s,qn(D(e,`${s}.conf`)),n);if(a)Ug(D(e,`${s}.tune.conf`),D(e,`${a.stem}.tune.conf`)),Ug(D(e,`${s}.off.conf`),D(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Bn(D(i,s))){let c=D(i,s,u),l=Wg(s,qn(D(c,".conf")),n,u);if(!l)continue;for(let f of Bn(c)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${s}${f}`;if(f!==".conf")Jg(D(c,f),D(e,d))}oi(c,{recursive:!0}),o.push(l)}if(Bn(D(i,s)).length===0)oi(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(Bn(i).length===0)oi(i,{recursive:!0,force:!0});return ui(e,t,Object.keys(t.palettes)),t}function jg(e,t,n){return t.startsWith("~/")?D(n,t.slice(2)):P1(t)?t:D(e,t)}function em(e,t,n){let r=new Map,i=(a,u)=>{let c=qn(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(jg(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,`${pn(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:jg(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 Do(e,t,n){let r=Te(e),i=lt(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);Dg(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 ui(r,i,[t]),{key:a.key,left:s.pictures.length}}function tm(e,t,n,r){let i=is(n.figure,r),s=is(n.fill,r),o=`${pn(e)}.${Kg("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 $c(e,t){return D(Xo,`${pn(e)}-${t}`)}function Mc(e,t){return t.map(([n,r])=>{let i=D(e,n);return Z(i,r),i})}function ea(e,t,n,r,i,s,o){let a=Te(e),u=t.name,c=ft(i),l=lt(a),f=l.palettes[u]??{active:c,pictures:[]},d=Ec(s.width,s.height),h=tm(u,c,Yg(r,d.width,d.height,o),n.color),g=$c(u,c),p={key:c,stem:h.stem,fill:h.fill,opacity:n.opacity,tone:n.color,blur:o,window:d,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${g}.${i.ext}`,...i.cut?{cut:`${g}.cut.png`}:{}},b=f.pictures.find(($)=>$.key===c);if(b)Dg(a,b);I1(D(a,Xo),{recursive:!0});let m=Mc(a,[...h.files,[p.original,i.bytes],...p.cut?[[p.cut,tc(rs(r))]]:[]]);return f.pictures=b?f.pictures.map(($)=>$===b?p:$):[...f.pictures,p],f.active=c,l.palettes[u]=f,ui(a,l,[u]),[...m,D(a,`${pn(u)}.conf`)]}function ci(e,t,n){let r=Te(e),i=lt(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,ui(r,i,[t]);return{at:o+1,of:s.pictures.length}}function Ht(e,t){let n=lt(Te(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var kc="top-right";function nm(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),p=u(l*(r-h)/2);if(a>=0){if(d>n)g=u((n-d)/2);if(h>r)p=Math.max(r-h,Math.min(0,u(r/2)-u(a*h/100)))}return{x:g,y:p,w:d,h}}function Ic(e,t){let n=qn(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=Bg(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!==kc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function $s(e,t,n,r,i){let s=n.size??"fill",o=n.position??kc,a=n.opacity??t.opacity;if(s==="fill"&&o===kc&&a===t.opacity)return;let u=$t.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(!t.tone)throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=rs(wr(new Uint8Array(Zo(c)))),{width:p,height:b}=d?Qo:g,m=d?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,$=nm(g.width,g.height,p,b,s,u,!1,m);l=D(e,`${t.stem}@${s}-${o}${d?`-${p}x${b}`:""}.png`);let k={x:0,y:0,w:g.width,h:g.height};Z(l,is(ns(Vo(g,{crop:k,at:$,focus:m},p,b)),t.tone)),f=d}let h=D(e,`${t.stem}.tune.conf`);return Z(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 rm(e){let t=new Map;for(let[n,r]of Object.entries(lt(Te(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 j1(e){try{let t=_n(new Uint8Array(Zo(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function ta(e,t,n,r,i,s,o,a,u){let c=Te(e),l=n.window??j1(D(c,n.fill))??Qo,f=tm(t,n.key,Yg(r,l.width,l.height,s),i.color),d={...n,stem:f.stem,fill:f.fill,opacity:i.opacity,tone:i.color,blur:s,window:l,...u?{cut:`${$c(t,n.key)}.cut.png`}:{}};if(u)Z(D(c,`${$c(t,n.key)}.cut.png`),tc(rs(r)));if(f.stem===n.stem)return d;Mc(c,f.files),$s(c,d,Ic(c,n),o,a);let h=D(c,`${n.stem}.off.conf`);if(yc(h))M1(h,D(c,`${d.stem}.off.conf`));return d}function im(e,t){let n=Te(e),r=lt(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;ui(n,r,[...i]);for(let o of s)Sc(n,o)}function K1(e,t,n,r){let i=(u)=>u.replace(/^background-image-opacity = (\S+)$/m,(c,l)=>Number(l)===n.opacity?`background-image-opacity = ${r.opacity}`:c);if(n.tone===r.color){let u=D(e,`${n.stem}.tune.conf`),c=qn(u);if(c!==void 0)Z(u,i(c));return{...n,opacity:r.opacity}}let s=Xg(e,n.stem).filter((u)=>u.endsWith(".png")).map((u)=>{let c=new Uint8Array(Zo(D(e,u)));return[u,Vh(c,r.color)??is(rs(wr(c)),r.color)]}),o=(u)=>s.find(([c])=>c===u)?.[1]??new Uint8Array,a=`${pn(t)}.${Kg("sha1").update(n.key).update(o(`${n.stem}.png`)).update(o(n.fill)).digest("hex").slice(0,8)}`;Mc(e,s.map(([u,c])=>[a+u.slice(n.stem.length),c]));for(let u of["tune","off"]){let c=qn(D(e,`${n.stem}.${u}.conf`));if(c!==void 0)Z(D(e,`${a}.${u}.conf`),i(c.split(n.stem).join(a)))}return{...n,stem:a,fill:a+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function sm(e,t){let n=Te(e),r=lt(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o),c=a.pictures.filter((l)=>u&&l.tone&&(l.tone!==u.color||l.opacity!==u.opacity));if(!u||c.length===0)continue;a.pictures=a.pictures.map((l)=>{if(!c.includes(l))return l;let f=K1(n,o,l,u);if(f.stem!==l.stem)s.push(l.stem);return f}),i.push(o)}if(i.length>0){ui(n,r,i);for(let o of s)Sc(n,o)}return i}function Ut(e){let{slot:t,color:n,opacity:r}=ai({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:An(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function wn(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 J1=6,B1=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function na(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,...B1]){let o=t(s);if(i.length===J1||!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 ks(){return{version:ot.version,gate:pt,placement:bn,palettes:[]}}function q1(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...ks(),palettes:e.map(Ut)}}var Nc={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(q1(e),null,2)}
316
- `}]}};import{existsSync as D1,readdirSync as fm,readFileSync as eE}from"node:fs";import{basename as dm,join as ys}from"node:path";import{existsSync as z1,readFileSync as om}from"node:fs";import{homedir as am}from"node:os";import{isAbsolute as um,join as Sr,resolve as Y1}from"node:path";var ee="official",tn="ttheme-market.json",li="ttheme-market",Q1=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,V1=/^[\w.-]{1,100}$/,Z1=/^\w[\w.+/-]{0,199}$/;function Yn(e){return Sr(e,"ttheme","installed.json")}function it(e){return e??[ee]}function fi(e){try{let{markets:t}=JSON.parse(om(Yn(e),"utf8"));return it(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[ee]}}function Ae(e){return um(e)}function kt(e){return e!==ee&&!Ae(e)}function zn(e){let t=e.indexOf("#");return kt(e)&&t>=0?e.slice(0,t):e}function Pc(e){let t=e.indexOf("#");return kt(e)&&t>=0?e.slice(t+1):void 0}function di(e,t){return zn(e)===zn(t)}function Qn(e,t){return!Ae(e)&&(t?.[e]??e===ee)}function X1(e){return!Z1.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function Vn(e,t=process.cwd()){if(e===ee)return ee;if(e==="~"||e.startsWith("~/"))return Sr(am(),e.slice(1));if(e.startsWith(".")||um(e))return Y1(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!Q1.test(s)||!o||!V1.test(o)||a.length>0||i.length>0||r!==void 0&&X1(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 cm(e){let t=Pc(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${zn(e)}/${t}/${tn}`}function lm(e){return e.slice(0,e.indexOf("/"))}function Oc(e){return Sr(e,"ttheme","markets")}function jt(e,t){return Sr(Oc(e),`${zn(t).replace("/","--")}.json`)}function ra(e){return Sr(e,"ttheme","market")}function Fc(e,t){return Sr(ra(e),t)}function Rc(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return en(`${e}@${t}/x`)}function yt({owner:e,name:t}){return`${e}@${t}`}function nn(e){let t=Sr(e,tn);if(!z1(t))throw Error(`${e} has no ${tn} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(om(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Rc(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(!Ae(e))return`github.com/${e}`;let t=am();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var $n="tt1:",hm=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function Mr(e,t=!0){return fi(e).filter(Ae).flatMap((n)=>{try{let r=nn(n);return[{dir:n,...r,id:yt(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
- `);return[]}})}function ia(e){return ys(e,"palettes")}function Zn(e){let t=ia(e);if(!D1(t))return[];let n=[],r=[];for(let i of fm(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of fm(ys(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:ys(t,i.name,s),slug:dm(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:ys(t,i.name),slug:dm(i.name,".toml")})}return[...n,...r]}function Es(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:ws(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function Hc(e,t){let n=ve(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=Mr(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=si(t);return Zn(r.dir).find((s)=>s.slug===i)?.path??ys(ia(r.dir),`${i}.toml`)}function tE(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&&!ve(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function Et(e,t,n){let r=si(e),{native:i,...s}=pc(`${r}.toml`,t,tE(r,n)),o=ve(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function Xn(e,t,n,r=!0){let i=new Map;return Zn(e).flatMap((s)=>{try{let o=Es(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Ut(Et(`${t}/${s.slug}`,eE(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 sa(e,t,n=!0){return Mr(e,n).flatMap(({dir:r,id:i})=>Xn(r,i,t,n))}function Tc(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 qe=(e)=>JSON.stringify(e);function gm(e){return["[[picture]]",`site = ${qe(e.site)}`,`id = ${e.id}`,...e.size===void 0?[]:[`size = ${typeof e.size==="number"?e.size:qe(e.size)}`],...e.position===void 0?[]:[`position = ${qe(e.position)}`],...e.opacity===void 0?[]:[`opacity = ${e.opacity}`]]}function mm(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
310
+ */import{readdirSync as Ky,rmSync as Jy,statSync as By}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as qy}from"node:net";import{homedir as zy}from"node:os";import{join as fs}from"node:path";import{setTimeout as Yy}from"node:timers/promises";var jn=100,wt=25000000,Qy=536870912,ii=["safe","questionable","explicit"],yr=["nudity","underwear"],mc=["comic","monochrome","sketch","chibi"],Eg=["off","5","10","25","50","100"],vg=["off","720","1080","1440","1800","2560"],Mg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Vy={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},Zy=/^(?:rating|score|width|height|filetype|dimension):/,ls={safe:"s",questionable:"q",explicit:"e"},Sg=8191,Xy=20000,Dy=5000,gg=3000,mg=8,e1=3000,Ig=60000,pg=3,t1=3,n1="https://static.zerochan.net",Ng="https://s1.zerochan.net",pc=`ttheme/${ot.version} (+${ot.homepage})`,r1=["orig","tile","thumb","cut"],Pg=new Map,i1=y1(process.env.TTHEME_FIND_HOSTS),s1=k1(process.env.TTHEME_FIND_CUTOUTS);qy(e1);var o1=["artist","character","copyright"];function bg(e){try{return Ky(e)}catch{return[]}}function si(e){return e.startsWith("//")?`https:${e}`:e}function Jn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function ds(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 a1(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=si(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Jn(r)}}function pn(e){return String(e??"").split(/\s+/).filter(Boolean)}function gc(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 Og(e,t){let n=si(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:pn(t.tags),named:t.named,...gc(e.created_at)?{posted:gc(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 u1(e){let t=a1(e);return ds(e).flatMap((n)=>{let r=si(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>pn(i).filter((a)=>t.get(a)===o);return Og(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Jn(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 c1(e){return ds(e).flatMap((t)=>{let n=si(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return Og(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Jn(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:pn(t.tag_string_artist),character:pn(t.tag_string_character),copyright:pn(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 Rg(e){return e.toLowerCase().replace(/\s+/g,"_")}function l1(e){return(Array.isArray(e)?e:[]).map((t)=>Rg(String(t)))}function f1(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function d1(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=l1(i.tags),a=si(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Jn(a),preview:`${Ng}/${f1(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>Mg.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 h1={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function wg(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 g1(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=h1[r],o=Rg(wg(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=gc(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:wg(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function m1(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function p1(e){return ds(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function b1(e){return ds(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function w1(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function $1(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function k1(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 y1(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 Wo(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 vr(e){return Wo(e,ii,["safe"])}function oi(e){return Wo(e,yr,yr,"none")}function Uo(e){return Wo(e,mc,[],"none")}function hs(e){let t=X.map((n)=>n.name);return Wo(e,t,t)}function bc(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function gs(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function wc(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function $c(e){let t=i1.get(e.key),n=s1.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 Fg(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function Hg(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function $g(e){let t=$c(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}`]:[],...Hg(i)],cutouts:Fg(t.cutouts),ratings:wc([ls.safe],[ls.questionable],[ls.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ls[i]}`;let s=ii.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${ls[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(jn),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:u1,count:w1,uploadedBy:(r)=>`user:${r}`}}function E1(e){let t=$c(e),n=wc(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...Hg(i),...s?["filetype:png"]:[]],cutouts:Fg(t.cutouts),ratings:n,rate:(r)=>r.length===ii.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(jn),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:c1,count:$1,uploadedBy:(r)=>`user:${r}`}}function dc(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function kg(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 v1(e){let t=$c(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:wc(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${dc(n)}?${new URLSearchParams({json:"",l:String(jn),p:String(r+1),...kg(n)})}`,countUrl:(n)=>`${t.origin}/${dc(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:d1,count:m1,credits:g1,counts:(n)=>dc(n).split(",").length===1&&!("d"in kg(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Ng,n1).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function M1(e){let t=yg(`https://${e}`);return X.find((n)=>yg(n.origin)===t)}function kc(e){return e.split(/\s+/).filter((t)=>t&&!Zy.test(t)).length}function jo(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=M1(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=[E1({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),$g({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),$g({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),v1({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Ft=X.find((e)=>e.key==="danbooru"),Bn=134217728;function Ht(e,t){let n=X.indexOf(e);return(n===-1?X.length:n)*Bn+t}function yg(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function ai(e,t,n=t){return t.mirror&&n===t?{site:Ft,url:t.mirror.file}:{site:e,url:n.file}}function Ko(e,t){return t.mirror?{site:Ft,url:t.mirror.preview}:{site:e,url:t.preview}}function Jo(e,t=yr){return e.tags.filter((n)=>t.some((r)=>Mg[r].has(n)))}function Tg(e,t){return e.tags.filter((n)=>t.some((r)=>Vy[r].has(n)))}function Bo(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function Ag(e,t){return e.rate(["safe"])===""?void 0:ii.find((n)=>e.ratings[n].has(t.rating))}function Zt(e){return[e,...e.smaller].find((t)=>t.width*t.height<=wt)}function xg(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 ui(){return fs(process.env.XDG_CACHE_HOME??fs(zy(),".cache"),"ttheme")}function Xt(e){return fs(ui(),e.key)}function Lg(e=Qy,t=ui()){let n=[],r=0;for(let i of bg(t))for(let s of r1){let o=fs(t,i,s);for(let a of bg(o)){let u=fs(o,a);try{let{size:c,mtimeMs:l}=By(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{Jy(i.path,{force:!0}),r-=i.size}catch{}}}function S1(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)?Ig:Math.max(0,n-t)}function Kn(e){return Pg.get(e.key)??0}function I1(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function N1(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function P1(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Er(e,t,n,r={},i=Xy){let s=t;for(let o=1,a=0;;o++){let u=Kn(e)-Date.now();if(u>0)await Yy(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":pc,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(o<pg&&!n.aborted&&I1(f))continue;throw f}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<t1){await c.body?.cancel(),s=P1(s,l),a++,o--;continue}if(c.status===429&&o<pg){await c.body?.cancel();let f=S1(c.headers.get("retry-after"),Date.now());if(f>Ig)throw Error(`${e.name} asks to wait ${Math.ceil(f/1000)}s`);Pg.set(e.key,Math.max(Kn(e),Date.now()+f));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(N1(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function qo(e,t,n){try{return await(await Er(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function Cg(e,t,n,r){return e.parse(await qo(e,e.postsUrl(t,n),r))}async function yc(e,t,n){return e.count(await qo(e,e.countUrl(t),n))}async function ms(e,t,n){let[r]=e.parse(await qo(e,e.postUrl(t),n));return r}async function zo(e,t,n){return e.credits?.(await qo(e,e.pageUrl(t),n))}var O1=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,R1=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function ps(e){let t=O1.exec(e)?.[1]??R1.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function Yo(e,t){return e.credits!==void 0&&t.named.artist.length===0}function bs(e,t){for(let n of o1){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 F1(e){let t=new URLSearchParams({limit:String(2*jn),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${Ft.origin}/posts.json?${t}`}function H1(e){return new Map(ds(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:pn(t.tag_string),named:{artist:pn(t.tag_string_artist),character:pn(t.tag_string_character),copyright:pn(t.tag_string_copyright)},source:String(t.source??""),file:si(String(t.file_url??""))}]]:[]}))}function Qo(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])],bs(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=Jn(r.file)}}}async function Vo(e,t){let n=new Map;if(Kn(Ft)>Date.now())return n;for(let r=0;r<e.length;r+=jn){let i=await(await Er(Ft,F1(e.slice(r,r+jn)),t,{},Dy)).text();for(let[s,o]of H1(i))n.set(s,o)}return n}async function Zo(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Er(e,r,n,{Range:`bytes=0-${Sg}`}),s=Wn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Jn(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 _g(e,t){if(Kn(Ft)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(mg)}),s=`${Ft.origin}/autocomplete.json?${i}`;return p1(await(await Er(Ft,s,t,{},gg)).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(mg)});return b1(await(await Er(n,`${n.origin}/tag.json?${r}`,t,{},gg)).text())}async function Gg(e,t,n){let r=await Er(e,t,n,{Range:`bytes=0-${Sg}`});return Wn(new Uint8Array(await r.arrayBuffer()))}async function Xo(e,t,n,r){let i=await Er(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 $t=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],ws="Original",x1=1e6,Dt="_groups.toml",Wg=3,Ug=8,Ec="[a-z0-9]+(?:-[a-z0-9]+)*",L1=new RegExp(`^(?:(${Ec})@(${Ec})/)?(${Ec})$`),Bg=["background","foreground","cursor","selection"];function he(e,t){throw Error(`${e}: ${t}`)}function Mr(e,t,n){if(typeof n!=="string"||!Yt(n))he(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function ks(e,t,n){if(typeof n!=="string"||n.length===0)he(e,`${t} must be a non-empty string`);return n}function bn(e){return e.replace("@","--").replace("/","--")}function z(e){return`ttheme-${bn(e)}`}function ve(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function li(e){return e.slice(e.indexOf("/")+1)}function en(e){let t=L1.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 ys(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 $s(e,t,n){let r=ks(e,t,n),i=ys(r);if(i)he(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function jg(e,t,n){let r=ks(e,t,n),i=en(r);if(i)he(e,`${t} "${r}" ${i}`);return r}function ci(e){return e&&typeof e==="object"?e:{}}function C1(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)he(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Mr(e,`ghostty.icon_screen[${s}]`,i))}function _1(e,t,n){let r=ci(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Mr(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:C1(e,r.icon_screen,n)}}function G1(e){return new Map([...Bg.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function W1(e,t,n){if(!Array.isArray(t)||t.length!==Wg)he(e,`meta.signature must name exactly ${Wg} palette slots`);let r=G1(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=ks(e,u,a),l=r.get(c);if(l===void 0)he(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${Bg.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)he(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function U1(e,t,n){if(t===void 0)return;if(!n)he(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))he(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)he(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)))he(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))he(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function j1(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>Ug)he(e,`[[picture]] holds 1 to ${Ug} pictures`);return t.map((n,r)=>{let i=ci(n),s=`picture[${r}]`,o=X.find((l)=>l.key===i.site);if(!o)he(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)he(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))he(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!$t.includes(u))he(e,`${s}.position must be one of ${$t.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))he(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 qg(e,t){try{return fc(t)}catch(n){he(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
+ `)[0]}`)}}function K1(e){let n=qg(Dt,Kg(Jg(e,Dt),"utf8")).group;if(!Array.isArray(n)||n.length===0)he(Dt,"needs at least one [[group]] table");return n.map((r)=>{let i=ci(r);return{name:$s(Dt,"group.name",i.name),native:i.native===void 0?void 0:$s(Dt,"group.native",i.native),lead:ks(Dt,"group.lead",i.lead)}})}function J1(e,t){if(!Array.isArray(t)||t.length===0)he(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=$s(e,`meta.native_names[${r}]`,n);if(i.includes("|"))he(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function vc(e,t,n){let r=qg(e,t),i=ci(r.meta),s=ci(r.colors),o=ci(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)he(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=jg(e,"meta.name",i.name);if(u!==n.name)he(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let T of["order","role"])if(c&&i[T]!==void 0)he(e,`meta.${T} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")he(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:jg(e,"meta.base",i.base);if(f!==void 0&&!c)he(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??ws:$s(e,"meta.group",i.group),g=n.groups.get(h);if(!g&&!(c&&(h===ws||n.open)))he(e,`meta.group "${h}" has no [[group]] table in ${Dt}`);let p=Mr(e,"colors.background",s.background),b=Mr(e,"colors.foreground",s.foreground),m=Mr(e,"colors.cursor",s.cursor),$=Mr(e,"colors.selection_background",s.selection_background),k=a.map((T,A)=>Mr(e,`colors.ansi[${A}]`,T)),S=W1(e,i.signature,{background:p,foreground:b,cursor:m,selection:$,ansi:k}),w=i.booru===void 0?void 0:ks(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))he(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let M=U1(e,i.booru_sites,w),y=i.native_names===void 0?void 0:J1(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")he(e,"contrast.waive needs a contrast.reason explaining why");let O=j1(e,r.picture);return{name:u,...f?{base:f}:{},group:h,native:g?.native,...y?{nativeNames:y}:{},lead:!c&&g?.lead===u,order:c?d?.order??x1:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?f??"original":$s(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...M?{booruSites:M}:{},background:p,foreground:b,cursor:m,selectionBackground:$,ansi:k,signature:S.colors,signatureSlots:S.names,ghostty:_1(e,r.ghostty,{background:p,cursor:m,selectionBackground:$}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...O?{pictures:O}:{}}}function zg(e){let t=K1(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)he(Dt,"group.name must be unique");let r=T1(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>vc(s,Kg(Jg(e,s),"utf8"),{name:A1(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)he(Dt,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))he(Dt,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function Yg(e){return e.filter((t)=>t.role===void 0)}function Sr(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>ve(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(ve(r.name)!==void 0)-Number(ve(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 Do={width:2560,height:1550},Q1=2560,V1=0.1,sm=0.99,Z1=2,wn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},X1=Ye(rt("#19161e","#9b86c8",0.2)),D1="shelf",na="originals",eE="images.json",Sc=1;function tE(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 Qg(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 om(e,t){let r=Qg((s)=>Yd({name:e.name,background:rt(e.background,t,s),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),i=Qg((s)=>Ye(rt(e.background,t,s))<=X1);return{cap:r,matched:i,opacity:Math.floor(Math.min(r,i)*100)/100}}function Vg(e,t){let n=tE(e,t),{cap:r,matched:i,opacity:s}=om(e,n),o=Me(e.background),a=Math.hypot(...Me(n).map((u,c)=>(u-(o[c]??0))*s));return{slot:t,color:n,cap:r,matched:i,opacity:s,reach:a}}function ra(e,t){return om(e,t).opacity}function di(e,t){let n=Vg(e,"cursor");if(n.opacity>=V1)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Vg(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function nE(e){return ng(e)??{x:0,y:0,w:e.width,h:e.height}}function Fc(e,t){if(e<=0||t<=0)return Do;let n=Math.min(1,Do.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function am(e,t,n,r){if(r<wn.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(wn.tall*n,wn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>wn.widest*t)s=wn.widest*t,i=s*e.h/e.w;let o=wn.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-wn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function um(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function rE(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(um(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*sm)return Math.min(Z1,Math.max(1,255/Math.max(1,o)));return 1}var Mc=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 iE(e,t,n){return`#${[e,t,n].map((r)=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function sE(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*(Mc[c]??0)+0.7152*(Mc[l]??0)+0.0722*(Mc[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*sm){let u=Math.max(1,n[a]??1);return iE((r[a*3]??0)/u,(r[a*3+1]??0)/u,(r[a*3+2]??0)/u)}return"#ffffff"}function oE(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,um(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function cm(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 ea(e,t,n,r){let i=new Float32Array(n*r),s=cm(t,n,r);if(s){let o=sg(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 Hc(e,t,n,r){let i=new Uint8Array(n*r*4),s=cm(t,n,r);if(s){let o=s.x1-s.x0,a=Lo(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 Ic(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)=>is(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 Tc(e){let t=nE(e);return{box:t,clear:mn(e,t),ink:oE(e,rE(e,t)),image:e,peak:sE(e,t)}}function lm(e,t,n,r,i){let s=Tc(e),{box:o,clear:a,ink:u}=s,c=am(o,t,n,a),l=Math.min(1,Q1/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:Ic(Lo(e,o,f.w,f.h),d),fill:Ic(Hc(e,c,t,n),r),focus:c.focus,peak:s.peak};let h=ea(u,{crop:o,at:f,focus:c.focus},f.w,f.h),g=ea(u,c,t,n);return{coloring:i,figure:ss(is(h,d)),fill:ss(is(g,r)),focus:c.focus}}function aE(e,t,n,r){let i=Me(t),s=Me(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 uE(e,t,n){let r=Me(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 fm(e,t,n,r,i,s,o,a="tone"){let{box:u,clear:c,ink:l}=e,f=am(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:$m(u.w,u.h,r,i,h,o?.at??5,!1,h>100?Math.round(f.focus*100):-1),focus:f.focus},p=a==="original"?ra(t,e.peak):n.opacity,b=o?.opacity??p;return{image:a==="original"?uE(Ic(Hc(e.image,g,r,i),s),t.background,b):aE(ss(is(ea(l,g,r,i),s)),t.background,n.color,b),fill:d,opacity:p}}function Re(e){return D(e,"ttheme","backgrounds")}function Nc(e){return D(e,eE)}function zn(e){try{return ta(e,"utf8")}catch{return}}function qn(e){try{return z1(e)}catch{return[]}}function ct(e){let t=zn(Nc(e));if(t===void 0)return cE(e);let n=JSON.parse(t);if(n.version!==Sc)throw Error(`${Nc(e)} is version ${n.version} — this ttheme reads version ${Sc}`);return n}function Yn(e){return e.coloring??"tone"}function Ac(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 Es(e){return{hue:{color:e.backdrop.color,opacity:e.backdrop.opacity},colors:Ac(e)}}function vs(e){return e.tone===void 0&&Yn(e)==="tone"}function Zg(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function dm(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${Zg(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?Zg(i):"-"}`,...i.from?[i.from]:[]].join(" ")),...t.pictures.filter((i)=>Yn(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 hm(e){let t=Re(e);for(let[n,r]of Object.entries(ct(t).palettes)){let i=D(t,`${bn(n)}.conf`),s=dm(t,r);if(zn(i)!==s)Z(i,s)}}function hi(e,t,n){Z(Nc(e),`${JSON.stringify(t,null,2)}
313
+ `);for(let r of n){let i=t.palettes[r],s=D(e,`${bn(r)}.conf`);if(i)Z(s,dm(e,i));else fi(s,{force:!0})}}function gm(e,t){return qn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function xc(e,t){for(let n of gm(e,t))fi(D(e,n),{force:!0})}function mm(e,t){xc(e,t.stem);for(let n of[t.original,t.cut])if(n)fi(D(e,n),{force:!0})}function Xg(e,t,n,r){let i=im(/^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(na,c)}:{}}}function Dg(e,t){if(Rc(e))rm(e,t)}function cE(e){let t={version:Sc,palettes:{}};if(!Rc(e))return t;let n=qn(D(e,na)),r=qn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=D(e,D1);for(let s of new Set([...r,...qn(i)])){let o=[],a=Xg(s,zn(D(e,`${s}.conf`)),n);if(a)Dg(D(e,`${s}.tune.conf`),D(e,`${a.stem}.tune.conf`)),Dg(D(e,`${s}.off.conf`),D(e,`${a.stem}.off.conf`)),o.push(a);for(let u of qn(D(i,s))){let c=D(i,s,u),l=Xg(s,zn(D(c,".conf")),n,u);if(!l)continue;for(let f of qn(c)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${s}${f}`;if(f!==".conf")rm(D(c,f),D(e,d))}fi(c,{recursive:!0}),o.push(l)}if(qn(D(i,s)).length===0)fi(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(qn(i).length===0)fi(i,{recursive:!0,force:!0});return hi(e,t,Object.keys(t.palettes)),t}function em(e,t,n){return t.startsWith("~/")?D(n,t.slice(2)):Y1(t)?t:D(e,t)}function pm(e,t,n){let r=new Map,i=(a,u)=>{let c=zn(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(em(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,`${bn(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:em(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 ia(e,t,n){let r=Re(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);mm(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 hi(r,i,[t]),{key:a.key,left:s.pictures.length}}function bm(e,t,n,r){let i=n.coloring==="original"?Gn(n.figure):as(n.figure,r),s=n.coloring==="original"?Gn(n.fill):as(n.fill,r),o=`${bn(e)}.${nm("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 wm(e,t,n){return n.coloring==="original"?{coloring:"original",opacity:ra(e,n.peak),peak:n.peak}:{coloring:"tone",opacity:t.opacity,tone:t.color}}function Pc(e,t){return D(na,`${bn(e)}-${t}`)}function Lc(e,t){return t.map(([n,r])=>{let i=D(e,n);return Z(i,r),i})}function sa(e,t,n,r,i,s,o,a="tone"){let u=Re(e),c=t.name,l=ft(i),f=ct(u),d=f.palettes[c]??{active:l,pictures:[]},h=Fc(s.width,s.height),g=lm(r,h.width,h.height,o,a),p=bm(c,l,g,n.color),b=Pc(c,l),m={key:l,stem:p.stem,fill:p.fill,...wm(t,n,g),blur:o,window:h,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${b}.${i.ext}`,...i.cut?{cut:`${b}.cut.png`}:{}},$=d.pictures.find((S)=>S.key===l);if($)mm(u,$);q1(D(u,na),{recursive:!0});let k=Lc(u,[...p.files,[m.original,i.bytes],...m.cut?[[m.cut,uc(os(r))]]:[]]);return d.pictures=$?d.pictures.map((S)=>S===$?m:S):[...d.pictures,m],d.active=l,f.palettes[c]=d,hi(u,f,[c]),[...k,D(u,`${bn(c)}.conf`)]}function gi(e,t,n){let r=Re(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,hi(r,i,[t]);return{at:o+1,of:s.pictures.length}}function Tt(e,t){let n=ct(Re(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var Oc="top-right";function $m(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),p=u(l*(r-h)/2);if(a>=0){if(d>n)g=u((n-d)/2);if(h>r)p=Math.max(r-h,Math.min(0,u(r/2)-u(a*h/100)))}return{x:g,y:p,w:d,h}}function Cc(e,t){let n=zn(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=im(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!==Oc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Ms(e,t,n,r,i){let s=n.size??"fill",o=n.position??Oc,a=n.opacity??t.opacity;if(s==="fill"&&o===Oc&&a===t.opacity)return;let u=$t.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(vs(t))throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=kr(new Uint8Array(ta(c))),{width:p,height:b}=d?Do:g,m=d?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,$=$m(g.width,g.height,p,b,s,u,!1,m);l=D(e,`${t.stem}@${s}-${o}${d?`-${p}x${b}`:""}.png`);let S={crop:{x:0,y:0,w:g.width,h:g.height},at:$,focus:m};Z(l,t.tone?as(ss(ea(os(g),S,p,b)),t.tone):Gn(Hc(g,S,p,b))),f=d}let h=D(e,`${t.stem}.tune.conf`);return Z(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 km(e){let t=new Map;for(let[n,r]of Object.entries(ct(Re(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 lE(e){try{let t=Wn(new Uint8Array(ta(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function oa(e,t,n,r,i,s,o,a,u,c=Yn(n)){let l=Re(e),f=n.window??lE(D(l,n.fill))??Do,d=lm(r,f.width,f.height,s,c),h=bm(t,n.key,d,i.hue.color),g={...n,stem:h.stem,fill:h.fill,...wm(i.colors,i.hue,d),blur:s,window:f,...u?{cut:`${Pc(t,n.key)}.cut.png`}:{}};if(d.coloring==="original")delete g.tone;else delete g.peak;if(u)Z(D(l,`${Pc(t,n.key)}.cut.png`),uc(os(r)));if(h.stem===n.stem)return g;Lc(l,h.files);let p=Cc(l,n);Ms(l,g,Yn(n)===c?p:{...p,opacity:void 0},o,a);let b=D(l,`${n.stem}.off.conf`);if(Rc(b))B1(b,D(l,`${g.stem}.off.conf`));return g}function _c(e,t){let n=Re(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;hi(n,r,[...i]);for(let o of s)xc(n,o)}function ym(e,t,n){return e.replace(/^background-image-opacity = (\S+)$/m,(r,i)=>Number(i)===t?`background-image-opacity = ${n}`:r)}function Em(e,t,n){let r=D(e,`${t.stem}.tune.conf`),i=zn(r);if(i!==void 0)Z(r,ym(i,t.opacity,n));return{...t,opacity:n}}function fE(e,t,n,r){if(n.tone===r.color)return Em(e,n,r.opacity);let i=gm(e,n.stem).filter((a)=>a.endsWith(".png")).map((a)=>{let u=new Uint8Array(ta(D(e,a)));return[a,ug(u,r.color)??as(os(kr(u)),r.color)]}),s=(a)=>i.find(([u])=>u===a)?.[1]??new Uint8Array,o=`${bn(t)}.${nm("sha1").update(n.key).update(s(`${n.stem}.png`)).update(s(n.fill)).digest("hex").slice(0,8)}`;Lc(e,i.map(([a,u])=>[o+a.slice(n.stem.length),u]));for(let a of["tune","off"]){let u=zn(D(e,`${n.stem}.${a}.conf`));if(u!==void 0)Z(D(e,`${o}.${a}.conf`),ym(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 tm(e,t){if(Yn(e)==="original")return e.peak!==void 0&&ra(t.colors,e.peak)!==e.opacity;return e.tone!==void 0&&(e.tone!==t.hue.color||e.opacity!==t.hue.opacity)}function vm(e,t){let n=Re(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)=>tm(c,u)))continue;a.pictures=a.pictures.map((c)=>{if(!tm(c,u))return c;let l=Yn(c)==="original"?Em(n,c,ra(u.colors,c.peak)):fE(n,o,c,u.hue);if(l.stem!==c.stem)s.push(c.stem);return l}),i.push(o)}if(i.length>0){hi(n,r,i);for(let o of s)xc(n,o)}return i}function Ut(e){let{slot:t,color:n,opacity:r}=di({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:An(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function $n(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 dE=6,hE=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function aa(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,...hE]){let o=t(s);if(i.length===dE||!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 Ss(){return{version:ot.version,gate:pt,placement:wn,palettes:[]}}function gE(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Ss(),palettes:e.map(Ut)}}var Gc={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(gE(e),null,2)}
316
+ `}]}};import{existsSync as yE,readdirSync as Om,readFileSync as EE}from"node:fs";import{basename as Rm,join as Is}from"node:path";import{existsSync as mE,readFileSync as Mm}from"node:fs";import{homedir as Sm}from"node:os";import{isAbsolute as Im,join as Ir,resolve as pE}from"node:path";var ee="official",tn="ttheme-market.json",mi="ttheme-market",bE=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,wE=/^[\w.-]{1,100}$/,$E=/^\w[\w.+/-]{0,199}$/;function Vn(e){return Ir(e,"ttheme","installed.json")}function it(e){return e??[ee]}function pi(e){try{let{markets:t}=JSON.parse(Mm(Vn(e),"utf8"));return it(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[ee]}}function Ae(e){return Im(e)}function kt(e){return e!==ee&&!Ae(e)}function Qn(e){let t=e.indexOf("#");return kt(e)&&t>=0?e.slice(0,t):e}function Wc(e){let t=e.indexOf("#");return kt(e)&&t>=0?e.slice(t+1):void 0}function bi(e,t){return Qn(e)===Qn(t)}function Zn(e,t){return!Ae(e)&&(t?.[e]??e===ee)}function kE(e){return!$E.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function Xn(e,t=process.cwd()){if(e===ee)return ee;if(e==="~"||e.startsWith("~/"))return Ir(Sm(),e.slice(1));if(e.startsWith(".")||Im(e))return pE(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!bE.test(s)||!o||!wE.test(o)||a.length>0||i.length>0||r!==void 0&&kE(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 Nm(e){let t=Wc(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${Qn(e)}/${t}/${tn}`}function Pm(e){return e.slice(0,e.indexOf("/"))}function Uc(e){return Ir(e,"ttheme","markets")}function jt(e,t){return Ir(Uc(e),`${Qn(t).replace("/","--")}.json`)}function ua(e){return Ir(e,"ttheme","market")}function jc(e,t){return Ir(ua(e),t)}function Kc(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return en(`${e}@${t}/x`)}function yt({owner:e,name:t}){return`${e}@${t}`}function nn(e){let t=Ir(e,tn);if(!mE(t))throw Error(`${e} has no ${tn} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Mm(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=Kc(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(!Ae(e))return`github.com/${e}`;let t=Sm();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var kn="tt1:",Fm=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function Nr(e,t=!0){return pi(e).filter(Ae).flatMap((n)=>{try{let r=nn(n);return[{dir:n,...r,id:yt(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
+ `);return[]}})}function ca(e){return Is(e,"palettes")}function Dn(e){let t=ca(e);if(!yE(t))return[];let n=[],r=[];for(let i of Om(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of Om(Is(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:Is(t,i.name,s),slug:Rm(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Is(t,i.name),slug:Rm(i.name,".toml")})}return[...n,...r]}function Ns(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:ys(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function Jc(e,t){let n=ve(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=Nr(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=li(t);return Dn(r.dir).find((s)=>s.slug===i)?.path??Is(ca(r.dir),`${i}.toml`)}function vE(e,t){let n=new Map;for(let i of t)if(i.group!==ws&&!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&&!ve(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function Et(e,t,n){let r=li(e),{native:i,...s}=vc(`${r}.toml`,t,vE(r,n)),o=ve(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function er(e,t,n,r=!0){let i=new Map;return Dn(e).flatMap((s)=>{try{let o=Ns(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Ut(Et(`${t}/${s.slug}`,EE(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 la(e,t,n=!0){return Nr(e,n).flatMap(({dir:r,id:i})=>er(r,i,t,n))}function Bc(e,t=e.name,n){return{name:t,...e.base?{base:e.base}:{},...e.group!==ws?{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 qe=(e)=>JSON.stringify(e);function Hm(e){return["[[picture]]",`site = ${qe(e.site)}`,`id = ${e.id}`,...e.size===void 0?[]:[`size = ${typeof e.size==="number"?e.size:qe(e.size)}`],...e.position===void 0?[]:[`position = ${qe(e.position)}`],...e.opacity===void 0?[]:[`opacity = ${e.opacity}`]]}function Tm(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
319
319
  `)}${t.map((n)=>`
320
- ${gm(n).join(`
320
+ ${Hm(n).join(`
321
321
  `)}
322
- `).join("")}`}function Ac(e){let t=["[meta]",`name = ${qe(si(e.name))}`,...e.base?[`base = ${qe(e.base)}`]:[],...e.group?[`group = ${qe(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${qe(e.ansiSource)}`]:[],...e.booru?[`booru = ${qe(e.booru)}`]:[],`signature = [${e.signature.map(qe).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(qe).join(", ")}]`)]:[],"","[colors]",`background = ${qe(e.background)}`,`foreground = ${qe(e.foreground)}`,`cursor = ${qe(e.cursor)}`,`selection_background = ${qe(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${qe(n)},`),"",...e.ansi.slice(8).map((n)=>` ${qe(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(qe).join(", ")}]`,`reason = ${qe(e.reason??"")}`);for(let n of e.pictures??[])t.push("",...gm(n));return`${t.join(`
322
+ `).join("")}`}function qc(e){let t=["[meta]",`name = ${qe(li(e.name))}`,...e.base?[`base = ${qe(e.base)}`]:[],...e.group?[`group = ${qe(e.group)}`]:[],...e.ansiSource?[`ansi_source = ${qe(e.ansiSource)}`]:[],...e.booru?[`booru = ${qe(e.booru)}`]:[],`signature = [${e.signature.map(qe).join(", ")}]`,...e.booruSites?["","[meta.booru_sites]",...Object.entries(e.booruSites).map(([n,r])=>`${n} = [${r.map(qe).join(", ")}]`)]:[],"","[colors]",`background = ${qe(e.background)}`,`foreground = ${qe(e.foreground)}`,`cursor = ${qe(e.cursor)}`,`selection_background = ${qe(e.selection)}`,"ansi = [",...e.ansi.slice(0,8).map((n)=>` ${qe(n)},`),"",...e.ansi.slice(8).map((n)=>` ${qe(n)},`),"]"];if(e.waive&&e.waive.length>0)t.push("","[contrast]",`waive = [${e.waive.map(qe).join(", ")}]`,`reason = ${qe(e.reason??"")}`);for(let n of e.pictures??[])t.push("",...Hm(n));return`${t.join(`
323
323
  `)}
324
- `}class pm{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 bm{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 wm(e){let t=new pm;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(hm.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<<xu.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:$t.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${$n}${t.done()}`}function $m(e){if(!e.startsWith($n))throw Error(`a share code starts with ${$n}`);let t=e.slice($n.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 bm(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(($)=>hm[$]??`slot${$}`),l=n.str(),f=n.str(),d=n.str(),h=n.str(),g=n.u16(),p=n.str(),b=xu.filter(($,k)=>g&1<<k),m=Array.from({length:n.u8()},()=>{let $=X[n.u8()]?.key??"unknown",k=n.u32(),M=n.u16(),w=n.u8(),S=n.u16();return{site:$,id:k,...M===1?{size:"fill"}:M>1?{size:M}:{},...w>0?{position:$t[w-1]??"unknown"}:{},...S>0?{opacity:(S-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Yt))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,...b.length>0?{waive:b,reason:p}:{},...m.length>0?{pictures:m}:{}}}function Lc(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function xc(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,()=>qe(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}${qe(c)}`),e.slice(0,n)+s+e.slice(r))}function km(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(qe).join(", ")}]`)}function vs(e){let t=An(wn(e)),n=new Set(e.waived??[]),r=Math.max(...pt.map((i)=>i.label.length));return pt.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 vm="https://kecan0406.github.io/ttheme/manifest.json",nE=20000;function Kt(e){return Em(e,"ttheme","catalog.json")}function oa(e,t){Z(Kt(e),`${JSON.stringify(t,null,2)}
325
- `)}function We(e,t=!0){let n=fi(e),r=Kt(e),i=ks();if(n.includes(ee)){if(!ym(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=rn(Cc(r,"utf8"))}let s=n.filter(kt).flatMap((o)=>rE(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function Dn(e,t){return Gc(Cc(jt(e,t),"utf8"))}function hi(e,t){return yt({owner:lm(e),name:t.name})}function rE(e,t,n){let r=jt(e,t);if(!ym(r))return[];try{let i=Dn(e,t);return aa(i,hi(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
- `);return[]}}function Gc(e){let t=rn(e),n=Rc(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>ve(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 aa(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function rn(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=Sm(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function Sm(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=en(e.name)??(e.base===void 0?void 0:en(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Yt(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"?ws(n):"has a field that is not text";if(r)return r}return}function Mm(e){return Em(e,"ttheme","kept.json")}function ua(e,t){Z(Mm(e),`${JSON.stringify({palettes:t},null,2)}
327
- `)}function kn(e){try{let{palettes:t}=JSON.parse(Cc(Mm(e),"utf8"));return Array.isArray(t)?t.filter((n)=>Sm(n)===void 0):[]}catch{return[]}}function je(e,t,n=!0){let r=[...t.palettes,...sa(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...kn(e).filter((s)=>!i.has(s.name))]}}function yn(e){return je(e,We(e))}class ca extends Error{}class la extends Error{}async function Ss(e,t,n=nE,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 ca(`nothing at ${e}`);if(i.status===403||i.status===429)throw new la(`${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 Ms(e){let t=new Set(e.waived??[]),n=e.gate??An(wn(e));return pt.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 Ir(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${_c(e,[t])}`);return n}function _c(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 Im(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 Nm(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 Pm(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as Tv}from"node:child_process";import{existsSync as Rl,mkdirSync as Dp,readdirSync as Av,readFileSync as Tl,rmSync as eb}from"node:fs";import{basename as Lv,join as Fr,relative as xv}from"node:path";import{existsSync as El,readFileSync as Tp,rmSync as vl}from"node:fs";import{homedir as on}from"node:os";import{join as Ia}from"node:path";var iE=["black","red","green","yellow","blue","magenta","cyan","white"];function Om(e,t){return[e,...iE.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
- `)}var Wc={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...er(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}'`,"",Om("[colors.normal]",e.ansi.slice(0,8)),Om("[colors.bright]",e.ansi.slice(8,16))].join(`
329
- `);return[{path:`alacritty/themes/${z(e.name)}.toml`,content:t}]}};var Uc={id:"ghostty",emit(e){let t=[...er(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
330
- `);return[{path:`ghostty/themes/${z(e.name)}`,content:t}]}};function tr(e){let[t,n,r]=Pe(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function Fm(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,tr(t)])),"Background Color":tr(e.background),"Bold Color":tr(e.foreground),"Cursor Color":tr(e.cursor),"Cursor Text Color":tr(e.background),"Foreground Color":tr(e.foreground),"Selected Text Color":tr(e.foreground),"Selection Color":tr(e.selectionBackground)}}function sE(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Rm(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:z(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...sE(t.get(o.name)),...Fm(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
331
- `}function oE(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 jc={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(Fm(e)).map(([n,r])=>oE(n,r)),"</dict>","</plist>",""].join(`
333
- `);return[{path:`iterm2/${z(e.name)}.itermcolors`,content:t}]}};var Kc={id:"kitty",emit(e){let t=[...er(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/${z(e.name)}.conf`,content:t}]}};function Hm(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 En(e,t){return[`[${e}]`,`Color=${Pe(t).join(",")}`,""]}function aE(e){let t=(n)=>rt(n,e.background,0.5);return[...er(e),"",...En("Background",e.background),...En("BackgroundFaint",e.background),...En("BackgroundIntense",e.background),...e.ansi.slice(0,8).flatMap((n,r)=>[...En(`Color${r}`,n),...En(`Color${r}Faint`,t(n)),...En(`Color${r}Intense`,e.ansi[r+8])]),...En("Foreground",e.foreground),...En("ForegroundFaint",t(e.foreground)),...En("ForegroundIntense",e.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${e.name}`,"Opacity=1","Wallpaper=",""].join(`
336
- `)}var Jc={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(e){return[{path:`konsole/${z(e.name)}.colorscheme`,content:aE(e)}]}};var Tm=44,Tt=[{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 fa(e){let t=Tt.length;return Tt[(e%t+t)%t]}function Am(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 uE,writeSync as cE}from"node:fs";import{ReadStream as lE}from"node:tty";var gi=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function At(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function Bc(e,t){return`\x1B]${gi[e]};${t}\x1B\\`}function qc(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":Bc(r,n)).join("")}function fE(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function dE(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 hE(e){return`#${e.slice(e.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function Lm(e,t=[...e.keys()],n=!1){return t.map((r)=>{let i=e.get(r);return i?`\x1B]${r};${n?hE(i):i}\x1B\\`:fE(r)}).join("")}function xm(e,t){return`\x1B]50;ColorScheme=${e};UseCustomCursorColor=true;customCursorColor=${t}\x07`}function gE(e=gi){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function mE(e){return e.includes("\x1B[0n")}async function Cm(e=gi){let t,n;try{t=uE("/dev/tty","r+"),n=new lE(t),n.setRawMode(!0)}catch{return new Map}try{cE(t,gE(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),mE(r))clearTimeout(s),i()})}),dE(r)}finally{n.setRawMode(!1),n.destroy()}}function Nr(e){if(e.TERM_PROGRAM==="WarpTerminal")return"warp";if(e.GHOSTTY_RESOURCES_DIR||e.TERM_PROGRAM==="ghostty")return"ghostty";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.ALACRITTY_WINDOW_ID)return"alacritty";if(e.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 nr={ghostty:{links:!0,pictures:!0,bands:!1,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,paints:!0},warp:{links:!1,pictures:!1,bands:!1,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,paints:!0}};function Gm(e){return nr[Nr(e)].links}function _m(e){return nr[Nr(e)].pictures&&!e.TMUX}function Wm(e){return nr[Nr(e)].bands}var mi="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function rr(e,t){let n=Nr(e),r=nr[n];if(!t||At(e)||e.TMUX||!r.paints)return;let i=r.repaint??gi.map((o,a)=>a),s=gi.filter((o,a)=>i.includes(a));return{slots:i,paint:(o)=>qc(o,i),wear:(o,a)=>!r.schemes?qc(o):a.includes(n)?xm(z(o.name),o.cursor):void 0,saved:()=>Cm(s),restore:(o)=>Lm(o,s,r.hex===!0)}}var vt=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var pE=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Ns=[{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:"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:vt,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, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Is(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function zc(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var bE=[["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 Ps(e,t=!1){let n=Ns.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=pE.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>","",ot.description,"","Start here",...zc(o.map((u)=>[Is(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)=>Is(o).length));return["Usage: ttheme <command>","",ot.description,...r.flatMap(({section:o,title:a})=>["",a,...zc(n.filter((u)=>u.section===o).map((u)=>[Is(u),u.about]),s)]),"","Examples",...zc(bE),"",...i].join(`
338
- `)}import{readFileSync as wE}from"node:fs";import{join as $E}from"node:path";var Yc="# ttheme begin",Qc="# ttheme end",pi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function ir(e,t){let n=`${Yc}
324
+ `}class Am{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 xm{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 Lm(e){let t=new Am;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(Fm.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<<Ku.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:$t.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${kn}${t.done()}`}function Cm(e){if(!e.startsWith(kn))throw Error(`a share code starts with ${kn}`);let t=e.slice(kn.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 xm(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(($)=>Fm[$]??`slot${$}`),l=n.str(),f=n.str(),d=n.str(),h=n.str(),g=n.u16(),p=n.str(),b=Ku.filter(($,k)=>g&1<<k),m=Array.from({length:n.u8()},()=>{let $=X[n.u8()]?.key??"unknown",k=n.u32(),S=n.u16(),w=n.u8(),M=n.u16();return{site:$,id:k,...S===1?{size:"fill"}:S>1?{size:S}:{},...w>0?{position:$t[w-1]??"unknown"}:{},...M>0?{opacity:(M-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Yt))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,...b.length>0?{waive:b,reason:p}:{},...m.length>0?{pictures:m}:{}}}function zc(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function Yc(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,()=>qe(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}${qe(c)}`),e.slice(0,n)+s+e.slice(r))}function _m(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(qe).join(", ")}]`)}function Ps(e){let t=An($n(e)),n=new Set(e.waived??[]),r=Math.max(...pt.map((i)=>i.label.length));return pt.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 Um="https://kecan0406.github.io/ttheme/manifest.json",ME=20000;function Kt(e){return Wm(e,"ttheme","catalog.json")}function fa(e,t){Z(Kt(e),`${JSON.stringify(t,null,2)}
325
+ `)}function We(e,t=!0){let n=pi(e),r=Kt(e),i=Ss();if(n.includes(ee)){if(!Gm(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=rn(Qc(r,"utf8"))}let s=n.filter(kt).flatMap((o)=>SE(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function tr(e,t){return Vc(Qc(jt(e,t),"utf8"))}function wi(e,t){return yt({owner:Pm(e),name:t.name})}function SE(e,t,n){let r=jt(e,t);if(!Gm(r))return[];try{let i=tr(e,t);return da(i,wi(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
+ `);return[]}}function Vc(e){let t=rn(e),n=Kc(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>ve(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 da(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function rn(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=jm(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function jm(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=en(e.name)??(e.base===void 0?void 0:en(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Yt(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"?ys(n):"has a field that is not text";if(r)return r}return}function Km(e){return Wm(e,"ttheme","kept.json")}function ha(e,t){Z(Km(e),`${JSON.stringify({palettes:t},null,2)}
327
+ `)}function yn(e){try{let{palettes:t}=JSON.parse(Qc(Km(e),"utf8"));return Array.isArray(t)?t.filter((n)=>jm(n)===void 0):[]}catch{return[]}}function je(e,t,n=!0){let r=[...t.palettes,...la(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...yn(e).filter((s)=>!i.has(s.name))]}}function sn(e){return je(e,We(e))}class ga extends Error{}class ma extends Error{}async function Os(e,t,n=ME,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 ga(`nothing at ${e}`);if(i.status===403||i.status===429)throw new ma(`${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 Rs(e){let t=new Set(e.waived??[]),n=e.gate??An($n(e));return pt.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 Pr(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${Zc(e,[t])}`);return n}function Zc(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 Jm(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 Bm(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 qm(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as Xv}from"node:child_process";import{existsSync as Kl,mkdirSync as wb,readdirSync as Dv,readFileSync as Bl,rmSync as $b}from"node:fs";import{basename as eM,join as xr,relative as tM}from"node:path";import{existsSync as Al,readFileSync as Dp,rmSync as xl}from"node:fs";import{homedir as an}from"node:os";import{join as Ha}from"node:path";var IE=["black","red","green","yellow","blue","magenta","cyan","white"];function zm(e,t){return[e,...IE.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
+ `)}var Xc={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...nr(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}'`,"",zm("[colors.normal]",e.ansi.slice(0,8)),zm("[colors.bright]",e.ansi.slice(8,16))].join(`
329
+ `);return[{path:`alacritty/themes/${z(e.name)}.toml`,content:t}]}};var Dc={id:"ghostty",emit(e){let t=[...nr(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${e.ghostty.iconGhost}`,`macos-icon-screen-color = ${e.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
330
+ `);return[{path:`ghostty/themes/${z(e.name)}`,content:t}]}};function rr(e){let[t,n,r]=Me(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function Ym(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,rr(t)])),"Background Color":rr(e.background),"Bold Color":rr(e.foreground),"Cursor Color":rr(e.cursor),"Cursor Text Color":rr(e.background),"Foreground Color":rr(e.foreground),"Selected Text Color":rr(e.foreground),"Selection Color":rr(e.selectionBackground)}}function NE(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function Qm(e,t,n,r){let i=(o,a)=>({Name:`ttheme · ${a}`,Guid:z(a),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...NE(t.get(o.name)),...Ym(o)}),s=[...n?[i(n,"default")]:[],...e.map((o)=>i(o,o.name))];return`${JSON.stringify({Profiles:s},null,2)}
331
+ `}function PE(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 el={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(Ym(e)).map(([n,r])=>PE(n,r)),"</dict>","</plist>",""].join(`
333
+ `);return[{path:`iterm2/${z(e.name)}.itermcolors`,content:t}]}};var tl={id:"kitty",emit(e){let t=[...nr(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/${z(e.name)}.conf`,content:t}]}};function Vm(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 En(e,t){return[`[${e}]`,`Color=${Me(t).join(",")}`,""]}function OE(e){let t=(n)=>rt(n,e.background,0.5);return[...nr(e),"",...En("Background",e.background),...En("BackgroundFaint",e.background),...En("BackgroundIntense",e.background),...e.ansi.slice(0,8).flatMap((n,r)=>[...En(`Color${r}`,n),...En(`Color${r}Faint`,t(n)),...En(`Color${r}Intense`,e.ansi[r+8])]),...En("Foreground",e.foreground),...En("ForegroundFaint",t(e.foreground)),...En("ForegroundIntense",e.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${e.name}`,"Opacity=1","Wallpaper=",""].join(`
336
+ `)}var nl={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(e){return[{path:`konsole/${z(e.name)}.colorscheme`,content:OE(e)}]}};var Zm=44,At=[{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=At.length;return At[(e%t+t)%t]}function Xm(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 RE,writeSync as FE}from"node:fs";import{ReadStream as HE}from"node:tty";var $i=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function xt(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function rl(e,t){return`\x1B]${$i[e]};${t}\x1B\\`}function il(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":rl(r,n)).join("")}function TE(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function AE(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 xE(e){return`#${e.slice(e.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function Dm(e,t=[...e.keys()],n=!1){return t.map((r)=>{let i=e.get(r);return i?`\x1B]${r};${n?xE(i):i}\x1B\\`:TE(r)}).join("")}function ep(e,t){return`\x1B]50;ColorScheme=${e};UseCustomCursorColor=true;customCursorColor=${t}\x07`}function LE(e=$i){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function CE(e){return e.includes("\x1B[0n")}async function tp(e=$i){let t,n;try{t=RE("/dev/tty","r+"),n=new HE(t),n.setRawMode(!0)}catch{return new Map}try{FE(t,LE(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),CE(r))clearTimeout(s),i()})}),AE(r)}finally{n.setRawMode(!1),n.destroy()}}function Or(e){if(e.TERM_PROGRAM==="WarpTerminal")return"warp";if(e.GHOSTTY_RESOURCES_DIR||e.TERM_PROGRAM==="ghostty")return"ghostty";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.ALACRITTY_WINDOW_ID)return"alacritty";if(e.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 ir={ghostty:{links:!0,pictures:!0,bands:!1,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,paints:!0},warp:{links:!1,pictures:!1,bands:!1,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,paints:!0}};function np(e){return ir[Or(e)].links}function rp(e){return ir[Or(e)].pictures&&!e.TMUX}function ip(e){return ir[Or(e)].bands}var ki="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function sr(e,t){let n=Or(e),r=ir[n];if(!t||xt(e)||e.TMUX||!r.paints)return;let i=r.repaint??$i.map((o,a)=>a),s=$i.filter((o,a)=>i.includes(a));return{slots:i,paint:(o)=>il(o,i),wear:(o,a)=>!r.schemes?il(o):a.includes(n)?ep(z(o.name),o.cursor):void 0,saved:()=>tp(s),restore:(o)=>Dm(o,s,r.hex===!0)}}var vt=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var _E=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Hs=[{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:"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:vt,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:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function Fs(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function sl(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var GE=[["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 Ts(e,t=!1){let n=Hs.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=_E.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>","",ot.description,"","Start here",...sl(o.map((u)=>[Fs(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)=>Fs(o).length));return["Usage: ttheme <command>","",ot.description,...r.flatMap(({section:o,title:a})=>["",a,...sl(n.filter((u)=>u.section===o).map((u)=>[Fs(u),u.about]),s)]),"","Examples",...sl(GE),"",...i].join(`
338
+ `)}import{readFileSync as sp}from"node:fs";import{join as op}from"node:path";var ol="# ttheme begin",al="# ttheme end",yi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function or(e,t){let n=`${ol}
339
339
  ${t}
340
- ${Qc}
341
- `;if(pi.test(e))return e.replace(pi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
340
+ ${al}
341
+ `;if(yi.test(e))return e.replace(yi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
342
342
  `)}
343
- ${n}`}function sr(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 or(e,t){let n=e.replace(pi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Um(e){return`source ${e}/ttheme.zsh`}var kE="# ttheme settings — uncomment a line to change it; exported variables win over this file",bi={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_BG_BLUR:{doc:"# soften the background pictures behind the text: a blur radius in screen pixels, 0 keeps them sharp — changing it draws every picture again (default 0)",default:"0"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the posts tagged solo, the character alone, by danbooru or zerochan; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_MIN_SCORE:{doc:"# the lowest score find lists: off, or a number such as 5, 10, 25, 50 or 100 — danbooru, konachan and yande.re filter by it, zerochan keeps no score (default off)",default:"off"},TTHEME_FIND_MIN_SIZE:{doc:"# the shortest side a picture find lists must reach, in pixels: off, or a number such as 720, 1080, 1440, 1800 or 2560 (default off)",default:"off"},TTHEME_FIND_SITES:{doc:"# the sites find mixes in its all tab: any of danbooru, konachan, yande.re and zerochan (default all four)",default:"danbooru konachan yande.re zerochan"},TTHEME_FIND_HIDE:{doc:"# the kinds of picture find leaves out by tag: comic, monochrome, sketch, chibi, or none to keep them all (default none)",default:"none"},TTHEME_FIND_HIDE_TAGS:{doc:'# more tags find leaves out, spaced — e.g. "cosplay multiple_girls" (default none)',default:""},TTHEME_FIND_PNG:{doc:"# on lists PNG originals only — a zerochan post counts only where danbooru holds the same file (default off)",default:"off"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://danbooru.donmai.us" (default none)',default:""}};function Vc(e){return bi[e]?.default}function Zc(e,t){let n=`: \${${e}:=${t}}`;return Vc(e)===t?`# ${n}`:n}function jm(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function yE(e,t){if(jm(t).test(e))return e;let n=bi[t];return`${e.replace(/\n*$/,`
343
+ ${n}`}function ar(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 ur(e,t){let n=e.replace(yi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function ap(e){return`source ${e}/ttheme.zsh`}var WE="# ttheme settings — uncomment a line to change it; exported variables win over this file",Rr={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_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 ul(e){return Rr[e]?.default}function cl(e,t){let n=`: \${${e}:=${t}}`;return ul(e)===t?`# ${n}`:n}function up(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function UE(e,t){if(up(t).test(e))return e;let n=Rr[t];return`${e.replace(/\n*$/,`
345
345
  `)}
346
346
  ${n.doc}
347
- ${Zc(t,n.default)}
348
- `}var Km=Object.keys(bi),EE=8;function wi(e){let t="";try{t=wE($E(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??bi.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(EE,Math.max(0,r)):0}function Xc(){let e=Object.entries(bi).map(([t,n])=>`${n.doc}
349
- ${Zc(t,n.default)}`);return`${[kE,...e].join(`
347
+ ${cl(t,n.default)}
348
+ `}var cp=Object.keys(Rr),jE=8;function Fr(e){let t="";try{t=sp(op(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??Rr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(jE,Math.max(0,r)):0}function ba(e){let t="";try{t=sp(op(e,"ttheme","config.zsh"),"utf8")}catch{}return(/^: \$\{TTHEME_BG_COLORS:=([^}\n]*)\}/m.exec(t)?.[1]??Rr.TTHEME_BG_COLORS.default).replace(/^(["'])(.*)\1$/,"$2")==="original"?"original":"tone"}function ll(){let e=Object.entries(Rr).map(([t,n])=>`${n.doc}
349
+ ${cl(t,n.default)}`);return`${[WE,...e].join(`
350
350
 
351
351
  `)}
352
- `}function Jm(e,t,n){let r=Zc(t,n),i=jm(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
352
+ `}function lp(e,t,n){let r=cl(t,n),i=up(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
353
353
  `)}
354
354
  ${r}
355
- `}function Bm(e){if(e==="")return Xc();return Object.keys(bi).reduce(yE,e)}var qm=/["$`\\]/;function vE(e){return e.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Dc(e,t,n=[],r={}){for(let l of e)for(let f of[l.name,l.group,l.native??"",...l.nativeNames??[],l.ansiSource])if(qm.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=Ns.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=${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(Ps(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(Ps(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Km.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Xc().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(vr(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&&!qm.test(l.booru)).map((l)=>s(l,vE(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${Tt.map((l)=>l.name).join(" ")})`,...Tt.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(nr).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,na(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 el={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Dc(e.map(Ut))}]}};var SE=["black","red","green","yellow","blue","magenta","cyan","white"];function zm(e,t){return[` ${e}:`,...SE.map((n,r)=>` ${n}: "${t[r]}"`)]}var tl={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Ye(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...zm("normal",e.ansi.slice(0,8)),...zm("bright",e.ansi.slice(8,16)),""].join(`
357
- `);return[{path:`warp/themes/${z(e.name)}.yaml`,content:t}]}};var Ym=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,nl={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${z(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 = ${Ym(e.ansi.slice(0,8))}`,`brights = ${Ym(e.ansi.slice(8,16))}`,""].join(`
358
- `);return[{path:`wezterm/colors/${z(e.name)}.toml`,content:t}]}},$i=(e)=>JSON.stringify(e);function Qm(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${$i(e.path)}`,`local COLORS = ${$i(e.colors)}`,`local BACKGROUNDS = ${$i(e.backgrounds)}`,`local STARTUP = ${e.startup?$i(z(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${$i(t.name)}] = ${$i(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(`
359
- `)}var Vm=["black","red","green","yellow","blue","purple","cyan","white"];function Zm(e){return{name:z(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Vm.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(Vm.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function rl(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:z(n)}]}:{},schemes:e.map(Zm)};return`${JSON.stringify(r,null,2)}
360
- `}var il={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${z(e.name)}.json`,content:`${JSON.stringify(Zm(e),null,2)}
361
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:rl(e)}]}};function er(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}import{execFileSync as ME}from"node:child_process";import{existsSync as Xm,readdirSync as IE,readFileSync as NE}from"node:fs";import{join as Dm}from"node:path";function Oe(e){return Xm(e)?NE(e,"utf8"):""}function De(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function da(e){return[...new Set(e.split(`
362
- `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function sn(e,t){let n=Oe(e),r=t(n);return r===n?[]:[{file:e,content:r}]}function Os(e){return process.env.XDG_DATA_HOME??Dm(e,".local","share")}function ha(e){return Xm(e)?IE(e).flatMap((t)=>t.startsWith(z(""))?[Dm(e,t)]:[]):[]}function sl(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 Pr(){return{platform:process.platform,env:process.env,run:(e,t)=>{try{return ME(e,[...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as ep}from"node:fs";import{join as ma}from"node:path";function PE(e){let t=e.replace(pi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var OE=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,tp=/^[ \t]*\[/m,np=/^[ \t]*import[ \t]*=/m,FE=/^[ \t]*general[ \t]*[.=]/m;function RE(e){return e?`[general]
363
- import = ["${e}"]`:""}function ol(e,t){let n=e.replace(pi,""),r=OE.exec(n);if(!r){let u=n.search(tp),c=u<0?n:n.slice(0,u);if(FE.test(n)||np.test(c))return;return ir(e,RE(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(tp);if(np.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
355
+ `}function fp(e){if(e==="")return ll();return Object.keys(Rr).reduce(UE,e)}var dp=/["$`\\]/;function KE(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(dp.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=Hs.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=${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(Ts(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(Ts(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${cp.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${ll().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(Sr(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&&!dp.test(l.booru)).map((l)=>s(l,KE(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${At.map((l)=>l.name).join(" ")})`,...At.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(ir).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,aa(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 dl={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:fl(e.map(Ut))}]}};var JE=["black","red","green","yellow","blue","magenta","cyan","white"];function hp(e,t){return[` ${e}:`,...JE.map((n,r)=>` ${n}: "${t[r]}"`)]}var hl={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){let t=[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Ye(e.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...hp("normal",e.ansi.slice(0,8)),...hp("bright",e.ansi.slice(8,16)),""].join(`
357
+ `);return[{path:`warp/themes/${z(e.name)}.yaml`,content:t}]}};var gp=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,gl={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${z(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 = ${gp(e.ansi.slice(0,8))}`,`brights = ${gp(e.ansi.slice(8,16))}`,""].join(`
358
+ `);return[{path:`wezterm/colors/${z(e.name)}.toml`,content:t}]}},Ei=(e)=>JSON.stringify(e);function mp(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Ei(e.path)}`,`local COLORS = ${Ei(e.colors)}`,`local BACKGROUNDS = ${Ei(e.backgrounds)}`,`local STARTUP = ${e.startup?Ei(z(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Ei(t.name)}] = ${Ei(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(`
359
+ `)}var pp=["black","red","green","yellow","blue","purple","cyan","white"];function bp(e){return{name:z(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(pp.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(pp.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function ml(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:z(n)}]}:{},schemes:e.map(bp)};return`${JSON.stringify(r,null,2)}
360
+ `}var pl={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${z(e.name)}.json`,content:`${JSON.stringify(bp(e),null,2)}
361
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:ml(e)}]}};function nr(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}import{execFileSync as BE}from"node:child_process";import{existsSync as wp,readdirSync as qE,readFileSync as zE}from"node:fs";import{join as $p}from"node:path";function Oe(e){return wp(e)?zE(e,"utf8"):""}function De(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function wa(e){return[...new Set(e.split(`
362
+ `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function on(e,t){let n=Oe(e),r=t(n);return r===n?[]:[{file:e,content:r}]}function As(e){return process.env.XDG_DATA_HOME??$p(e,".local","share")}function $a(e){return wp(e)?qE(e).flatMap((t)=>t.startsWith(z(""))?[$p(e,t)]:[]):[]}function bl(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 Hr(){return{platform:process.platform,env:process.env,run:(e,t)=>{try{return BE(e,[...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as kp}from"node:fs";import{join as ya}from"node:path";function YE(e){let t=e.replace(yi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var QE=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,yp=/^[ \t]*\[/m,Ep=/^[ \t]*import[ \t]*=/m,VE=/^[ \t]*general[ \t]*[.=]/m;function ZE(e){return e?`[general]
363
+ import = ["${e}"]`:""}function wl(e,t){let n=e.replace(yi,""),r=QE.exec(n);if(!r){let u=n.search(yp),c=u<0?n:n.slice(0,u);if(VE.test(n)||Ep.test(c))return;return or(e,ZE(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(yp);if(Ep.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
364
364
  `:"";return`${n.slice(0,i)}
365
- ${Yc}
366
- ${a}${Qc}${s}`}function ga(e){return ma(e,"alacritty","alacritty.toml")}function rp(e){return ma(e.configHome,"alacritty","themes")}function HE(e,t){return t?ma(e,"alacritty","themes",`${z(t)}.toml`):void 0}var al={id:"alacritty",name:"Alacritty",emitter:Wc,shelf:{from:"themes",dir:rp},offered:()=>!0,present:(e)=>ep(ma(e.configHome,"alacritty")),sync(e,t){t.themes(al);let n=ga(e.configHome),r=ol(Oe(n),HE(e.configHome,e.startup));if(r!==void 0)t.wire(n,r)},plan(e){let t=ga(e.configHome);return ol(Oe(t),void 0)!==void 0?[`Edit ${De(t,e.home)} — a ttheme block: general.import`]:[]},notes(e){let t=ga(e.configHome),n=Oe(t);return[...ep(t)&&ol(n,void 0)===void 0?[`${t} already imports files under [general] — ttheme left it alone; add ${rp(e)}/<palette>.toml to that import list yourself`]:[],...PE(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:sn(ga(e.configHome),sr),removals:[],touches:[]})};import{existsSync as TE}from"node:fs";import{join as ba}from"node:path";function AE(e,t,n=""){let r=[];if(!or(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!or(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${z(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
367
- `)}function pa(e){return ba(e,"ghostty","config")}function ip(e,t,n){return AE(ba(e.configHome,"ttheme"),t,n)}var ul={id:"ghostty",name:"Ghostty",emitter:Uc,shelf:{from:"themes",dir:(e)=>ba(e.configHome,"ghostty","themes")},offered:()=>!0,present:(e)=>TE(ba(e.configHome,"ghostty")),sync(e,t){t.themes(ul);let n=pa(e.configHome),r=Oe(n);t.wire(n,ir(r,ip(e,e.startup,r)))},plan(e){let t=pa(e.configHome);return[`Edit ${De(t,e.home)} — a ttheme block: ${da(ip(e,e.startup,Oe(t)))}`]},notes(e){let t=pa(e.configHome);return or(Oe(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:sn(pa(e.configHome),sr),removals:[],touches:[]})};import{existsSync as sp}from"node:fs";import{join as up}from"node:path";var cl="ttheme-default";function Fs(e){return up(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function op(e){let t=Te(e.configHome),n=new Map;for(let i of e.themes){let s=em(t,i.name,e.home);if(s)n.set(i.name,s)}let r=new Set(Xe(e.entries).map((i)=>i.name));return Rm(e.themes.filter((i)=>r.has(i.name)),n,e.themes.find((i)=>i.name===e.startup),e.state.itermBase)}function cp(e){return e.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function ap(e){return e.platform==="darwin"?e.run("defaults",["read",cp(e),"Default Bookmark Guid"])||void 0:void 0}var LE={key:"itermBase",profile:()=>"ttheme · default",base(e){let t=ap(e.host);return t&&!t.startsWith("ttheme-")?{...e.state,itermBase:t}:e.state},point(e,t){let n=ap(e.host),r=e.startup?t||n===cl?cl:void 0:n===cl?e.state.itermBase:void 0;if(!r||r===n)return;if(e.host.platform==="darwin")e.host.run("defaults",["write",cp(e.host),"Default Bookmark Guid","-string",r]);return{restart:Boolean(e.host.run("pgrep",["-x","iTerm2"]))}}},lp={id:"iterm2",name:"iTerm2",emitter:jc,bakes:!0,offered:(e,t)=>t.platform==="darwin",present:(e)=>sp(up(e.home,"Library","Application Support","iTerm2")),sync(e,t){t.write(Fs(e.home),op(e))},pictures(e,t){t.write(Fs(e.home),op(e))},plan:(e)=>[`Write ${De(Fs(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:sp(Fs(e.home))?[Fs(e.home)]:[],touches:[]}),defaults:LE};import{existsSync as xE}from"node:fs";import{join as $a}from"node:path";function fp(e,t,n=""){return[...e?[`include themes/${z(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!or(n,r.split(" ")[0]))].join(`
368
- `)}function wa(e){return $a(e,"kitty","kitty.conf")}function ll(e){return $a(e,"ttheme","kitty.py")}function dp(e){return $a(e.configHome,"kitty","themes")}var fl={id:"kitty",name:"kitty",emitter:Kc,shelf:{from:"themes",dir:dp},offered:()=>!0,present:(e)=>xE($a(e.configHome,"kitty")),sync(e,t){t.themes(fl),t.write(ll(e.configHome),Hm({themes:dp(e),backgrounds:Te(e.configHome)}));let n=wa(e.configHome),r=Oe(n);t.wire(n,ir(r,fp(e.startup,ll(e.configHome),r)))},plan(e){let t=wa(e.configHome),n=fp(e.startup,ll(e.configHome),Oe(t));return[`Edit ${De(t,e.home)} — a ttheme block: ${da(n)}`]},notes(e){let t=Oe(wa(e.configHome));return or(t,"window_logo_scale")||or(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:sn(wa(e.configHome),sr),removals:[],touches:[]})};import{existsSync as ya}from"node:fs";import{isAbsolute as CE,join as Hs}from"node:path";function ka(e){return Hs(Os(e),"konsole")}function Rs(e){return Hs(e,"konsolerc")}function hp(e){return`${z(e)}.profile`}function Ts(e){return`ttheme · ${e}`}function gp(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 dl(e){return new RegExp(String.raw`^\s*${e}\s*=`)}function ar(e,t,n){let r=e.split(`
369
- `),i=gp(r,t);return(i&&r.slice(i[0]+1,i[1]).find((o)=>dl(n).test(o)))?.replace(dl(n),"").trim()}function mp(e,t){let n=e.split(`
370
- `),r=gp(n,"Desktop Entry"),i=t===void 0?[]:[`DefaultProfile=${t}`];if(!r)return t===void 0?e:`${e===""?"":e.replace(/\n*$/,`
365
+ ${ol}
366
+ ${a}${al}${s}`}function ka(e){return ya(e,"alacritty","alacritty.toml")}function vp(e){return ya(e.configHome,"alacritty","themes")}function XE(e,t){return t?ya(e,"alacritty","themes",`${z(t)}.toml`):void 0}var $l={id:"alacritty",name:"Alacritty",emitter:Xc,shelf:{from:"themes",dir:vp},offered:()=>!0,present:(e)=>kp(ya(e.configHome,"alacritty")),sync(e,t){t.themes($l);let n=ka(e.configHome),r=wl(Oe(n),XE(e.configHome,e.startup));if(r!==void 0)t.wire(n,r)},plan(e){let t=ka(e.configHome);return wl(Oe(t),void 0)!==void 0?[`Edit ${De(t,e.home)} — a ttheme block: general.import`]:[]},notes(e){let t=ka(e.configHome),n=Oe(t);return[...kp(t)&&wl(n,void 0)===void 0?[`${t} already imports files under [general] — ttheme left it alone; add ${vp(e)}/<palette>.toml to that import list yourself`]:[],...YE(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:on(ka(e.configHome),ar),removals:[],touches:[]})};import{existsSync as DE}from"node:fs";import{join as va}from"node:path";function ev(e,t,n=""){let r=[];if(!ur(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!ur(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${z(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
367
+ `)}function Ea(e){return va(e,"ghostty","config")}function Mp(e,t,n){return ev(va(e.configHome,"ttheme"),t,n)}var kl={id:"ghostty",name:"Ghostty",emitter:Dc,shelf:{from:"themes",dir:(e)=>va(e.configHome,"ghostty","themes")},offered:()=>!0,present:(e)=>DE(va(e.configHome,"ghostty")),sync(e,t){t.themes(kl);let n=Ea(e.configHome),r=Oe(n);t.wire(n,or(r,Mp(e,e.startup,r)))},plan(e){let t=Ea(e.configHome);return[`Edit ${De(t,e.home)} — a ttheme block: ${wa(Mp(e,e.startup,Oe(t)))}`]},notes(e){let t=Ea(e.configHome);return ur(Oe(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:on(Ea(e.configHome),ar),removals:[],touches:[]})};import{existsSync as Sp}from"node:fs";import{join as Pp}from"node:path";var yl="ttheme-default";function xs(e){return Pp(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function Ip(e){let t=Re(e.configHome),n=new Map;for(let i of e.themes){let s=pm(t,i.name,e.home);if(s)n.set(i.name,s)}let r=new Set(Xe(e.entries).map((i)=>i.name));return Qm(e.themes.filter((i)=>r.has(i.name)),n,e.themes.find((i)=>i.name===e.startup),e.state.itermBase)}function Op(e){return e.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function Np(e){return e.platform==="darwin"?e.run("defaults",["read",Op(e),"Default Bookmark Guid"])||void 0:void 0}var tv={key:"itermBase",profile:()=>"ttheme · default",base(e){let t=Np(e.host);return t&&!t.startsWith("ttheme-")?{...e.state,itermBase:t}:e.state},point(e,t){let n=Np(e.host),r=e.startup?t||n===yl?yl:void 0:n===yl?e.state.itermBase:void 0;if(!r||r===n)return;if(e.host.platform==="darwin")e.host.run("defaults",["write",Op(e.host),"Default Bookmark Guid","-string",r]);return{restart:Boolean(e.host.run("pgrep",["-x","iTerm2"]))}}},Rp={id:"iterm2",name:"iTerm2",emitter:el,bakes:!0,offered:(e,t)=>t.platform==="darwin",present:(e)=>Sp(Pp(e.home,"Library","Application Support","iTerm2")),sync(e,t){t.write(xs(e.home),Ip(e))},pictures(e,t){t.write(xs(e.home),Ip(e))},plan:(e)=>[`Write ${De(xs(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:Sp(xs(e.home))?[xs(e.home)]:[],touches:[]}),defaults:tv};import{existsSync as nv}from"node:fs";import{join as Sa}from"node:path";function Fp(e,t,n=""){return[...e?[`include themes/${z(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!ur(n,r.split(" ")[0]))].join(`
368
+ `)}function Ma(e){return Sa(e,"kitty","kitty.conf")}function El(e){return Sa(e,"ttheme","kitty.py")}function Hp(e){return Sa(e.configHome,"kitty","themes")}var vl={id:"kitty",name:"kitty",emitter:tl,shelf:{from:"themes",dir:Hp},offered:()=>!0,present:(e)=>nv(Sa(e.configHome,"kitty")),sync(e,t){t.themes(vl),t.write(El(e.configHome),Vm({themes:Hp(e),backgrounds:Re(e.configHome)}));let n=Ma(e.configHome),r=Oe(n);t.wire(n,or(r,Fp(e.startup,El(e.configHome),r)))},plan(e){let t=Ma(e.configHome),n=Fp(e.startup,El(e.configHome),Oe(t));return[`Edit ${De(t,e.home)} — a ttheme block: ${wa(n)}`]},notes(e){let t=Oe(Ma(e.configHome));return ur(t,"window_logo_scale")||ur(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:on(Ma(e.configHome),ar),removals:[],touches:[]})};import{existsSync as Na}from"node:fs";import{isAbsolute as rv,join as Cs}from"node:path";function Ia(e){return Cs(As(e),"konsole")}function Ls(e){return Cs(e,"konsolerc")}function Tp(e){return`${z(e)}.profile`}function _s(e){return`ttheme · ${e}`}function Ap(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 Ml(e){return new RegExp(String.raw`^\s*${e}\s*=`)}function cr(e,t,n){let r=e.split(`
369
+ `),i=Ap(r,t);return(i&&r.slice(i[0]+1,i[1]).find((o)=>Ml(n).test(o)))?.replace(Ml(n),"").trim()}function xp(e,t){let n=e.split(`
370
+ `),r=Ap(n,"Desktop Entry"),i=t===void 0?[]:[`DefaultProfile=${t}`];if(!r)return t===void 0?e:`${e===""?"":e.replace(/\n*$/,`
371
371
 
372
372
  `)}[Desktop Entry]
373
373
  ${i[0]}
374
- `;let s=n.findIndex((a,u)=>u>r[0]&&u<r[1]&&dl("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(`
375
- `)}function GE(e){if(e&&Yt(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 pp(e,t){let n=t.endsWith(".profile")?t:`${t}.profile`;if(CE(n))return ya(n)?n:void 0;let r=n.includes("/")?n:Hs("konsole",n);return[Os(e.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((s)=>Hs(s,r)).find((s)=>ya(s))}function bp(e,t,n=0){let r=t&&t!=="FALLBACK/"&&n<8?pp(e,t):void 0;if(!r)return{};let i=Oe(r),s=bp(e,ar(i,"General","Parent"),n+1);return{scheme:ar(i,"Appearance","ColorScheme")||s.scheme,use:ar(i,"Cursor Options","UseCustomCursorColor")??s.use,cursor:ar(i,"Cursor Options","CustomCursorColor")??s.cursor}}function _E(e,t){let n=bp(e,t),r=n.use==="true"?GE(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function WE(e,t){return["[Appearance]",`ColorScheme=${z(e.name)}`,"","[Cursor Options]",`CustomCursorColor=${Pe(e.cursor).join(",")}`,`CustomCursorTextColor=${Pe(e.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${Ts(e.name)}`,`Parent=${t}`,""].join(`
376
- `)}function UE(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 hl=["--session","--print-reply","--reply-timeout=2000"];function jE(e){return[...(e.run("dbus-send",[...hl,"--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",[...hl,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function KE(e,{service:t,window:n},r){let i=(s,...o)=>e.run("dbus-send",[...hl,`--dest=${t}`,n,`org.kde.konsole.Window.${s}`,...o]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function JE(e,t){let n=pp(e,t);return n?ar(Oe(n),"General","Name"):void 0}function BE(e){return ar(Oe(Rs(e)),"Desktop Entry","DefaultProfile")}var qE={key:"konsoleBase",profile:Ts,base(e){let t=BE(e.configHome);return t&&!t.startsWith(z(""))?{...e.state,konsoleBase:t}:e.state},point(e,t){let n=Rs(e.configHome),r=Oe(n),i=ar(r,"Desktop Entry","DefaultProfile"),s=i?.startsWith(z(""))===!0,o=e.startup?t||s?hp(e.startup):void 0:s?e.state.konsoleBase??"":void 0;if(o===void 0||o===(i??"")&&!t)return;if(o!==(i??""))Ln(n,mp(r,o||void 0));let a=e.startup?Ts(e.startup):o?JE(e,o):void 0,u=jE(e.host),c=a!==void 0&&u.every((l)=>KE(e.host,l,a));return{restart:u.length>0&&!c}}},gl={id:"konsole",name:"Konsole",emitter:Jc,shelf:{from:"",dir:(e)=>ka(e.home)},offered:(e,t)=>t.platform!=="darwin"&&t.platform!=="win32",present:(e)=>ya(ka(e.home))||ya(Rs(e.configHome)),sync(e,t){t.themes(gl);let n=ka(e.home),r=e.state.konsoleBase??"FALLBACK/",i=new Set;for(let s of UE(e)){let o=Hs(n,hp(s.name));i.add(o),t.write(o,WE(s,r))}for(let s of ha(n))if(s.endsWith(".profile")&&!i.has(s))t.remove(s)},layer:(e)=>({TTHEME_KONSOLE_BASE:_E(e,e.state.konsoleBase)}),plan(e){return[`Write ${De(ka(e.home),e.home)}/${z("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...e.startup?[`Edit ${De(Rs(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 "${Ts(e.startup)}"`:`Konsole default "${Ts(e.startup)}", which follows \`ttheme default\``);return n},unwire(e,t){let n=Rs(e.configHome),r=Oe(n);return{edits:ar(r,"Desktop Entry","DefaultProfile")?.startsWith(z(""))?[{file:n,content:mp(r,t?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:qE};import{spawn as zE}from"node:child_process";import{existsSync as ki,mkdirSync as YE,readFileSync as wp,realpathSync as QE,rmSync as VE,writeFileSync as ZE}from"node:fs";import{dirname as $p,join as yi}from"node:path";function ml(e){return process.platform==="darwin"?yi(e,".warp","themes"):yi(Os(e),"warp-terminal","themes")}function pl(e,t){return process.platform==="darwin"?yi(e,".warp","settings.toml"):yi(t,"warp-terminal","settings.toml")}var kp='"dark"';function yp(e){return yi(e,"ttheme","warp.base")}var Ep="[appearance.themes]";function vp(e){let t=e.findIndex((r)=>r.trim()===Ep);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function Sp(e){let t=e.split(`
377
- `),n=vp(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function XE(e){return`{ custom = { name = "${e}", path = "${z(e)}.yaml" } }`}function Mp(e,t){let n=e.split(`
378
- `),r=vp(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
374
+ `;let s=n.findIndex((a,u)=>u>r[0]&&u<r[1]&&Ml("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(`
375
+ `)}function iv(e){if(e&&Yt(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 Lp(e,t){let n=t.endsWith(".profile")?t:`${t}.profile`;if(rv(n))return Na(n)?n:void 0;let r=n.includes("/")?n:Cs("konsole",n);return[As(e.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((s)=>Cs(s,r)).find((s)=>Na(s))}function Cp(e,t,n=0){let r=t&&t!=="FALLBACK/"&&n<8?Lp(e,t):void 0;if(!r)return{};let i=Oe(r),s=Cp(e,cr(i,"General","Parent"),n+1);return{scheme:cr(i,"Appearance","ColorScheme")||s.scheme,use:cr(i,"Cursor Options","UseCustomCursorColor")??s.use,cursor:cr(i,"Cursor Options","CustomCursorColor")??s.cursor}}function sv(e,t){let n=Cp(e,t),r=n.use==="true"?iv(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function ov(e,t){return["[Appearance]",`ColorScheme=${z(e.name)}`,"","[Cursor Options]",`CustomCursorColor=${Me(e.cursor).join(",")}`,`CustomCursorTextColor=${Me(e.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${_s(e.name)}`,`Parent=${t}`,""].join(`
376
+ `)}function av(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 Sl=["--session","--print-reply","--reply-timeout=2000"];function uv(e){return[...(e.run("dbus-send",[...Sl,"--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",[...Sl,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function cv(e,{service:t,window:n},r){let i=(s,...o)=>e.run("dbus-send",[...Sl,`--dest=${t}`,n,`org.kde.konsole.Window.${s}`,...o]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function lv(e,t){let n=Lp(e,t);return n?cr(Oe(n),"General","Name"):void 0}function fv(e){return cr(Oe(Ls(e)),"Desktop Entry","DefaultProfile")}var dv={key:"konsoleBase",profile:_s,base(e){let t=fv(e.configHome);return t&&!t.startsWith(z(""))?{...e.state,konsoleBase:t}:e.state},point(e,t){let n=Ls(e.configHome),r=Oe(n),i=cr(r,"Desktop Entry","DefaultProfile"),s=i?.startsWith(z(""))===!0,o=e.startup?t||s?Tp(e.startup):void 0:s?e.state.konsoleBase??"":void 0;if(o===void 0||o===(i??"")&&!t)return;if(o!==(i??""))xn(n,xp(r,o||void 0));let a=e.startup?_s(e.startup):o?lv(e,o):void 0,u=uv(e.host),c=a!==void 0&&u.every((l)=>cv(e.host,l,a));return{restart:u.length>0&&!c}}},Il={id:"konsole",name:"Konsole",emitter:nl,shelf:{from:"",dir:(e)=>Ia(e.home)},offered:(e,t)=>t.platform!=="darwin"&&t.platform!=="win32",present:(e)=>Na(Ia(e.home))||Na(Ls(e.configHome)),sync(e,t){t.themes(Il);let n=Ia(e.home),r=e.state.konsoleBase??"FALLBACK/",i=new Set;for(let s of av(e)){let o=Cs(n,Tp(s.name));i.add(o),t.write(o,ov(s,r))}for(let s of $a(n))if(s.endsWith(".profile")&&!i.has(s))t.remove(s)},layer:(e)=>({TTHEME_KONSOLE_BASE:sv(e,e.state.konsoleBase)}),plan(e){return[`Write ${De(Ia(e.home),e.home)}/${z("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...e.startup?[`Edit ${De(Ls(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 "${_s(e.startup)}"`:`Konsole default "${_s(e.startup)}", which follows \`ttheme default\``);return n},unwire(e,t){let n=Ls(e.configHome),r=Oe(n);return{edits:cr(r,"Desktop Entry","DefaultProfile")?.startsWith(z(""))?[{file:n,content:xp(r,t?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:dv};import{spawn as hv}from"node:child_process";import{existsSync as vi,mkdirSync as gv,readFileSync as _p,realpathSync as mv,rmSync as pv,writeFileSync as bv}from"node:fs";import{dirname as Gp,join as Mi}from"node:path";function Nl(e){return process.platform==="darwin"?Mi(e,".warp","themes"):Mi(As(e),"warp-terminal","themes")}function Pl(e,t){return process.platform==="darwin"?Mi(e,".warp","settings.toml"):Mi(t,"warp-terminal","settings.toml")}var Wp='"dark"';function Up(e){return Mi(e,"ttheme","warp.base")}var jp="[appearance.themes]";function Kp(e){let t=e.findIndex((r)=>r.trim()===jp);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function Jp(e){let t=e.split(`
377
+ `),n=Kp(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function wv(e){return`{ custom = { name = "${e}", path = "${z(e)}.yaml" } }`}function Bp(e,t){let n=e.split(`
378
+ `),r=Kp(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
379
379
  `)}
380
- ${Ep}
380
+ ${jp}
381
381
  theme = ${t}
382
382
  `;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(`
383
- `)}function bl(e){return Sp(e)?.includes(`path = "${z("")}`)===!0}var DE="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function ev(e,t,n){let r=pl(e.home,e.configHome);if(!ki(r))return;let i=yp(e.configHome),s=wp(r,"utf8"),o;if(t){if(!bl(s)&&!ki(i))YE($p(i),{recursive:!0}),ZE(i,Sp(s)??"");o=XE(t)}else{if(!bl(s))return;o=ki(i)&&wp(i,"utf8")||kp,VE(i,{force:!0})}let a=Mp(s,o);if(a===s)return;if(n)Gu(r),zE(process.execPath,["-e",DE,QE(r),a,s],{detached:!0,stdio:"ignore"}).unref();else Ln(r,a);return r}var wl={id:"warp",name:"Warp",emitter:tl,shelf:{from:"themes",dir:(e)=>ml(e.home)},offered:(e,t)=>t.platform!=="win32",present:(e)=>ki($p(ml(e.home))),sync(e,t){let n=e.startup!==void 0&&!ki(yi(ml(e.home),`${z(e.startup)}.yaml`)),r=ev(e,e.startup,n);if(t.themes(wl),r)t.note(r)},plan(e){let t=pl(e.home,e.configHome);return e.startup&&ki(t)?[`Edit ${De(t,e.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own"],next:()=>[],unwire(e){let t=pl(e.home,e.configHome),n=Oe(t);return{edits:bl(n)?[{file:t,content:Mp(n,Oe(yp(e.configHome))||kp)}]:[],removals:[],touches:[]}}};import{existsSync as Sa}from"node:fs";import{join as Ei}from"node:path";var Ip=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,tv=/^return config[ \t]*$/gm;function nv(e){return`dofile(${JSON.stringify(e)})(config)`}var Pp=`local wezterm = require 'wezterm'
383
+ `)}function Ol(e){return Jp(e)?.includes(`path = "${z("")}`)===!0}var $v="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function kv(e,t,n){let r=Pl(e.home,e.configHome);if(!vi(r))return;let i=Up(e.configHome),s=_p(r,"utf8"),o;if(t){if(!Ol(s)&&!vi(i))gv(Gp(i),{recursive:!0}),bv(i,Jp(s)??"");o=wv(t)}else{if(!Ol(s))return;o=vi(i)&&_p(i,"utf8")||Wp,pv(i,{force:!0})}let a=Bp(s,o);if(a===s)return;if(n)Bu(r),hv(process.execPath,["-e",$v,mv(r),a,s],{detached:!0,stdio:"ignore"}).unref();else xn(r,a);return r}var Rl={id:"warp",name:"Warp",emitter:hl,shelf:{from:"themes",dir:(e)=>Nl(e.home)},offered:(e,t)=>t.platform!=="win32",present:(e)=>vi(Gp(Nl(e.home))),sync(e,t){let n=e.startup!==void 0&&!vi(Mi(Nl(e.home),`${z(e.startup)}.yaml`)),r=kv(e,e.startup,n);if(t.themes(Rl),r)t.note(r)},plan(e){let t=Pl(e.home,e.configHome);return e.startup&&vi(t)?[`Edit ${De(t,e.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own"],next:()=>[],unwire(e){let t=Pl(e.home,e.configHome),n=Oe(t);return{edits:Ol(n)?[{file:t,content:Bp(n,Oe(Up(e.configHome))||Wp)}]:[],removals:[],touches:[]}}};import{existsSync as Ra}from"node:fs";import{join as Si}from"node:path";var qp=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,yv=/^return config[ \t]*$/gm;function Ev(e){return`dofile(${JSON.stringify(e)})(config)`}var Yp=`local wezterm = require 'wezterm'
384
384
  local config = wezterm.config_builder()
385
385
 
386
- `;function rv(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${Pp}return config
387
- `?"":t}function $l(e,t){let n=`-- ttheme begin
386
+ `;function vv(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${Yp}return config
387
+ `?"":t}function Fl(e,t){let n=`-- ttheme begin
388
388
  ${t}
389
389
  -- ttheme end
390
- `;if(Ip.test(e))return e.replace(Ip,n);if(e==="")return`${Pp}${n}
390
+ `;if(qp.test(e))return e.replace(qp,n);if(e==="")return`${Yp}${n}
391
391
  return config
392
- `;let r=[...e.matchAll(tv)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
393
- ${e.slice(r.index)}`}function Ea(e,t){let n=Ei(t,".wezterm.lua");return Sa(n)?n:Ei(e,"wezterm","wezterm.lua")}function Np(e){return Ei(e.configHome,"wezterm","colors")}function va(e){return Ei(e.configHome,"ttheme","wezterm.lua")}var kl={id:"wezterm",name:"WezTerm",emitter:nl,shelf:{from:"colors",dir:Np},offered:()=>!0,present:(e)=>Sa(Ei(e.configHome,"wezterm"))||Sa(Ei(e.home,".wezterm.lua")),sync(e,t){t.themes(kl),t.write(va(e),Qm({path:va(e),colors:Np(e),backgrounds:Te(e.configHome),...e.startup?{startup:e.startup}:{},palettes:e.themes}));let n=Ea(e.configHome,e.home),r=$l(Oe(n),nv(va(e)));if(r!==void 0)t.wire(n,r)},plan(e){let t=Ea(e.configHome,e.home);return $l(Oe(t),"")!==void 0?[`Edit ${De(t,e.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(e){let t=Ea(e.configHome,e.home);return Sa(t)&&$l(Oe(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:sn(Ea(e.configHome,e.home),rv),removals:[],touches:[]})};import{existsSync as Fp,readFileSync as iv,utimesSync as sv}from"node:fs";import{dirname as ov,join as Ma}from"node:path";function yl(e){return Ma(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Op(e){return[Ma(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Ma(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Ma(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Fp(t))}function av(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(iv(t,"utf8"))?.[1];if(n)return n}return}function Rp(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 Hp={id:"windows-terminal",name:"Windows Terminal",emitter:il,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=Op(n);if(t.write(yl(n),rl(e.themes,r??av(i),e.startup))){let s=new Date;for(let o of i)sv(o,s,s);if(i.length>0)t.repaint()}},plan:(e)=>e.state.wtHome?[`Write ${yl(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?ov(yl(n)):void 0;return{edits:[],removals:r&&Fp(r)?[r]:[],touches:n?Op(n):[]}}};var ur={ghostty:ul,kitty:fl,alacritty:al,wezterm:kl,iterm2:lp,"windows-terminal":Hp,warp:wl,konsole:gl};function Ce(e=vt){return e.map((t)=>ur[t])}function Or(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Jt(e){return e.off?void 0:Or(e)}function ge(){return process.env.XDG_CONFIG_HOME??Ia(on(),".config")}var vi=(e)=>typeof e==="string"&&e!==""?e:void 0,uv={author:vi,startup:vi,off:(e)=>e?!0:void 0,itermBase:vi,konsoleBase:vi,wtHome:vi,wtProfile:vi,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 ce(e){let t=Yn(e);if(!El(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Tp(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)=>vt.includes(r)),...Object.fromEntries(Object.entries(uv).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function an(e,t){Z(Yn(e),`${JSON.stringify(t,null,2)}
394
- `)}function Ap(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)=>ve(o)??[]))].filter((o)=>!e.palettes.some((a)=>ve(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:_c(Xe(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function As(e,t,n){return{configHome:e,home:n,state:t,startup:Jt(t)}}function Lp(e,t,n,r){return{...As(e,n,r),entries:t,themes:t.map(wn)}}function xp(e){let t=[],n={written:t,repainted:!1,write(r,i){if(t.push(r),El(r)&&Tp(r,"utf8")===i)return!1;return Z(r,i),!0},wire(r,i){t.push(r),Ln(r,i)},note(r){t.push(r)},remove(r){vl(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 sl(r,s))n.write(Ia(i,o),a)},repaint(){n.repainted=!0}};return n}function cv(e){return Object.assign({},...Ce(e.state.terminals).map((t)=>t.layer?.(e)??{}))}function gt(e,t,n,r=on()){lt(Te(e));let i=Ap(je(e,t),n.palettes);sm(e,new Map(i.map((c)=>[c.name,c.backdrop]))),Zg(e),ua(e,i);let s=Lp(e,i,n,r),o=xp(s);for(let c of Ce(n.terminals))c.sync(s,o);let a=Ia(e,"ttheme","palettes.zsh"),u=Dc(i,s.startup,n.terminals,cv(s));if(o.repainted||Oe(a)!==u)Z(a,u),vl(`${a}.zwc`,{force:!0});return o.written.push(a),o.written}function Lt(e,t=on()){let n=ce(e),r=Ce(n.terminals).filter((o)=>o.pictures);if(r.length===0)return;let i=Lp(e,Ap(yn(e),n.palettes),n,t),s=xp(i);for(let o of r)o.pictures?.(i,s)}function Si(e){return!Ce(e).some((t)=>t.bakes)}function Cp(e,t,n=on()){let r=As(e,t,n);return Ce(t.terminals).flatMap((i)=>[...i.shelf?[`Write ${De(i.shelf.dir(r),n)}/${z("*")} — a theme file per palette`]:[],...i.plan(r)])}function Gp(e,t,n=on()){let r=As(e,t,n);return Ce(t.terminals).flatMap((i)=>i.notes(r))}function _p(e,t,n,r=on()){let i=As(e,t,r);return Ce(t.terminals).flatMap((s)=>s.next(i,n.get(s.id)))}function Na(e,t,n,r,i=on()){let s=[],o=je(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 sl(a,wn(c))){let f=Ia(u,l);if(El(f))vl(f,{force:!0}),s.push(f)}}return s}function Wp(e,t,n,r){return{...As(e,t,r),host:n}}function Sl(e,t,n,r=on()){return Ce(t.terminals).reduce((i,s)=>s.defaults?.base(Wp(e,i,n,r))??i,t)}function Ls(e,t,n,r,i=on()){let s=new Map;for(let o of Ce(t.terminals)){let a=o.defaults?.point(Wp(e,t,r,i),n);if(a)s.set(o.id,a)}return s}function un(e,t,n,r,i=!1,s=Pr(),o=on()){let a=i||!Jt(n)&&Jt(r)!==void 0,u=a?Sl(e,r,s,o):r;return gt(e,t,u,o),an(e,u),a||Jt(n)!==Jt(r)?Ls(e,u,a,s,o):new Map}var lv=300,fv=80,Up=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Pa(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Oa(e,t){if(!t)return Pa(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function cr(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=At()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${nt(`${Up[i%Up.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},fv),o.unref()},lv);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 Sv,mkdirSync as Qp,readFileSync as Vp,statSync as Mv}from"node:fs";import{homedir as Iv}from"node:os";import{dirname as Nv,join as zp}from"node:path";import{existsSync as Ml,mkdirSync as Kp,readFileSync as Ii}from"node:fs";import{homedir as bv}from"node:os";import{dirname as Jp,join as Ni}from"node:path";import{spawn as dv}from"node:child_process";var hv=30000,gv=3,mv=97,pv=`ObjC.import('Vision')
392
+ `;let r=[...e.matchAll(yv)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
393
+ ${e.slice(r.index)}`}function Pa(e,t){let n=Si(t,".wezterm.lua");return Ra(n)?n:Si(e,"wezterm","wezterm.lua")}function zp(e){return Si(e.configHome,"wezterm","colors")}function Oa(e){return Si(e.configHome,"ttheme","wezterm.lua")}var Hl={id:"wezterm",name:"WezTerm",emitter:gl,shelf:{from:"colors",dir:zp},offered:()=>!0,present:(e)=>Ra(Si(e.configHome,"wezterm"))||Ra(Si(e.home,".wezterm.lua")),sync(e,t){t.themes(Hl),t.write(Oa(e),mp({path:Oa(e),colors:zp(e),backgrounds:Re(e.configHome),...e.startup?{startup:e.startup}:{},palettes:e.themes}));let n=Pa(e.configHome,e.home),r=Fl(Oe(n),Ev(Oa(e)));if(r!==void 0)t.wire(n,r)},plan(e){let t=Pa(e.configHome,e.home);return Fl(Oe(t),"")!==void 0?[`Edit ${De(t,e.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(e){let t=Pa(e.configHome,e.home);return Ra(t)&&Fl(Oe(t),"")===void 0?[`${t} has no \`return config\` line — ttheme left it alone; call \`dofile("${Oa(e)}")(config)\` from it yourself`]:[]},next:()=>["WezTerm Reloads its config by itself"],unwire:(e)=>({edits:on(Pa(e.configHome,e.home),vv),removals:[],touches:[]})};import{existsSync as Vp,readFileSync as Mv,utimesSync as Sv}from"node:fs";import{dirname as Iv,join as Fa}from"node:path";function Tl(e){return Fa(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Qp(e){return[Fa(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Fa(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Fa(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Vp(t))}function Nv(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(Mv(t,"utf8"))?.[1];if(n)return n}return}function Zp(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 Xp={id:"windows-terminal",name:"Windows Terminal",emitter:pl,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=Qp(n);if(t.write(Tl(n),ml(e.themes,r??Nv(i),e.startup))){let s=new Date;for(let o of i)Sv(o,s,s);if(i.length>0)t.repaint()}},plan:(e)=>e.state.wtHome?[`Write ${Tl(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?Iv(Tl(n)):void 0;return{edits:[],removals:r&&Vp(r)?[r]:[],touches:n?Qp(n):[]}}};var lr={ghostty:kl,kitty:vl,alacritty:$l,wezterm:Hl,iterm2:Rp,"windows-terminal":Xp,warp:Rl,konsole:Il};function Ce(e=vt){return e.map((t)=>lr[t])}function Tr(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Jt(e){return e.off?void 0:Tr(e)}function ge(){return process.env.XDG_CONFIG_HOME??Ha(an(),".config")}var Ii=(e)=>typeof e==="string"&&e!==""?e:void 0,Pv={author:Ii,startup:Ii,off:(e)=>e?!0:void 0,itermBase:Ii,konsoleBase:Ii,wtHome:Ii,wtProfile:Ii,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 ue(e){let t=Vn(e);if(!Al(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Dp(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)=>vt.includes(r)),...Object.fromEntries(Object.entries(Pv).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function un(e,t){Z(Vn(e),`${JSON.stringify(t,null,2)}
394
+ `)}function eb(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)=>ve(o)??[]))].filter((o)=>!e.palettes.some((a)=>ve(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:Zc(Xe(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Gs(e,t,n){return{configHome:e,home:n,state:t,startup:Jt(t)}}function tb(e,t,n,r){return{...Gs(e,n,r),entries:t,themes:t.map($n)}}function nb(e){let t=[],n={written:t,repainted:!1,write(r,i){if(t.push(r),Al(r)&&Dp(r,"utf8")===i)return!1;return Z(r,i),!0},wire(r,i){t.push(r),xn(r,i)},note(r){t.push(r)},remove(r){xl(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 bl(r,s))n.write(Ha(i,o),a)},repaint(){n.repainted=!0}};return n}function Ov(e){return Object.assign({},...Ce(e.state.terminals).map((t)=>t.layer?.(e)??{}))}function gt(e,t,n,r=an()){ct(Re(e));let i=eb(je(e,t),n.palettes);vm(e,new Map(i.map((c)=>[c.name,Es(c)]))),hm(e),ha(e,i);let s=tb(e,i,n,r),o=nb(s);for(let c of Ce(n.terminals))c.sync(s,o);let a=Ha(e,"ttheme","palettes.zsh"),u=fl(i,s.startup,n.terminals,Ov(s));if(o.repainted||Oe(a)!==u)Z(a,u),xl(`${a}.zwc`,{force:!0});return o.written.push(a),o.written}function Mt(e,t=an()){let n=ue(e),r=Ce(n.terminals).filter((o)=>o.pictures);if(r.length===0)return;let i=tb(e,eb(sn(e),n.palettes),n,t),s=nb(i);for(let o of r)o.pictures?.(i,s)}function Ar(e){return!Ce(e).some((t)=>t.bakes)}function rb(e,t,n=an()){let r=Gs(e,t,n);return Ce(t.terminals).flatMap((i)=>[...i.shelf?[`Write ${De(i.shelf.dir(r),n)}/${z("*")} — a theme file per palette`]:[],...i.plan(r)])}function ib(e,t,n=an()){let r=Gs(e,t,n);return Ce(t.terminals).flatMap((i)=>i.notes(r))}function sb(e,t,n,r=an()){let i=Gs(e,t,r);return Ce(t.terminals).flatMap((s)=>s.next(i,n.get(s.id)))}function Ta(e,t,n,r,i=an()){let s=[],o=je(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 bl(a,$n(c))){let f=Ha(u,l);if(Al(f))xl(f,{force:!0}),s.push(f)}}return s}function ob(e,t,n,r){return{...Gs(e,t,r),host:n}}function Ll(e,t,n,r=an()){return Ce(t.terminals).reduce((i,s)=>s.defaults?.base(ob(e,i,n,r))??i,t)}function Ws(e,t,n,r,i=an()){let s=new Map;for(let o of Ce(t.terminals)){let a=o.defaults?.point(ob(e,t,r,i),n);if(a)s.set(o.id,a)}return s}function cn(e,t,n,r,i=!1,s=Hr(),o=an()){let a=i||!Jt(n)&&Jt(r)!==void 0,u=a?Ll(e,r,s,o):r;return gt(e,t,u,o),un(e,u),a||Jt(n)!==Jt(r)?Ws(e,u,a,s,o):new Map}var Rv=300,Fv=80,ab=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Aa(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function xa(e,t){if(!t)return Aa(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function fr(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=xt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${nt(`${ab[i%ab.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},Fv),o.unref()},Rv);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 Kv,mkdirSync as gb,readFileSync as mb,statSync as Jv}from"node:fs";import{homedir as Bv}from"node:os";import{dirname as qv,join as db}from"node:path";import{existsSync as Cl,mkdirSync as cb,readFileSync as Pi}from"node:fs";import{homedir as Cv}from"node:os";import{dirname as lb,join as Oi}from"node:path";import{spawn as Hv}from"node:child_process";var Tv=30000,Av=3,xv=97,Lv=`ObjC.import('Vision')
395
395
  ObjC.import('CoreImage')
396
396
  ObjC.import('CoreGraphics')
397
397
  function run(argv) {
@@ -410,11 +410,11 @@ function run(argv) {
410
410
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
411
411
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
412
412
  if (!written) throw new Error('write failed')
413
- }`;function Mi(){return process.platform==="darwin"}function Fa(e){return e>=gv&&e<=mv}function xs(e,t,n){return new Promise((r,i)=>{let s=dv("osascript",["-l","JavaScript","-e",pv,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(hv)])}),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(`
414
- `).at(-1)||`osascript exited ${a}`))})})}var Bp=90000;function Ra(e,t){let n=Te(e),r=Ht(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),...Ic(n,i)}]:[]});return r.length>0?r:void 0}function wv(e,t){let n=new Set(lt(Te(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ft(r)))}function Pi(e,t){let n=new Set((t??[]).map((r)=>ft(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ft(r)))}}function $v(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selection,ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}async function kv(e,t,n,r,i,s){let o=X.find((b)=>b.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await ds(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==Ft&&a.md5)try{Bo([a],await qo([a.md5],i))}catch{}let u=Jo(o,a)?Ko(o,a.id,i).then((b)=>{if(b)gs(a,b)},()=>{}):void 0;if(!Uo(o,a,yr(process.env.TTHEME_FIND_RATING))||Wo(a,ti(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=Zt(a);if(!c)throw Error("too large to use");let l=Ni(Xt(o),"orig",`${n.id}.${c.ext}`),f;if(Ml(l))f=new Uint8Array(Ii(l));else{s("Downloading");let b=ni(o,a,c);f=await Yo(b.site,b.url,i,(m,$)=>s("Downloading",Oa(m,$))),Z(l,f)}let d=Gn(f,wt),h=!1;if(gn(d)===0&&Mi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let b=Ni(Xt(o),"cut",`${n.id}.png`);try{if(!Ml(b))s("Cutting out"),Kp(Jp(b),{recursive:!0}),await xs(l,b,i);let m=Gn(new Uint8Array(Ii(b)),wt);if(Fa(gn(m)))d=m,h=!0}catch{}}await u;let g=$v(t);s("Drawing"),ea(e,g,ai(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:hs(a.source),cut:h},{width:0,height:0},wi(e));let p=Ht(e,t.name).find((b)=>b.key===ft(n));if(p)$s(Te(e),p,n,r,bv())}function yv(e,t){let n=X.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${At()?Vi:`\x1B[${30+n.ansi}m${Vi}\x1B[39m`} ${Io(r,n.pageUrl(e.id))}`}async function vn(e,t,n){let r=t.flatMap((u)=>wv(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=Si(n),s=process.stdout.isTTY&&Gm(process.env),o=new Set,a=cr();for(let[u,{entry:c,shared:l}]of r.entries()){let f=`${c.name} · ${yv(l,s)}`,d=r.length>1?` · ${u+1}/${r.length}`:"",h=(g,p)=>a.set(`${g} ${f}${p?` · ${p}`:""}${d}`);try{await kv(e,c,l,i,AbortSignal.timeout(Bp),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)=>Ht(e,u.name).some((f)=>f.key===ft(l)));if(c)ci(e,u.name,ft(c))}if(o.size>0)Lt(e)}function jp(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 Ev(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Ni(ri(),n??"local","cut",`${r??e}.png`);if(!Ml(i)){if(!Mi())return;Kp(Jp(i),{recursive:!0}),await xs(t,i,AbortSignal.timeout(Bp))}return Gn(new Uint8Array(Ii(i)),wt)}function vv(e,t){try{return gn(wr(new Uint8Array(Ii(Ni(e,`${t.stem}.png`)))))>0}catch{return!1}}async function qp(e,t,n,r,i,s,o){let a=Te(e),u=lt(a).palettes[t]?.pictures.find((f)=>f.key===n);if(!u?.original)return null;let c=Ni(a,u.original),l=Gn(new Uint8Array(Ii(c)),wt);if(u.cut){if(!jp(l,wr(new Uint8Array(Ii(Ni(a,u.cut)))),0))return null;return ta(e,t,u,l,r,i,s,o,!1)}if(u.tone===void 0&&gn(l)===0&&vv(a,u)){let f=await Ev(n,c);if(!f||!jp(l,f,3))return null;return ta(e,t,u,l,r,i,s,o,!0)}return ta(e,t,u,l,r,i,s,o,!1)}var Pv=86400000,Ov=3600000,Nl=5000;function Il(){return zp(process.env.XDG_STATE_HOME??zp(Iv(),".local","state"),"ttheme","markets.json")}function Sn(){try{let e=JSON.parse(Vp(Il(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Yp(e,t){let n=Sn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Qp(Nv(Il()),{recursive:!0}),Z(Il(),`${JSON.stringify(n,null,2)}
415
- `)}function Cs(e,t){let n=t===ee?Kt(e):kt(t)?jt(e,t):void 0;try{return n?Mv(n).mtimeMs:void 0}catch{return}}function Fv(e,t,n,r){return e&&(t===void 0||r-t>=Pv)&&(n===void 0||r-n>=Ov)}function Pl(e,t,n=Date.now()){let r=Sn();return it(t.markets).filter((i)=>Fv(Qn(i,t.updates),Cs(e,i),r[i]?.at,n))}async function Rv(e,t,n){try{return await Ss(cm(e),Gc,t,n)}catch(r){if(r instanceof ca)throw Error(`${ye(e)} has no ${tn} — is the repository public, and has its action run?`);throw r}}async function Gs(e,t,n){if(e===ee){let s=await Ss(vm,rn,t,n);return{source:e,id:ee,manifest:s,entries:s.palettes}}let r=await Rv(e,t,n),i=hi(e,r);return{source:e,id:i,manifest:r,entries:aa(r,i)}}function Oi(e,t){if(t.source===ee){oa(e,t.manifest);return}Qp(Oc(e),{recursive:!0}),Z(jt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
416
- `)}function Fi(e,t){try{if(t===ee)return rn(Vp(Kt(e),"utf8")).palettes;let n=Dn(e,t);return aa(n,hi(t,n))}catch{return[]}}function Hv(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 _s(e,t,n){let r=Fi(e,t),i;try{i=await Gs(t,n)}catch(s){throw Yp(t,s.message),s}return Oi(e,i),Yp(t,void 0),{source:t,id:i.id,...t===ee?{version:i.manifest.version}:{},count:Xe(i.entries).length,change:Hv(r,i.entries)}}function dt(e){return`${e} palette${e===1?"":"s"}`}function Ws(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 Zp({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 Ol(e){let t=Zp(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${dt(e.count)}${t?` (${t})`:""}`}function Fl(e){return Zp(e.change)?`Updated ${Ol(e)}`:void 0}async function Ha(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);gt(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 vn(e,je(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Pi(c,u.get(c.name))),t.terminals)}async function Xp(e=ge()){try{if(!Sv(Yn(e)))return;let t=ce(e),n=Pl(e,t);if(n.length===0)return;let r=kn(e),i=cr(`Checking ${n.map(ye).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>_s(e,a,Nl)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>Fl(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await Ha(e,t,r,s)}catch{return}}var rb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Cv=["add","remove","search","init"];function Al(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Gv(){try{let e=Tv("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return rb.test(e)?e:void 0}catch{return}}async function _v(e,t){if(t.author)return t.author;let n=Gv();if(!n){if(!Al())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 Ru({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>rb.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 an(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Ri(e,t){if(t===ee)return ee;return Ae(t)?yt(nn(t)):hi(t,Dn(e,t))}function Ta(e,t){try{return Ri(e,t)}catch{return}}function ib(e){return ve(e)??ee}function Aa(e){return We(e).palettes.filter((t)=>ve(t.name)===void 0)}function Wv(e){let t=Fr(import.meta.dirname,"..","dist","manifest.json");return Rl(t)?rn(Tl(t,"utf8")).palettes:Aa(e)}function Us(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==Qn(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function sb(e,t,n,r){return t.find((i)=>i!==n&&!di(i,n)&&Ta(e,i)===r)}function Hl(e,t,n,r){let i=ce(e),s=it(i.markets),o=sb(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};an(e,Us(i,s.includes(t)?s:[...s,t],a))}async function Uv(e){if(!Al())return!1;let t=await Fn({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 ob(e){let t=cr(`Fetching ${ye(e)}`);try{return await Gs(e)}finally{t.done()}}async function jv(e,t,n){let r=await ob(n),i=ce(e),s=it(i.markets),o=sb(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 an(e,Us(i,s.map((l)=>l===t?n:l),c)),Oi(e,r),r}async function Ll(e,t){let n=Vn(t),r=it(ce(e).markets);if(r.includes(n))return console.log(`${ye(n)} is already added`),{source:n,id:Ri(e,n),fresh:!1};let i=kt(n)?r.find((u)=>kt(u)&&di(u,n)):void 0;if(i){let u=await jv(e,i,n);return console.log(`Moved ${u.id} to ${Pc(n)??"its default branch"} · ${ye(n)} — ${dt(Xe(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Ae(n)){let u=yt(nn(n));Hl(e,n,u);let c=Xn(n,u,Aa(e)).length;return console.log(`Added ${u} · ${ye(n)} — ${dt(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await ob(n),o=n===ee?void 0:await Uv(s.id);Hl(e,n,s.id,o),Oi(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 Kv(e){let t=ge(),{source:n,id:r,fresh:i}=await Ll(t,e);if(!i)return;if(Ae(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===ee)console.log("\n`ttheme browse` picks them");else console.log(`
417
- \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function xl(e,t){if(t===ee)eb(Kt(e),{force:!0});else if(kt(t))eb(jt(e,t),{force:!0})}function Cl(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 Jv(e){let t=ge(),n=ce(t),r=it(n.markets),i=r.find((c)=>Ta(t,c)===e)??r.find((c)=>c===ab(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Ta(t,i),o=n.palettes.filter((c)=>ib(c)===s),a=r.filter((c)=>c!==i),u=Us(n,a,n.updates??{});if(an(t,u),xl(t,i),gt(t,We(t),u),console.log(`Removed ${s??e} · ${ye(i)}`),o.length>0)console.log(Cl(o))}function ab(e){try{return Vn(e)}catch{return}}function Bv(e,t){try{if(t===ee)return Xe(rn(Tl(Kt(e),"utf8")).palettes).length;if(Ae(t))return Xn(t,Ri(e,t),Aa(e),!1).length;return Dn(e,t).palettes.length}catch{return}}function Gl(e,t,n=Sn(),r=Date.now()){if(Ae(t))return"read in place";let i=n[t],s=Cs(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${Ws(i.at,r)}`;return s===void 0?"never updated":`updated ${Ws(s,r)}`}function qv(){let e=ge(),t=ce(e),n=it(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=Sn(),i=n.map((a)=>{let u=Ta(e,a)??"?",c=Bv(e,a),l=t.palettes.filter((d)=>ib(d)===u).length,f=Ae(a)?[]:[`auto-update ${Qn(a,t.updates)?"on":"off"}`];return{name:u,where:ye(a),note:[c===void 0?"Unreadable":dt(c),...l>0?[`${l} installed`]:[],...f,Gl(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 _l(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function Wl(e,t){let n=encodeURIComponent(`topic:${li}${e?` ${e}`:""}`);try{let{items:r}=await Ss(`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 la)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function zv(e){let t=ge(),n=await Wl(e);if(n.length===0){console.log(`No repository carries the ${li} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(it(ce(t).markets).map(zn)),i=n.map((o)=>{let a=_l(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 Yv=`name: ttheme market
413
+ }`;function Ni(){return process.platform==="darwin"}function La(e){return e>=Av&&e<=xv}function Us(e,t,n){return new Promise((r,i)=>{let s=Hv("osascript",["-l","JavaScript","-e",Lv,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Tv)])}),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(`
414
+ `).at(-1)||`osascript exited ${a}`))})})}var fb=90000;function Ca(e,t){let n=Re(e),r=Tt(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),...Cc(n,i)}]:[]});return r.length>0?r:void 0}function _v(e,t){let n=new Set(ct(Re(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ft(r)))}function Ri(e,t){let n=new Set((t??[]).map((r)=>ft(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ft(r)))}}async function Gv(e,t,n,r,i,s){let o=X.find((b)=>b.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await ms(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==Ft&&a.md5)try{Qo([a],await Vo([a.md5],i))}catch{}let u=Yo(o,a)?zo(o,a.id,i).then((b)=>{if(b)bs(a,b)},()=>{}):void 0;if(!Bo(o,a,vr(process.env.TTHEME_FIND_RATING))||Jo(a,oi(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=Zt(a);if(!c)throw Error("too large to use");let l=Oi(Xt(o),"orig",`${n.id}.${c.ext}`),f;if(Cl(l))f=new Uint8Array(Pi(l));else{s("Downloading");let b=ai(o,a,c);f=await Xo(b.site,b.url,i,(m,$)=>s("Downloading",xa(m,$))),Z(l,f)}let d=_n(f,wt),h=!1;if(mn(d)===0&&Ni()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let b=Oi(Xt(o),"cut",`${n.id}.png`);try{if(!Cl(b))s("Cutting out"),cb(lb(b),{recursive:!0}),await Us(l,b,i);let m=_n(new Uint8Array(Pi(b)),wt);if(La(mn(m)))d=m,h=!0}catch{}}await u;let g=Ac(t);s("Drawing"),sa(e,g,di(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:ps(a.source),cut:h},{width:0,height:0},Fr(e),ba(e));let p=Tt(e,t.name).find((b)=>b.key===ft(n));if(p)Ms(Re(e),p,n,r,Cv())}function Wv(e,t){let n=X.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${xt()?Xi:`\x1B[${30+n.ansi}m${Xi}\x1B[39m`} ${Fo(r,n.pageUrl(e.id))}`}async function vn(e,t,n){let r=t.flatMap((u)=>_v(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=Ar(n),s=process.stdout.isTTY&&np(process.env),o=new Set,a=fr();for(let[u,{entry:c,shared:l}]of r.entries()){let f=`${c.name} · ${Wv(l,s)}`,d=r.length>1?` · ${u+1}/${r.length}`:"",h=(g,p)=>a.set(`${g} ${f}${p?` · ${p}`:""}${d}`);try{await Gv(e,c,l,i,AbortSignal.timeout(fb),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)=>Tt(e,u.name).some((f)=>f.key===ft(l)));if(c)gi(e,u.name,ft(c))}if(o.size>0)Mt(e)}function ub(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 Uv(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Oi(ui(),n??"local","cut",`${r??e}.png`);if(!Cl(i)){if(!Ni())return;cb(lb(i),{recursive:!0}),await Us(t,i,AbortSignal.timeout(fb))}return _n(new Uint8Array(Pi(i)),wt)}function jv(e,t){try{return mn(kr(new Uint8Array(Pi(Oi(e,`${t.stem}.png`)))))>0}catch{return!1}}async function _a(e,t,n,r,i,s,o,a){let u=Re(e),c=ct(u).palettes[t]?.pictures.find((d)=>d.key===n);if(!c?.original)return null;let l=Oi(u,c.original),f=_n(new Uint8Array(Pi(l)),wt);if(c.cut){if(!ub(f,kr(new Uint8Array(Pi(Oi(u,c.cut)))),0))return null;return oa(e,t,c,f,r,i,s,o,!1,a)}if(vs(c)&&mn(f)===0&&jv(u,c)){let d=await Uv(n,l);if(!d||!ub(f,d,3))return null;return oa(e,t,c,f,r,i,s,o,!0,a)}return oa(e,t,c,f,r,i,s,o,!1,a)}var zv=86400000,Yv=3600000,Gl=5000;function _l(){return db(process.env.XDG_STATE_HOME??db(Bv(),".local","state"),"ttheme","markets.json")}function Mn(){try{let e=JSON.parse(mb(_l(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function hb(e,t){let n=Mn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};gb(qv(_l()),{recursive:!0}),Z(_l(),`${JSON.stringify(n,null,2)}
415
+ `)}function js(e,t){let n=t===ee?Kt(e):kt(t)?jt(e,t):void 0;try{return n?Jv(n).mtimeMs:void 0}catch{return}}function Qv(e,t,n,r){return e&&(t===void 0||r-t>=zv)&&(n===void 0||r-n>=Yv)}function Wl(e,t,n=Date.now()){let r=Mn();return it(t.markets).filter((i)=>Qv(Zn(i,t.updates),js(e,i),r[i]?.at,n))}async function Vv(e,t,n){try{return await Os(Nm(e),Vc,t,n)}catch(r){if(r instanceof ga)throw Error(`${ye(e)} has no ${tn} — is the repository public, and has its action run?`);throw r}}async function Ks(e,t,n){if(e===ee){let s=await Os(Um,rn,t,n);return{source:e,id:ee,manifest:s,entries:s.palettes}}let r=await Vv(e,t,n),i=wi(e,r);return{source:e,id:i,manifest:r,entries:da(r,i)}}function Fi(e,t){if(t.source===ee){fa(e,t.manifest);return}gb(Uc(e),{recursive:!0}),Z(jt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
416
+ `)}function Hi(e,t){try{if(t===ee)return rn(mb(Kt(e),"utf8")).palettes;let n=tr(e,t);return da(n,wi(t,n))}catch{return[]}}function Zv(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 Js(e,t,n){let r=Hi(e,t),i;try{i=await Ks(t,n)}catch(s){throw hb(t,s.message),s}return Fi(e,i),hb(t,void 0),{source:t,id:i.id,...t===ee?{version:i.manifest.version}:{},count:Xe(i.entries).length,change:Zv(r,i.entries)}}function dt(e){return`${e} palette${e===1?"":"s"}`}function Bs(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 pb({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 Ul(e){let t=pb(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${dt(e.count)}${t?` (${t})`:""}`}function jl(e){return pb(e.change)?`Updated ${Ul(e)}`:void 0}async function Ga(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);gt(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 vn(e,je(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ri(c,u.get(c.name))),t.terminals)}async function bb(e=ge()){try{if(!Kv(Vn(e)))return;let t=ue(e),n=Wl(e,t);if(n.length===0)return;let r=yn(e),i=fr(`Checking ${n.map(ye).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>Js(e,a,Gl)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>jl(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await Ga(e,t,r,s)}catch{return}}var Eb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,nM=["add","remove","search","init"];function ql(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function rM(){try{let e=Xv("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Eb.test(e)?e:void 0}catch{return}}async function iM(e,t){if(t.author)return t.author;let n=rM();if(!n){if(!ql())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 _u({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Eb.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 un(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Ti(e,t){if(t===ee)return ee;return Ae(t)?yt(nn(t)):wi(t,tr(e,t))}function Wa(e,t){try{return Ti(e,t)}catch{return}}function vb(e){return ve(e)??ee}function Ua(e){return We(e).palettes.filter((t)=>ve(t.name)===void 0)}function sM(e){let t=xr(import.meta.dirname,"..","dist","manifest.json");return Kl(t)?rn(Bl(t,"utf8")).palettes:Ua(e)}function qs(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==Zn(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function Mb(e,t,n,r){return t.find((i)=>i!==n&&!bi(i,n)&&Wa(e,i)===r)}function Jl(e,t,n,r){let i=ue(e),s=it(i.markets),o=Mb(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};un(e,qs(i,s.includes(t)?s:[...s,t],a))}async function oM(e){if(!ql())return!1;let t=await Rn({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 Sb(e){let t=fr(`Fetching ${ye(e)}`);try{return await Ks(e)}finally{t.done()}}async function aM(e,t,n){let r=await Sb(n),i=ue(e),s=it(i.markets),o=Mb(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 un(e,qs(i,s.map((l)=>l===t?n:l),c)),Fi(e,r),r}async function zl(e,t){let n=Xn(t),r=it(ue(e).markets);if(r.includes(n))return console.log(`${ye(n)} is already added`),{source:n,id:Ti(e,n),fresh:!1};let i=kt(n)?r.find((u)=>kt(u)&&bi(u,n)):void 0;if(i){let u=await aM(e,i,n);return console.log(`Moved ${u.id} to ${Wc(n)??"its default branch"} · ${ye(n)} — ${dt(Xe(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(Ae(n)){let u=yt(nn(n));Jl(e,n,u);let c=er(n,u,Ua(e)).length;return console.log(`Added ${u} · ${ye(n)} — ${dt(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await Sb(n),o=n===ee?void 0:await oM(s.id);Jl(e,n,s.id,o),Fi(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 uM(e){let t=ge(),{source:n,id:r,fresh:i}=await zl(t,e);if(!i)return;if(Ae(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===ee)console.log("\n`ttheme browse` picks them");else console.log(`
417
+ \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function Yl(e,t){if(t===ee)$b(Kt(e),{force:!0});else if(kt(t))$b(jt(e,t),{force:!0})}function Ql(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 cM(e){let t=ge(),n=ue(t),r=it(n.markets),i=r.find((c)=>Wa(t,c)===e)??r.find((c)=>c===Ib(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Wa(t,i),o=n.palettes.filter((c)=>vb(c)===s),a=r.filter((c)=>c!==i),u=qs(n,a,n.updates??{});if(un(t,u),Yl(t,i),gt(t,We(t),u),console.log(`Removed ${s??e} · ${ye(i)}`),o.length>0)console.log(Ql(o))}function Ib(e){try{return Xn(e)}catch{return}}function lM(e,t){try{if(t===ee)return Xe(rn(Bl(Kt(e),"utf8")).palettes).length;if(Ae(t))return er(t,Ti(e,t),Ua(e),!1).length;return tr(e,t).palettes.length}catch{return}}function Vl(e,t,n=Mn(),r=Date.now()){if(Ae(t))return"read in place";let i=n[t],s=js(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${Bs(i.at,r)}`;return s===void 0?"never updated":`updated ${Bs(s,r)}`}function fM(){let e=ge(),t=ue(e),n=it(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=Mn(),i=n.map((a)=>{let u=Wa(e,a)??"?",c=lM(e,a),l=t.palettes.filter((d)=>vb(d)===u).length,f=Ae(a)?[]:[`auto-update ${Zn(a,t.updates)?"on":"off"}`];return{name:u,where:ye(a),note:[c===void 0?"Unreadable":dt(c),...l>0?[`${l} installed`]:[],...f,Vl(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 Zl(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function Xl(e,t){let n=encodeURIComponent(`topic:${mi}${e?` ${e}`:""}`);try{let{items:r}=await Os(`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 ma)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function dM(e){let t=ge(),n=await Xl(e);if(n.length===0){console.log(`No repository carries the ${mi} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(it(ue(t).markets).map(Qn)),i=n.map((o)=>{let a=Zl(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 hM=`name: ttheme market
418
418
 
419
419
  on:
420
420
  push:
@@ -429,33 +429,33 @@ jobs:
429
429
  runs-on: ubuntu-latest
430
430
  steps:
431
431
  - uses: kecan0406/ttheme/market@v1
432
- `;function ub({name:e}){return`ttheme-${e}`}function Qv(e,t){Dp(ia(e),{recursive:!0}),Dp(Fr(e,".github","workflows"),{recursive:!0}),cb(e,t,[]),Z(Fr(e,".github","workflows","ttheme.yml"),Yv),Z(Fr(e,"README.md"),`# ${yt(t)}
432
+ `;function Nb({name:e}){return`ttheme-${e}`}function gM(e,t){wb(ca(e),{recursive:!0}),wb(xr(e,".github","workflows"),{recursive:!0}),Pb(e,t,[]),Z(xr(e,".github","workflows","ttheme.yml"),hM),Z(xr(e,"README.md"),`# ${yt(t)}
433
433
 
434
434
  A [ttheme](https://github.com/kecan0406/ttheme) market:
435
435
 
436
436
  \`\`\`sh
437
- ttheme market add ${t.owner}/${ub(t)}
437
+ ttheme market add ${t.owner}/${Nb(t)}
438
438
  ttheme browse
439
439
  \`\`\`
440
- `)}function cb(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=ks(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};Z(Fr(e,tn),`${JSON.stringify(a,null,2)}
441
- `)}function lb(e){return en(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function fb(){if(!Al())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Ru({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>lb((t??"").toLowerCase())});if(ht(e))throw Error("no market name given");return e.toLowerCase()}async function db(e,t){let n=Mr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===ab(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 fb();return hb(e,Fc(e,s),s)}async function hb(e,t,n){let r=!Rl(Fr(t,tn)),i;if(r){let o=lb(n);if(o)throw Error(`the market name ${n} ${o}`);if(Rl(t)&&Av(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await _v(e,ce(e)),name:n},Qv(t,i)}else i=nn(t);let s=yt(i);return Hl(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ye(t)}`),{dir:t,...i,id:s}}function tb(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function Vv(e){let t=ge(),n=e&&!tb(e)?e.toLowerCase():e?Lv(Vn(e)).toLowerCase():await fb(),r=e&&tb(e)?Vn(e):Fc(t,n),i=await hb(t,r,n),s=`${i.owner}/${ub(i)}`;console.log(`
440
+ `)}function Pb(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Ss(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};Z(xr(e,tn),`${JSON.stringify(a,null,2)}
441
+ `)}function Ob(e){return en(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function Rb(){if(!ql())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await _u({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>Ob((t??"").toLowerCase())});if(ht(e))throw Error("no market name given");return e.toLowerCase()}async function Fb(e,t){let n=Nr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===Ib(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 Rb();return Hb(e,jc(e,s),s)}async function Hb(e,t,n){let r=!Kl(xr(t,tn)),i;if(r){let o=Ob(n);if(o)throw Error(`the market name ${n} ${o}`);if(Kl(t)&&Dv(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await iM(e,ue(e)),name:n},gM(t,i)}else i=nn(t);let s=yt(i);return Jl(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ye(t)}`),{dir:t,...i,id:s}}function kb(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function mM(e){let t=ge(),n=e&&!kb(e)?e.toLowerCase():e?eM(Xn(e)).toLowerCase():await Rb(),r=e&&kb(e)?Xn(e):jc(t,n),i=await Hb(t,r,n),s=`${i.owner}/${Nb(i)}`;console.log(`
442
442
  \`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:
443
443
 
444
444
  cd ${ye(r)}
445
445
  git init -b main && git add -A && git commit -m "${i.id}"
446
446
  gh repo create ${s} --public --source . --push
447
- gh repo edit ${s} --add-topic ${li}
447
+ gh repo edit ${s} --add-topic ${mi}
448
448
 
449
- Its action rebuilds ${tn} on every push; then \`ttheme market add ${s}\` works anywhere`)}function Zv(e){let t=e?Vn(e):process.cwd(),n=nn(t),r=yt(n),i=Wv(ge()),s=new Map,o=[],a=[];for(let u of Zn(t))try{let c=Es(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=Et(`${r}/${u.slug}`,Tl(u.path,"utf8"),i),f=Ut({...l,name:u.slug});o.push(u.catalog?{...f,catalog:u.catalog}:f)}catch(c){a.push(` ${xv(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:
449
+ Its action rebuilds ${tn} on every push; then \`ttheme market add ${s}\` works anywhere`)}function pM(e){let t=e?Xn(e):process.cwd(),n=nn(t),r=yt(n),i=sM(ge()),s=new Map,o=[],a=[];for(let u of Dn(t))try{let c=Ns(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=Et(`${r}/${u.slug}`,Bl(u.path,"utf8"),i),f=Ut({...l,name:u.slug});o.push(u.catalog?{...f,catalog:u.catalog}:f)}catch(c){a.push(` ${tM(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:
450
450
  ${a.join(`
451
- `)}`),1;for(let u of o){let l=vs(u).filter((d)=>d.startsWith(" ✗")),f=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${f}${l.length>0?`
451
+ `)}`),1;for(let u of o){let l=Ps(u).filter((d)=>d.startsWith(" ✗")),f=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${f}${l.length>0?`
452
452
  ${l.join(`
453
- `)}`:" passes the gate"}`)}return cb(t,n,o),console.log(`
454
- ${r} · ${dt(o.length)} → ${Fr(t,tn)}`),0}async function gb(e,t){switch(e){case void 0:qv();return;case"add":await Kv(nb(e,t));return;case"remove":Jv(nb(e,t));return;case"search":await zv(t);return;case"init":await Vv(t);return;case"build":return Zv(t);default:throw Error(`unknown market action ${e} — ${Cv.join(", ")}, or none to list them`)}}function nb(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 mb(e,t){let n=Ri(e,t);return`${n} — ${dt(Xn(t,n,Aa(e),!1).length)}, read in place`}function Ks(e,t){return`${e}/${t}`}function pb(e){return ve(e.name)?si(e.name):e.name}function js(e){return e.catalog!==void 0&&wb(e.group)?Ks(e.group,e.catalog):void 0}function Ul(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${Ks(e.group,e.name)}`;return e?.kind??""}function La(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function bb(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)=>La(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)=>js(d)!==void 0);for(let d of new Set(f.map((h)=>h.catalog))){let h=f.filter((p)=>p.catalog===d),g=r.length>0||t.has(Ks(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)=>js(d)===void 0).map(o))}return i}function Xv(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||La(i,n))).map((i)=>i.group));return bb(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function wb(e){return e.includes("@")}function jl(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 Kl(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 Dv(e){let t=e.findIndex((n)=>n.kind==="group"&&wb(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 eS(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var lr="\x1B[0m",Js="\x1B[2m",Bs="\x1B[1m",Rr="\x1B[22m",Jl="\x1B[36m",Bl="\x1B[33m";function xa(e){return e==="decode"||e==="glitch"?e:"typewriter"}class qs{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+pb(t).length))}indent(e){return js(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===""||La(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)=>La(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"?Xv(this.entries,this.filter):bb(this.entries,this.expanded,this.filter);this.rows=n.length>0?Dv([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[eS(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=Ul(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>Ul(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=jl(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)=>Ul(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(Ks(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=js(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?`${Js}${"── Markets ──────────"}${lr}`:"── 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?`${Js}${m}${Rr}`:m,s=(m)=>this.color?`${Bs}${m}${Rr}`:m,o=(m)=>this.color?` ${Pd(na(m),r?zt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${zt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Mo(n.selection,n.foreground)} ${m} ${lr}`:`${a} ${m}`;if(e.kind==="all"){let m=this.everyone(this.rows).every(($)=>this.picked.has($.name))?"●":"○";return u(`${m} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let m=this.pickedIn(e.name)===e.count?"●":"○",$=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${m} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i($)}`)}let c=this.rows[this.cursor],l=(m,$)=>this.color&&c?.kind==="palette"&&m?`${Bs}${zt(c.entry.cursor)}${$}${Rr}\x1B[39m`:s($);if(e.kind==="group"){let m=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),$=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${$}`)}if(e.kind==="catalog"){let m=c?.kind==="palette"&&js(c.entry)===Ks(e.group,e.name),$=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(m,e.name)} ${$}`)}let f=e.entry,d=this.picked.has(f.name)?"●":"○",h=this.indent(f),g=pb(f),p=this.color?g.padEnd(this.namePad-h.length):g,b=t?s(p):p;return u(`${h}${d} ${b}${o(f)}`)}}function ql(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 Ca{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 zl extends Nt{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 qs({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 Ca(e.fx??"typewriter",()=>ql(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=Kl(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?`${Js}${h}${lr}`:h,t=(h)=>this.color?`${Jl}${h}${lr}`: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?`${Bl}${this.error}${lr}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,s,...u,c,d].join(`
455
- `)}}var zs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],Yl=34,tS=72,nS=94,Ql={title:"",lines:[],brief:""};function Ga(e){let t=e.trim();if(t!==ee&&!t.includes("/")&&!t.startsWith("~"))return;try{return Vn(t)}catch{return}}function rS(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Vl extends Nt{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 qs({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new qs({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Ca(e.fx??"typewriter",()=>ql(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=Kl(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=zs.findIndex((i)=>i.tab===this.tab),n=zs[(t+e+zs.length)%zs.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]=jl(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"&&!Ae(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>di(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Ae(e)||e===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&&!Ga(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=Ga(this.filters.markets);if(i&&!n.some((o)=>di(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:_l(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?`${Js}${e}${Rr}`:e}bold(e){return this.color?`${Bs}${e}${Rr}`:e}warn(e){return this.color?`${Bl}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${zt(e.cursor)}▌\x1B[39m ${Mo(e.selection,e.foreground)} ${n} ${lr}`;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&&!Ga(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 zs.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 Ql;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?Ve(e.native,t).map((d)=>this.dim(d)):[],...Ve(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,...Ve(l,t),f],brief:`${e.group} · ${f}`}}let n=e.entry,r=this.sourceOf(n),i=Ms(n),s=`Gate ${pt.length-i.length}/${pt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=ve(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${Bs}${zt(n.cursor)}${n.name}${Rr}\x1B[39m`:n.name,lines:[...Ve(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>Ve(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 Ql;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=Ae(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??rS(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:[...Ve(s,t),u,"",Ae(i.source)?c:`${c} ${this.dim("←→")}`,...Ae(i.source)?[]:[l],...f?Ve(f,t).map((h)=>this.warn(h)):[],...d.length>0?["",...d.flatMap((h)=>Ve(h,t))]:[]],brief:[s,c,...d,...Ae(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(ye(e.source)),lines:["Not added","",...Ve(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:[...Ve(`Repositories with the ${li} topic`,t),...i&&!Ga(i)?[`Matching "${i}"`]:[],"",...Ve(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}`,...Ve(e.repo.description??"",t),"",...Ve(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:Ve(r.message,e),brief:r.message}:Ql}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?`${Jl}${f}${lr}`: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>=nS,r=n?Math.min(t-Yl-4,tS):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()}`,fn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?Yl:r-2);return[...n?u.map((f,d)=>`${nt(f,r)} ${this.dim("│")} ${nt(d===0?c.title:c.lines[d-1]??"",Yl,!1)}`):[...u.map((f)=>nt(f,r,!1)),nt(`${e("│")} ${this.dim(c.brief)}`,r,!1)],nt(this.footer(e,n),t-1,!1)].join(`
456
- `)}}import{existsSync as _I}from"node:fs";import{existsSync as co,mkdirSync as RI,readFileSync as If}from"node:fs";import{dirname as HI}from"node:path";import{execFile as iS}from"node:child_process";import{createHash as Eb}from"node:crypto";import{existsSync as sS,mkdtempSync as oS,readFileSync as ja,rmSync as aS,statSync as vb,writeFileSync as Sb}from"node:fs";import{homedir as uS,tmpdir as cS}from"node:os";import{join as _a}from"node:path";import{fileURLToPath as lS}from"node:url";import{promisify as fS}from"node:util";var cn=fS(iS),Wa=67108864,dS=4096,Dl=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],hS=["text/uri-list","text/plain;charset=utf-8","text/plain"],Zl=[...Dl,"text/uri-list","text/plain"];function gS(e){try{return vb(e).isFile()}catch{return!1}}function mS(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 $b(e){if(/^file:\/\//i.test(e))try{return lS(e)}catch{return}if(e.startsWith("~/"))return _a(uS(),e.slice(2));return e.startsWith("/")?e:void 0}function Hi(e,t=gS){let n=[];for(let r of e.replace(/\r\n?/g,`
453
+ `)}`:" passes the gate"}`)}return Pb(t,n,o),console.log(`
454
+ ${r} · ${dt(o.length)} → ${xr(t,tn)}`),0}async function Tb(e,t){switch(e){case void 0:fM();return;case"add":await uM(yb(e,t));return;case"remove":cM(yb(e,t));return;case"search":await dM(t);return;case"init":await mM(t);return;case"build":return pM(t);default:throw Error(`unknown market action ${e} — ${nM.join(", ")}, or none to list them`)}}function yb(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 Ab(e,t){let n=Ti(e,t);return`${n} — ${dt(er(t,n,Ua(e),!1).length)}, read in place`}function Ys(e,t){return`${e}/${t}`}function xb(e){return ve(e.name)?li(e.name):e.name}function zs(e){return e.catalog!==void 0&&Cb(e.group)?Ys(e.group,e.catalog):void 0}function Dl(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${Ys(e.group,e.name)}`;return e?.kind??""}function ja(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function Lb(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)=>ja(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)=>zs(d)!==void 0);for(let d of new Set(f.map((h)=>h.catalog))){let h=f.filter((p)=>p.catalog===d),g=r.length>0||t.has(Ys(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)=>zs(d)===void 0).map(o))}return i}function bM(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||ja(i,n))).map((i)=>i.group));return Lb(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function Cb(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 tf(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 wM(e){let t=e.findIndex((n)=>n.kind==="group"&&Cb(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 $M(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var dr="\x1B[0m",Qs="\x1B[2m",Vs="\x1B[1m",Lr="\x1B[22m",nf="\x1B[36m",rf="\x1B[33m";function Ka(e){return e==="decode"||e==="glitch"?e:"typewriter"}class Zs{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+xb(t).length))}indent(e){return zs(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===""||ja(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)=>ja(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"?bM(this.entries,this.filter):Lb(this.entries,this.expanded,this.filter);this.rows=n.length>0?wM([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[$M(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=Dl(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>Dl(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)=>Dl(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(Ys(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=zs(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?`${Qs}${"── Markets ──────────"}${dr}`:"── 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?`${Qs}${m}${Lr}`:m,s=(m)=>this.color?`${Vs}${m}${Lr}`:m,o=(m)=>this.color?` ${Wd(aa(m),r?zt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${zt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Ro(n.selection,n.foreground)} ${m} ${dr}`:`${a} ${m}`;if(e.kind==="all"){let m=this.everyone(this.rows).every(($)=>this.picked.has($.name))?"●":"○";return u(`${m} Select all ${i(`(${e.count})`)}`)}if(e.kind==="group"&&this.scope==="series"){let m=this.pickedIn(e.name)===e.count?"●":"○",$=`(${e.count})${e.native?` ${e.native}`:""}`;return u(`${m} ${s(e.name.padEnd(this.seriesPad))}${o(e.lead)}${this.color?" ":" "}${i($)}`)}let c=this.rows[this.cursor],l=(m,$)=>this.color&&c?.kind==="palette"&&m?`${Vs}${zt(c.entry.cursor)}${$}${Lr}\x1B[39m`:s($);if(e.kind==="group"){let m=l(c?.kind==="palette"&&c.entry.group===e.name,e.name),$=e.native?` ${i(e.native)}`:"";return u(`${e.expanded?"▾":"▸"} ${m} ${i(`(${this.pickedIn(e.name)}/${e.count})`)}${$}`)}if(e.kind==="catalog"){let m=c?.kind==="palette"&&zs(c.entry)===Ys(e.group,e.name),$=i(`(${this.pickedIn(e.group,e.name)}/${e.count})`);return u(` ${e.expanded?"▾":"▸"} ${l(m,e.name)} ${$}`)}let f=e.entry,d=this.picked.has(f.name)?"●":"○",h=this.indent(f),g=xb(f),p=this.color?g.padEnd(this.namePad-h.length):g,b=t?s(p):p;return u(`${h}${d} ${b}${o(f)}`)}}function sf(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 Ja{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 of extends Pt{picked;list;scope;color;hint;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output,validate:e.required?()=>this.picked.size===0?`Pick at least one ${this.scope}`:void 0:void 0},!0);this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new Zs({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 Ja(e.fx??"typewriter",()=>sf(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=tf(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?`${Qs}${h}${dr}`:h,t=(h)=>this.color?`${nf}${h}${dr}`: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?`${rf}${this.error}${dr}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,s,...u,c,d].join(`
455
+ `)}}var Xs=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],af=34,kM=72,yM=94,uf={title:"",lines:[],brief:""};function Ba(e){let t=e.trim();if(t!==ee&&!t.includes("/")&&!t.startsWith("~"))return;try{return Xn(t)}catch{return}}function EM(e){return e.charAt(0).toUpperCase()+e.slice(1)}class cf extends Pt{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new Zs({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new Zs({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new Ja(e.fx??"typewriter",()=>sf(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=tf(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=Xs.findIndex((i)=>i.tab===this.tab),n=Xs[(t+e+Xs.length)%Xs.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"&&!Ae(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>bi(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(Ae(e)||e===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&&!Ba(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=Ba(this.filters.markets);if(i&&!n.some((o)=>bi(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:Zl(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?`${Qs}${e}${Lr}`:e}bold(e){return this.color?`${Vs}${e}${Lr}`:e}warn(e){return this.color?`${rf}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${zt(e.cursor)}▌\x1B[39m ${Ro(e.selection,e.foreground)} ${n} ${dr}`;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&&!Ba(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 Xs.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 uf;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?Ve(e.native,t).map((d)=>this.dim(d)):[],...Ve(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,...Ve(l,t),f],brief:`${e.group} · ${f}`}}let n=e.entry,r=this.sourceOf(n),i=Rs(n),s=`Gate ${pt.length-i.length}/${pt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=ve(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${Vs}${zt(n.cursor)}${n.name}${Lr}\x1B[39m`:n.name,lines:[...Ve(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>Ve(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 uf;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=Ae(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??EM(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:[...Ve(s,t),u,"",Ae(i.source)?c:`${c} ${this.dim("←→")}`,...Ae(i.source)?[]:[l],...f?Ve(f,t).map((h)=>this.warn(h)):[],...d.length>0?["",...d.flatMap((h)=>Ve(h,t))]:[]],brief:[s,c,...d,...Ae(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(ye(e.source)),lines:["Not added","",...Ve(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:[...Ve(`Repositories with the ${mi} topic`,t),...i&&!Ba(i)?[`Matching "${i}"`]:[],"",...Ve(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}`,...Ve(e.repo.description??"",t),"",...Ve(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:Ve(r.message,e),brief:r.message}:uf}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?`${nf}${f}${dr}`: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>=yM,r=n?Math.min(t-af-4,kM):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()}`,dn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?af:r-2);return[...n?u.map((f,d)=>`${nt(f,r)} ${this.dim("│")} ${nt(d===0?c.title:c.lines[d-1]??"",af,!1)}`):[...u.map((f)=>nt(f,r,!1)),nt(`${e("│")} ${this.dim(c.brief)}`,r,!1)],nt(this.footer(e,n),t-1,!1)].join(`
456
+ `)}}import{existsSync as iN}from"node:fs";import{existsSync as mo,mkdirSync as VI,readFileSync as _f}from"node:fs";import{dirname as ZI}from"node:path";import{execFile as vM}from"node:child_process";import{createHash as Ub}from"node:crypto";import{existsSync as MM,mkdtempSync as SM,readFileSync as Qa,rmSync as IM,statSync as jb,writeFileSync as Kb}from"node:fs";import{homedir as NM,tmpdir as PM}from"node:os";import{join as qa}from"node:path";import{fileURLToPath as OM}from"node:url";import{promisify as RM}from"node:util";var ln=RM(vM),za=67108864,FM=4096,df=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],HM=["text/uri-list","text/plain;charset=utf-8","text/plain"],lf=[...df,"text/uri-list","text/plain"];function TM(e){try{return jb(e).isFile()}catch{return!1}}function AM(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 _b(e){if(/^file:\/\//i.test(e))try{return OM(e)}catch{return}if(e.startsWith("~/"))return qa(NM(),e.slice(2));return e.startsWith("/")?e:void 0}function Ai(e,t=TM){let n=[];for(let r of e.replace(/\r\n?/g,`
457
457
  `).split(`
458
- `)){let i=$b(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of mS(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=$b(s);if(o&&t(o))n.push(o)}}return n}function pS(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 kb(e){let t=Xr(e)?_n(e):pS(e);if(!t)return;return{ext:Xr(e)?"png":"jpg",width:t.width,height:t.height}}async function Ua(e,t){let n=kb(e);if(n&&n.width*n.height<=wt)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${wt/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=oS(_a(cS(),"ttheme-attach-"));try{let i=_a(r,"in"),s=_a(r,"out.png");Sb(i,e);let o=!n||n.width*n.height>wt?["--resampleHeightWidthMax",String(dS)]:[];await cn("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(ja(s)),u=kb(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{aS(r,{recursive:!0,force:!0})}}async function ef(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":cc},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Wa)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 Ua(r,e)}if(vb(e).size>Wa)throw Error("that picture is over 64 MB");return Ua(new Uint8Array(ja(e)),e)}var Mb=new Map,Hr={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)=>Mb.get(e)??"",parse:()=>[],count:()=>0};function Ib(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Nb(e,t){Mb.set(e,t)}function Pb(e){return Number.parseInt(Eb("sha1").update(e).digest("hex").slice(0,8),16)%Jn}var bS=`ObjC.import('AppKit')
458
+ `)){let i=_b(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of AM(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=_b(s);if(o&&t(o))n.push(o)}}return n}function xM(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 Gb(e){let t=ri(e)?Wn(e):xM(e);if(!t)return;return{ext:ri(e)?"png":"jpg",width:t.width,height:t.height}}async function Ya(e,t){let n=Gb(e);if(n&&n.width*n.height<=wt)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${wt/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=SM(qa(PM(),"ttheme-attach-"));try{let i=qa(r,"in"),s=qa(r,"out.png");Kb(i,e);let o=!n||n.width*n.height>wt?["--resampleHeightWidthMax",String(FM)]:[];await ln("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(Qa(s)),u=Gb(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{IM(r,{recursive:!0,force:!0})}}async function hf(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":pc},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>za)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 Ya(r,e)}if(jb(e).size>za)throw Error("that picture is over 64 MB");return Ya(new Uint8Array(Qa(e)),e)}var Jb=new Map,Cr={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)=>Jb.get(e)??"",parse:()=>[],count:()=>0};function Bb(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function qb(e,t){Jb.set(e,t)}function zb(e){return Number.parseInt(Ub("sha1").update(e).digest("hex").slice(0,8),16)%Bn}var LM=`ObjC.import('AppKit')
459
459
  function run(argv) {
460
460
  const pb = $.NSPasteboard.generalPasteboard
461
461
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -480,16 +480,16 @@ function run(argv) {
480
480
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
481
481
  const text = pb.stringForType('public.utf8-plain-text')
482
482
  return text && !text.isNil() ? text.js : ''
483
- }`,wS=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
483
+ }`,CM=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
484
484
  $c = [Windows.Forms.Clipboard]
485
485
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
486
486
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
487
487
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
488
488
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
489
- $c::GetText()`;function Ob(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(ja("/proc/version","utf8"))}catch{return!1}}async function $S(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await cn(n[0],n[1])).stdout.split(`
490
- `).map((o)=>o.trim()),i=(o)=>t?cn("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:Wa}):cn("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:Wa});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Dl.find((o)=>r.includes(o));if(s)return Sb(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 tf(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Fb(e){if(process.platform==="darwin"){let t=(await cn("osascript",["-l","JavaScript","-e",bS,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Ob()){let t=(await cn("powershell.exe",["-NoProfile","-STA","-Command",wS])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
491
- `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await cn("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
492
- `)}}if(process.platform==="linux")return $S(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var kS=`ObjC.import('AppKit')
489
+ $c::GetText()`;function Yb(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Qa("/proc/version","utf8"))}catch{return!1}}async function _M(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await ln(n[0],n[1])).stdout.split(`
490
+ `).map((o)=>o.trim()),i=(o)=>t?ln("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:za}):ln("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:za});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=df.find((o)=>r.includes(o));if(s)return Kb(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 gf(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Qb(e){if(process.platform==="darwin"){let t=(await ln("osascript",["-l","JavaScript","-e",LM,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Yb()){let t=(await ln("powershell.exe",["-NoProfile","-STA","-Command",CM])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
491
+ `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await ln("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
492
+ `)}}if(process.platform==="linux")return _M(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var GM=`ObjC.import('AppKit')
493
493
  function run() {
494
494
  const pb = $.NSPasteboard.generalPasteboard
495
495
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -501,49 +501,50 @@ function run() {
501
501
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
502
502
  }
503
503
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
504
- }`;async function Rb(){if(tf())return;if(process.platform==="darwin"){let[e="",t=""]=(await cn("osascript",["-l","JavaScript","-e",kS])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Ob()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await cn("wl-paste",["--list-types"])).stdout:(await cn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function Ka(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:yS(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 yS(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 Ys=(e)=>Buffer.from(e).toString("base64"),Xl=(e)=>Buffer.from(e,"base64");function yb(e,t){return t.find((n)=>e.includes(n))}class nf{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Ys(Eb("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;${Zl.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=${Ys("ttheme")}:pw=${this.pw};${Ys(".")}\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?Xl(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Xl(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=yb(s,[...Dl,...hS]);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=${Ys(u)}:pw=${a};${Ys(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=Zl.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=yb(a,Zl);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(Xl(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"?Hi(a).find((c)=>sS(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(ja(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var Be={pitch:25,cols:22,rows:9,height:13},Ar={cols:25,rows:16},ES=2147483648,vS=-1073741826,SS=1600,Hb=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],MS=56,IS=4,Tb=20,NS=50,Ab=[["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"]],PS="\x1B[0m",Qe="\x1B[1m",K="\x1B[2m",Zs="\x1B[32m",ln="\x1B[33m",OS={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 qa(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(OS[`${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===`
505
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Kb="\x1B]1337;ReportCellSize\x07\x1B[16t",Lb="\x1B]1337;ReportCellSize=";function uf(e){let t=e.indexOf(Lb);if(t!==-1){let i=e.slice(t+Lb.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function Lr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Be.pitch)),rowsVis:Math.max(1,Math.floor(n/Be.height)),height:n}}function Jb(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function Bb(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 qb(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function Ti(e){return`\x1B[38;2;${Pe(e).join(";")}m`}function Ba(e){return`\x1B[48;2;${Pe(e).join(";")}m`}var rf=!1;function za(e){return rf=!0,e.beat}function Ai(e){return Hb[za(e)%Hb.length]}function Ge(e){return $e(e)}function zb(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 Li(e){return`\x1B[${30+e}m`}function xi(e,t,n,r){return n?[[`${Vi} `,r],[e,t,n]]:[[e,t]]}function sf(e){return e.reduce((t,[n])=>t+Ge(n),0)}function FS(e,t){let n=[],r=t;for(let[i,s,o]of e){let a=Ge(i);if(a<=r){n.push([i,s,o]),r-=a;continue}n.push([`${zb(i,r)}…`,s,o]);break}return n}class Ja{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+Ge(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+Ge(r),0),t)}center(e,t){this.run(Math.floor((e-t.reduce((n,[r])=>n+Ge(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=zb(n,this.cols-t);e+=`\x1B[${t+1}G${r}${Io(s,i)}${r?PS:""}`}return e}}function RS(e){return e.replace(/_\([^)]*\)?$/,"")}function Yb(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<SS?ln:K]}function Xs(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[sf(s)]:[],...i.map(([d,h])=>Ge(d)+1+Ge(h))];return(r.badge?Ge(r.badge)+4:0)+l.reduce((d,h)=>d+h,0)+3*Math.max(0,l.length-1)+(o?3+Ge(o[0])+1+Ge(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=FS(s,Math.max(0,sf(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,Qe],[` ${f}`,K]])].forEach((l,f)=>{u=e.run(u+(f?3:0),l)}),o)e.right(t,[[o[0],Qe],[` ${o[1]}`,K]])}function HS(e,t){if(e==="d")return K;if(e==="b")return Qe;if(e==="s")return Ba(t.colors.selection);if(e==="c")return Ba(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 TS(e,t,n,r,i){let s=Tt.indexOf(fa(r.scene)),o=Tt.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Qe+i:K]]),a=o.reduce((u,[c])=>u+Ge(c),0)<=n;e?.run(t,a?o:[[fa(r.scene).name,Qe+i],[` ${s+1}/${Tt.length}`,K]])}function AS(e,t,n,r,i,s,o){let{ansi:a,cursor:u}=s.colors;TS(e[t-2],n,r,s,o);let c=r<Tm?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),Ti(a[d]??u)+Ba(a[d+8]??u))??l)+1;let f=t+2;for(let d of fa(s.scene).lines){let h=Am(d,r);if(!h)continue;if(f>i)return;e[f]?.run(n,h.map(([g,p])=>[g,HS(p,s)])),f++}}function LS(e,t,n){let r=[[]];for(let o of e){let a=r[r.length-1];if(a.length===0||Ge([...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&&Ge([...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 xb(e){return e.replace(/^https?:\/\/(?:www\.)?/,"")}function xS(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Li(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?xi(xb(s.page),"",s.page,a):[["—",K]]],["Source",s?.source?xi(xb(s.source),"",s.link,i):[["—",K]]],["Artist",[o.length>0?[o.join(" "),""]:["—",K]]]].forEach(([c,l],f)=>{e[t+f]?.put(n,c,K),e[t+f]?.run(n+12,l)})}function CS(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?[Pa(u.bytes)]:[]].join(" · "),d=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),h=(b,m)=>b.length>0?LS(b,l,m).map(($)=>[[$,""]]):[[["—",K]]],g=[["Characters",h(o.characters,2)],["Series",h(o.series,1)],["Tags",h(o.tags,3)],["Rating",[[[d,d==="—"?K:""]]]],["File",[[[f,""],...u?[[" ",""]]:[],...u?Qb(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",K]]]]],p=t;for(let[b,m]of g){if(p+m.length-1>i)return;e[p]?.put(n,b,K);for(let $ of m)e[p]?.run(c,$),p++}}var GS=["Size","Position","Opacity"],_S=[0,3,6];function WS(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 US(e){return e.toFixed(2)}function jS(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,Qe+s],[" Background",K],...a?[[" · ",K],...xi(`${a.site} ${a.id}`,K,a.page||void 0,Li(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[f,d]of GS.entries()){let h=t+_S[f],g=o.field===f,p=g?Qe:K;if(g)e[h]?.put(n,"▶",s);e[h]?.put(n+2,d,p);let b;if(f===1){for(let m=1;m<=9;m++){let $=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,$?"■":"·",$?Qe+s:K)}b=$t[i.tune.at-1]??"center"}else{let m;if(f===0){let{size:$}=i.tune;m=$==="fill"?u-1:Math.floor(($-c)*(u-1)/(l-c+1)),b=$==="fill"?"fill":`${$}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),b=US(i.tune.opacity);m=Math.max(0,Math.min(u-1,m)),e[h]?.run(n+12,[["━".repeat(m),s],["●",Qe],["─".repeat(u-1-m),K]])}if(e[h]?.right(r-2,[[b,p]]),WS(i,f))e[h]?.put(r-1,"↺",g?Qe+s:K)}}function KS(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 of(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function Vs(e){return`${X[Math.floor(e/Jn)]?.name??"local"} ${e%Jn}`}function Qs(e,t,n){let r=X[Math.floor(t/Jn)],i=Vs(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],...xi(i,n,r.pageUrl(t%Jn),Li(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function JS(e,t,n){let r=[{name:"all",moved:!1},...X].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?of(n,a):[` ${a} `,K];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+Ge(o),0)<=t;e.run(0,i?r:[of(n)])}function BS(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"}`,K);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":K]]),s=$r.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(" ")}`,K),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,K]);e.right(t,u)}}function Qb(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,Zs]];if(e.cut==="off")return[["Opaque · x cuts out",ln]];if(e.cut==="failed")return[["Opaque · no cut-out",ln]];return[e.clear>0?[`${e.clear}% transparent`,Zs]:["Opaque",ln]]}function Cb(e){return e.site==="all"?"any site":e.site}function af(e,t){if(e.installing!==void 0)return Qs(`${Ai(e)} Installing ${e.palette} ← ${Vs(e.installing)}`,e.installing,ln);if(e.hint)return[[e.hint,Zs]];if(e.error)return[[e.error,ln]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,ln]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return Qs(`${Ai(e)} Fetching ${Vs(n)} · ${Oa(r,i)}`,n,ln)}if(e.cutting!==void 0)return Qs(`${Ai(e)} Cutting out ${Vs(e.cutting)}`,e.cutting,ln);if(e.preparing!==void 0)return Qs(`${Ai(e)} Preparing ${Vs(e.preparing)}`,e.preparing,ln);if(t)return[t];if(e.saved)return Qs(e.saved.text,e.saved.key,Zs);if(e.note)return[[e.note,K]];return}function Vb(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 Zb(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function qS(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=za(r)%(Tb*2)/Tb,d=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(f<1?f:2-f)))),h=rt(s,o,i),g=rt(s,rt(a,s,0.15),i),p=Array.from({length:n},(m,$)=>{let k=(c>=0?$<c:$>=d&&$<d+l)?h:g;return $===0||$===n-1?rt(k,s,0.55):k}),b=0;for(let m=1;m<=n;m++)if(m===n||p[m]!==p[b])e?.put(t+b," ".repeat(m-b),Ba(p[b])),b=m}function zS(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(za(i)-i.loaderFrom)/IS),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[Vb(i),Qe+Ti(rt(s,o,a))],[Zb(i," "),Ti(rt(s,rt(o,s,0.45),a))]]);let c=Math.min(MS,r-8);if(qS(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?[[" · ",Ti(rt(s,o,0.25*a))]]:[],[l,Ti(rt(s,f?rt(o,s,0.2):o,f?a:0.32*a))]]))}function YS(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:K)}}function QS(e,t,n){if(t)return[`${Ai(e)} ${Vb(e)}${Zb(e," · ")}`,K];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Ai(e)} Loading thumbnails · ${i}/${r.length}`,K]:void 0}function VS(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=Lr(n,r);BS(e[0],n,i,s),JS(e[1],n,i);let c=e.map((y,N)=>N>=2&&N<2+u?y:void 0),l=Math.floor(i.scroll/Be.height),f=Math.floor((i.scroll+u-1)/Be.height),d=[];for(let y=l;y<=f;y++){let N=2+y*Be.height-i.scroll;for(let O=0;O<o;O++){let T=y*o+O,A=O*Be.pitch,C=i.tiles[T];if(!C)continue;d.push(C);let _=T===i.focus;if(_)KS(c,N,A,Be.height,Be.pitch-1,s);let L=N+1,R=Math.max(L,2),J=Math.min(L+Be.rows,2+u);if(C.thumb&&J>R)t.push({id:C.key,path:C.thumb,row:R,col:A+1,cols:Be.cols,rows:J-R,...J-R<Be.rows?{crop:R-L}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",Zs]]:[],...C.page||i.site!=="all"?xi(String(C.id),_?Qe:"",C.page||void 0,Li(C.siteAnsi)):[["● ",Li(C.siteAnsi)],[String(C.id),_?Qe:""]],[" ",""],Yb(C)],be=Be.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(A+1,sf(Ee)>be?Ee.map(([Le,de,ae])=>[Le.replace(/^(\S) $/,"$1"),de,ae]):Ee),C.mates.length>0)c[N+10]?.put(A+Be.cols,"≈",s);c[N+11]?.put(A+1,C.artist?RS(C.artist).slice(0,Be.cols-8):"—",K);let Y=[];if(C.score>0)Y.push([`★${C.score}`,K]);if(C.variants>1)Y.push([` ×${C.variants}`,s]);if(Y.length>0)c[N+11]?.right(A+Be.cols+1,Y)}}let h=Math.ceil(i.tiles.length/o)*Be.height;YS(e,n,i,u,h,s);let g=Math.max(2,2+h-i.scroll),p=2+u-g,b=i.searching&&p>=2;if(b)zS(c,g,p,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[y,N]=Ab[Math.floor(za(i)/NS)%Ab.length];e[r-2]?.run(0,[["Tip ",K],[y,Qe],[` ${N}`,K]])}let $=i.top*o,k=i.tiles.length-(i.top+a)*o,M=[...$>0?[`↑ ${$} above`]:[],...k>0?[`↓ ${k} more`]:[]];if(M.length>0)e[r-2]?.put(0,M.join(" "),K);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 ${Cb(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${Cb(i)} — tab tries ${i.nextSite}`,K);let w=QS(i,b,d),S=af(i,w);return Xs(e[r-1],n,s,{badge:"IMAGE SEARCH",lead:S,keys:m&&S?.[0]===w?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),b}function ZS(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=[of(i,o.site,o.siteAnsi),[" ",""],...xi(String(o.id),Qe,o.page||void 0,Li(o.siteAnsi)),[" ",""],Yb(o)];if(o.score>0)u.push([` · ★${o.score}`,K]);if(a)u.push([` · ${Pa(a.bytes)}`,K]);if(a)u.push([" ",""],...Qb(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),K]]);if(xS(e,1,2,i,s),i.tuning)jS(e,8,2,2+Math.min(n-4,60),i,s);else if(i.details)CS(e,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else AS(e,7,2,n-4,r-2,i,s);if(i.shown)t.push({id:ES+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:vS});if(i.tuning){Xs(e[r-1],n,s,{badge:"IMAGE EDIT",lead:af(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["enter","keep"]],right:["esc","undo"]});return}let c=af(i);Xs(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 XS=[["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"]],DS={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",`⇧←→ ${Tt.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"]]},cf=6,eM=24;function Ds(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function tM(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function Gb(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>tM(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function Xb(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 Tr(e,t){let n=[],r="";for(let i of e.split(" "))if(r&&Ge(r)+1+Ge(i)>t)n.push(r),r=i;else r=r?`${r} ${i}`:i;return r?[...n,r]:n}function nM(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 rM(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?"":K}];let o=s?[]:e.value.split(" "),a=(s?e.choices:nM(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${K}`:K}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function _b(e){if(e.entry==="text")return[{text:" ".repeat(eM),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(cf)}█ `,sgr:""}]:t}function iM(e){return e.reduce((t,n)=>t+Ge(n.text)+1,0)-1}function Wb(e,t){let n=[[]],r=0;for(let i of e){let s=Ge(i.text)>t?{...i,text:` …${Array.from(i.text).slice(-(t-2)).join("")}`}:i;if(r>0&&r+Ge(s.text)>t)n.push([]),r=0;n[n.length-1]?.push(s),r+=Ge(s.text)+1}return n}function Ub(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 jb(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 sM(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 oM(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((L)=>Ge(L.label))),c=Math.max(...r.settings.map((L)=>Ge(Ub(L)))),l=u+Math.max(...r.settings.map((L)=>iM(_b(L))))+c+5,f=Math.min(t-2,Math.max(48,l)),d=f-u-c-5,h=f-7,g=[!1,!0].map((L)=>({advanced:L,rows:Ds({settings:r.settings,advanced:L}).slice(0,-1)})),p=r.settings.map((L)=>Wb(_b(L),d).length),b=Math.max(...g.map((L)=>L.rows.reduce((R,J)=>R+p[J],0))),m=Math.max(...g.map((L)=>Tr(Gb({settings:r.settings,advanced:L.advanced}),h).length),...r.settings.map((L)=>Tr(L.about,h).length)),$=`${r.tag}: ${X.map((L)=>`${L.name} 0,000,000`).join(" · ")}`,k=r.tag?Math.max(Tr($,h).length,Tr(jb(r),h).length):0,M=b+m+k+8,w=Math.floor((t-f)/2),S=Math.max(1,Math.floor((n-1-M)/2)),y=`\x1B[7;${30+r.siteAnsi}m`;e[S]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let L=S+1;L<S+M-1;L++)e[L]?.put(w,`│${" ".repeat(f-2)}│`);let N=S+2;for(let L of Ds(r).slice(0,-1)){let R=r.settings[L],J=L===s;if(J)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,R.label,J?Qe:""),R.value!==R.default)e[N]?.right(w+f-3,[[Ub(R),K]]);Wb(rM(R,J,r.typing,r.siteAnsi),d).forEach((Ee,be)=>{let Y=w+u;for(let Le of Ee)Y=e[N+be].put(Y,Le.text,Le.sgr)+1}),N+=p[L]}let O=g.find((L)=>L.advanced!==r.advanced)?.rows??[],T=e[S+3+b];if(s===o)T.put(w+2,"▶",i);let A=T.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?y:Qe);if(O.some((L)=>r.settings[L]?.value!==r.settings[L]?.default))T.put(A+1,"•",K);e[S+5+b]?.put(w+2,"─".repeat(f-4),K),Tr(r.settings[s]?.about??Gb(r),h).forEach((L,R)=>{e[S+6+b+R]?.put(w+4,L)}),Tr(jb(r),h).forEach((L,R)=>{e[S+6+b+m+R]?.put(w+4,L,K)}),e[S+M-1]?.put(w,`╰${"─".repeat(f-2)}╯`);let{keys:C,right:_}=sM(r,r.settings[s]);Xs(e[n-1],t,i,{keys:C,right:_})}function aM(e,t,n,r,i){let s=r.tuning?XS:DS[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,d])=>Ge(d)+16))),a=s.map(([d,h])=>({label:d,parts:Tr(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,Qe);for(let g of h)e[f]?.put(c+13,g),f++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),Xs(e[n-1],t,i,{badge:"HELP",right:["? esc","close"]})}function uM(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)=>Ge(a.value))),o=Math.max(7,...i.map(Ge));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?Qe+n:""]]),l?.right(2+s+2+o,[[i[u],K]])})}function lf(e,t,n){let r=Array.from({length:n},()=>new Ja(t)),i=[],s=Ti(e.colors.cursor);if(rf=!1,t<Ar.cols||n<Ar.rows)return r[0]?.put(0,"ttheme find",Qe+s),r[1]?.put(0,`Needs ${Ar.cols}×${Ar.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",K),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")ZS(r,i,t,n,e,s);else o=VS(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 Ja(t);return uM(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 Ja(t);if(e.help)aM(r,t,n,e,s);else oM(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:rf}}var ff=5,cM=6,Db=0.05,lM=[1,2,3,4,5,6,9,10,11,12,13,14],ew=(e,t)=>(t-e+360)%360<=180?1:-1;function eo(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 xt(e,t,n){let r=0,i=t;if(eo(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(eo(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(eo(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function fM(e,t){let{l:n,c:r}=Je(e);return xt(n,r,(t+360)%360)}function dM(e,t,n){let{l:r,c:i,h:s}=Je(e),o=Ye(t)<0.18,a=(l)=>xt(o?r+(1-r)*l:r*(1-l),i,s);if(Ke(a(1),t)<n+Db)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let f=(u+c)/2;if(Ke(a(f),t)>=n+Db)c=f;else u=f}return a(c)}function hM(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(Ye(xt(u,r,i))<=t-0.005)s=u;else o=u}return xt(s,r,i)}function gM(e,t,n){let r=hn[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)=>Hn.every((h)=>{let g=(l>8?8:0)+h;if(g===l)return!0;let p=Je(e[g]);return p.c<Xi||Qt(p.h,f)>=Br+1||Math.abs(p.l-d)>=qr}),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(Qt(l,f)>Gt-ff||!n.has(t+8)&&!a(t+8,f,s.l))continue;let d=Qt(l,i.h)+Qt(f,s.h);if(d<c)c=d,u=[l,f]}}return u}class tw{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,fM(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Jr(this.theme)){let i=hn[Tn(n)];this.rehue(n,"ansi-role",i.center+ew(i.center,r)*(i.width-ff))}for(let{normal:n,gap:r}of gr(this.theme)){if(r<=Gt)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+ew(o,a)*(Gt-ff))}let t=zr(this.theme);for(let[n,r]of mr(this.theme)){let i=Tn(t.has(r)?n:r),s=gM(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(Ke(this.get(a),o)<s)this.set(a,r,dM(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",lM.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Ye(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",hM(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 Ya(e){let t=new tw(e);for(let n=0;n<cM;n++)if(t.readability(),t.roles(),pr(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:pr(t.theme)}}var to=[{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}],Qa={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},nw=(e,t,n)=>Math.min(n,Math.max(t,e));function rw(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:nw(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function xr(e){let t=(r,i,s)=>xt(nw(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 Hn){let i=hn[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 io=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],St=["Background","Foreground","Cursor","Selection"],eu=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],no=St.length+eu.length,Cr=[{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}],iw=5;function mM(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Hi(t).length>0}function Va(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function In(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function Za(e){if(e<St.length)return{name:St[e],about:io[e]};let t=e-St.length,n=eu[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var Xa=(e,t,n)=>Math.min(n,Math.max(t,e));function pM(e){return Xa(Math.round(e),0,255).toString(16).padStart(2,"0")}function sw(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)=>pM(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 xt(Xa(s,0,1),Number(i[3]),Number(i[4])%360)}return}function Da(e){let t=pt.find((n)=>n.rule===e);return t?.min??t?.max??0}function ro(e,t,n){let r=In(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function bM(e,t,n){let r=ro(e,t,n),i=(f)=>!n.includes(f),{background:s,foreground:o,selection:a,ansi:u}=In(e),c=new Set,l=(f,d,h,g)=>{if(i(g)&&Ke(d,h)<Da(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")&&Ye(u[0])>Da("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:f}of Jr(r))c.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of gr(r))if(d>Gt)c.add(4+f+8)}if(i("distinct"))for(let[f,d]of mr(r))c.add(4+f).add(4+d);return c}function Mn(e,t,n,r,i){let s=Ke(e,t),o=Da(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 ow(e,t,n,r){let i=In(e),s=ro(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce(($,k)=>Ke(i.ansi[$],i.background)<=Ke(i.ansi[k],i.background)?$:k);return[Mn(i.foreground,i.background,"foreground","Foreground on it",n),Mn(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),Mn(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[Mn(i.foreground,i.background,"foreground","On background",n),Mn(i.foreground,i.selection,"selection","On the selection",n)];if(r===2)return[{ok:void 0,text:`On background ${Ke(i.cursor,i.background).toFixed(2)}:1`}];if(r===3)return[Mn(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-St.length,a=i.ansi[o];if(o===0){let b=Ye(a),m=Da("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${b.toFixed(3)} · waived`}:{ok:b<=m,text:`Luminance ${b.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[Mn(a,i.background,"light-ansi","On background",n)];if(o===8)return[Mn(a,i.background,"ansi8-visible","On background",n)];let u=[Mn(a,i.background,"accents","On background",n)],c=Je(a),l=Tn(o),f=hn[l],d=`${f.name} ${f.center}±${f.width}°`;if(c.c<Xi)u.push({ok:void 0,text:"Too grey to have a hue"});else if(zr(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 b=Qt(c.h,f.center)-f.width;u.push(b>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${b.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${d}`})}let h=o<8?o+8:o-8,g=gr(s).find((b)=>b.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<=Gt,text:`${g.gap.toFixed(0)}° from ANSI ${h} · ≤ ${Gt}°`});let p=mr(s).flatMap(([b,m])=>b===o?[m]:m===o?[b]:[]);if(p.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${p.join(", ")} · within ${Br}° and ${qr} lightness`});return u}function aw(e,t,n){let r=An(ro(e,t,n));return pt.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 wM=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class df{mode;seeds=Qa;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=Va(e.colors??xr(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 In(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<St.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 bM(this.list,this.signature,this.waive)}failing(){return pr(ro(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(mM(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=sw(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=to.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=to[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:iw:1);this.seeds=rw(this.seeds,n,r),this.list=Va(xr(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"?no-1:1))%no,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:no-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:St.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=Cr.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=Cr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:iw:1))}else if(/^[0-9]$/.test(e)){let n=Cr[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=Cr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=Cr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:Xa(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=xt(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=sw(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=Va(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||wM.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Yt(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Je(t)}follow(){if(this.row<St.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:Xa(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=xt(r.l,r.c,r.h),this.col=1,this.notice=`${Za(t).name} follows ${Za(e).name.toLowerCase()}`}mark(){let e=io[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=ro(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=Ya({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=pr(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=Va({...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 gf=80,mf=24,tu=48,hf=11;function $M(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?zt(t):"",bg:(t)=>e?`\x1B[48;2;${Pe(t).join(";")}m`:""}}function kM(e){return Ye(e)>0.35?"#000000":"#ffffff"}function cw(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(kM(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function yM(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 eo(o.l,o.c,o.h)?xt(o.l,o.c,o.h):void 0})}function lw(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var uw={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 fw(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function dw(e,t,n){let r=aw(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=tu-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${fw(e,a.ok)} ${fn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function EM(e,t,n){let r=t.misses(),i=In(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(io[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Ke(i.foreground,i.selection):Ke(f,i.background),p=g===void 0?"":g.toFixed(1),b=r.has(l)?"✗":" ",$=`${e.color?`${e.fg(f)}${h}${d?e.fg(i.foreground):"\x1B[39m"} `:`${h} `}${f} ${p.padStart(4)}${b}`;return d?o(` ${$} `):` ${$} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<St.length;l++){let f=l===t.row,d=St[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=St.length;l<no;l++){let f=l===t.row,d=eu[l-St.length].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...dw(e,t,n-c.length)]}function vM(e,t,n){let r=In(t.list),i=[` ${e.dim("Seeds")}`];to.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:hf},(p,b)=>{let m=s.min+(s.max-s.min)*b/(hf-1);return uw[s.key](xr({...t.seeds,[s.key]:m}))}),l=cw(e,c,lw(u,s.min,s.max,hf),a),f=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),d=uw[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 Ve("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.",tu-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...dw(e,t,n-i.length)]}function hw(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} ${nt(f,n-2)} ${e.color?"\x1B[0m":""}`)}function SM(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}=Za(i),f=t.signature.includes(io[i]),d=[fn(`${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,[p,b,m]=Pe(s),$=g??`${e.bold(s)}${u!==s?e.dim(` was ${e.color?`${e.fg(u)}■\x1B[39m `:""}${u}`):""}`;d.push(`${h}${$}`),d.push(`${h}${e.dim(`rgb ${p} ${b} ${m}`)}`),d.push(`${h}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let k=Math.max(8,Math.min(64,n-12));Cr.forEach((S,y)=>{let N=t.mode==="tune"&&y===t.channel,O=o[S.key],T=`${O.toFixed(S.digits)}${S.wraps?"°":""}`.padStart(6),A=cw(e,yM(o,S,k),lw(O,S.min,S.max,k),N),C=S.key.toUpperCase();d.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${A} ${N?e.bold(T):e.dim(T)}`)}),d.push("");let M=ow(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 S of M)Ve(S.text,n-2).forEach((y,N)=>{d.push(`${N===0?fw(e,S.ok):" "} ${S.ok===!1?y:e.dim(y)}`)});let w=r-d.length-1;if(w>=3)d.push("",...hw(e,In(t.shown()),n).slice(0,w));return d}function MM(e,t,n,r){return[fn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...hw(e,In(t.list),n).slice(0,r-2)]}var IM=[["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 NM(e,t,n){let r=[` ${e.bold("Help")}`,""];for(let[i,s]of IM.filter(([o])=>o!=="Pictures"||t.options.find))Ve(s,n-16).forEach((o,a)=>{r.push(` ${e.bold((a===0?i:"").padEnd(11))} ${o}`)});return r}function PM(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=[fn(` ${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,p=e.color?`${e.bg(g.background)} ${[...g.ansi].map(($)=>`${e.fg($)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",b=h?"▌ ":" ",m=f.name.padEnd(l);a.push(`${b}${h?e.bold(m):m} ${p}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function OM(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?fn(f,c,n):nt(f,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function FM(e,t,n,r){let i=$M(r);if(t<gf||n<mf){let g=[i.bold("ttheme palette editor"),`Needs ${gf}×${mf} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(p,b)=>nt(g[b]??"",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=NM(i,e,t);else if(e.overlay==="open")d=PM(i,e,t,f);else{let g=t-tu-2,p=e.mode==="seeds"?vM(i,e,f):EM(i,e,f),b=e.mode==="seeds"?MM(i,e,g,f):SM(i,e,g,f);d=Array.from({length:f},(m,$)=>`${nt(p[$]??"",tu)}${i.dim("│")} ${nt(b[$]??"",g)}`)}let h=[fn(l,u,t),""];for(let g=0;g<f;g++)h.push(nt(d[g]??"",t));return h.push("",OM(i,e,t)),h}async function gw(e,t){let n=new df(e),{stdin:r,stdout:i}=process,s=i.columns||gf,o=i.rows||mf,a=[],u=[],c="",l,f=(k)=>i.write(k),d=()=>{l=void 0;let k="";if(n.shown().forEach((M,w)=>{if(u[w]!==M&&t.only?.includes(w))k+=Bc(w,M),u[w]=M}),k)f(k)},h=()=>{let k=FM(n,s,o,t.color),M="";if(k.forEach((w,S)=>{if(a[S]!==w)M+=`\x1B[${S+1};1H\x1B[0m\x1B[2K${w}`}),a=k,M)f(`\x1B[?2026h${M}\x1B[0m\x1B[?2026l`);if(t.only)l??=setTimeout(d,33)},g,p,b=!1,m=()=>{f(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${mi}`),r.setRawMode(!0),r.resume()},$=(k)=>{if(g&&p)r[k?"on":"off"]("data",g),i[k?"on":"off"]("resize",p)};m();try{return await new Promise((k)=>{let M=async(w)=>{let S=e.find;if(!S)return;b=!0,$(!1),clearTimeout(l),l=void 0;try{n.found(await S(n.edited(),w))}catch(y){n.notice=y instanceof Error?y.message:String(y)}b=!1,m(),$(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,h()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],f(mi),h()},g=(w)=>{c+=w.toString("utf8");let S=Ka(c);c=S.pending;for(let N of S.events)if(N.kind==="paste")n.paste(N.text);if(S.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(S.keys)&&n.typing===void 0)n.paste(S.keys);else for(let N of qa(S.keys))if(n.press(N),n.result||n.wants)break;if(n.result){k(n.result==="saved"?n.edited():void 0);return}let y=n.wants;if(y&&!b){n.wants=void 0,M(y.start);return}h()},$(!0),h()})}finally{clearTimeout(l),$(!1),r.setRawMode(!1),r.pause(),f("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as QM}from"node:child_process";import{createHash as Lw}from"node:crypto";import{existsSync as Ci,mkdirSync as VM,mkdtempSync as ZM,readFileSync as xw,rmSync as so,statSync as XM}from"node:fs";import{homedir as DM,tmpdir as eI}from"node:os";import{dirname as tI,join as Bt}from"node:path";import{pathToFileURL as Sw}from"node:url";var RM=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),HM=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),TM=0.04,AM=0.1,LM=0.05,xM=4096;function CM(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function GM(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...CM(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)+([...RM].some((l)=>o.has(l))?-3:0)+([...HM].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:GM(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 pw(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 pf(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function mw(e,t,n){let[r,i,s]=[pf(e),pf(t),pf(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 bw(e,t){let n=t.map((o)=>mw(...Pe(o))).filter(([,o,a])=>Math.hypot(o,a)>=TM);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/xM))),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]=mw(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([d,h,g],p)=>{if(Math.hypot(c-d,l-h,f-g)<AM)i[p]=i[p]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/LM),0)/n.length}import{mkdirSync as jM,readFileSync as wf,writeFileSync as Ew}from"node:fs";import{dirname as KM}from"node:path";import{isMainThread as JM,parentPort as vw,Worker as BM}from"node:worker_threads";var _M=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,WM=[[/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 bf(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 ww(e,t){let n=_M.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...WM.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function $w(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 kw(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,p=e.data[g+3]/255,b=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=b*p+255*(1-p)}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 UM(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function yw(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&&UM(e.hash,t.hash)<=2}var qM={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},ru;async function zM(e){if(e.job==="redraw")return qp(e.home,e.name,e.key,e.hue,e.blur,e.aligns,e.user);if(e.job==="show"){if(ru?.from!==e.from){let s=Gn(new Uint8Array(wf(e.from)),wt);ru={from:e.from,clear:gn(s),inked:vc(s)}}let{image:r,fill:i}=Qg(ru.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune);return jM(KM(e.to),{recursive:!0}),Ew(e.to,Ro(r)),{clear:ru.clear,fill:i}}let t=Gn(new Uint8Array(wf(e.from)),wt);if(e.job==="backdrop"){ea(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(wf(e.source)),cut:e.from!==e.source},e,e.blur);let r=e.tune&&Ht(e.home,e.colors.name).find((i)=>i.key===ft(e.origin));if(e.tune&&r)$s(Te(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:bw(t,e.colors),hash:kw(t)};if(e.job==="thumb")return Z(e.to,Ro(Bh(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return Ew(e.to,Ro({width:t.width,height:e.height,data:n})),0}function YM(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await zM(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class $f{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 BM(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 kf{lines=new Map;run(e){let t=qM[e.job],n=this.lines.get(t);if(!n)n=new $f,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class yf{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new $f)}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(!JM&&vw)YM(vw);var Gr=[{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:Dr,multi:{read:yr}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:$r,multi:{read:ti,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"]},...Mi()?[{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:lg,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:fg,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:ls},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:uc,multi:{read:Co,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 Mw(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 fs(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var nI=["fit","newest","score"];function Ef(e){return nI.find((t)=>t===e)??"fit"}var rI={left:-1,right:1,"shift-left":-10,"shift-right":10};function iI(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 vf=iI(process.env.TTHEME_BG_MARGIN);function sI(e,t,n){if(t<0){if(e!=="fill")return Math.max(Fw,e+t);if(!n)return e;return Math.max(Fw,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function Cw(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function oI(e,t){if(Cw(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:$t[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function aI(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var Iw=12,uI=4,cI=150,lI=300,Nw=12,fI=2,dI=150,hI=30,gI=4000,mI=8000,Pw=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,pI=process.platform==="win32"?"alt+v":"ctrl+v",Ow=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",bI=1280,wI=16,$I=$t.indexOf("top-right")+1,Fw=20,oo=2147483645,ao=2147483646,Rw=-1073741827,kI=-1073741828,Hw=2,yI=80,EI=16,vI=0.4,SI=3221225472,MI=256,II=3,NI=8;function iu(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 uo(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return uo(e.errors[0]);if(e.cause)return uo(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 Sf(e,t){return`${e}: ${uo(t)}`}function Tw(e){return e.width*e.height}function Aw(e,t){return`${e}-${Lw("sha1").update(t).digest("hex").slice(0,8)}`}function PI(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function OI(e,t){try{return JSON.parse(xw(Bt(Xt(e),t),"utf8"))}catch{return{}}}function FI(e,t,n){Z(Bt(Xt(e),t),`${JSON.stringify(n)}
506
- `)}class Mf{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(Gr.map((e)=>[e.name,Mw(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 kf;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=Wm(process.env);bandFiles=new Map;nextBand=SI;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new nf((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=ZM(Bt(eI(),"ttheme-find-"));home;catalog;entry;blurring;start;constructor(e,t,n,r,i){this.start=i,this.home=e,this.catalog=t,this.entry=n,this.tone=ai(n,n.signatureSlots),this.blurring=wi(e);let s={size:"fill",at:$I,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:Ef(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:yr(this.setting("TTHEME_FIND_RATING")),block:ti(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:ls(this.setting("TTHEME_FIND_SITES")),hide:Co(this.setting("TTHEME_FIND_HIDE")),hideTags:fs(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Gr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:Mw(o,Vc(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,Tt.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=iu(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??uI}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 lc(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 Bt(Xt(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=_o(e.site,e.post);return Bt(Xt(e.site),"thumb",`${Aw(e.post.id,t)}.${Kn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Rt(n,r.id),s=Zt(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===Hr?"":n.pageUrl(r.id),artist:n===Hr?Ib(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${mi}`);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\\${mi}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),so(this.scratch,{recursive:!0,force:!0}),Sg(),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(Kb)})}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=Ka(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),PI(this.typed)){this.partial=setTimeout(this.flushKeys,hI);return}this.flushKeys()};flushKeys=()=>{let e=qa(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!Go(t,this.site??X[0]);return Hi(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 — ${Ow}`);return}this.pasted(e.text);return}await this.bring(()=>Ua(e.bytes,e.source))}notice(e,t=gI){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 Rb()}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 · ${pI} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},mI),this.draw()}async fromClipboard(){let e=this.view;if(tf()){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 Fb(Bt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${uo(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await ef(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${Ow}`);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=Go(t,this.site??X[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Hi(t).sort((i,s)=>Number(!Pw.test(i))-Number(!Pw.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)=>ef(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(uo(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=Pb(i.bytes);Nb(s,i.source);let o=this.origPath(Hr,s,i.ext);Z(o,i.bytes);let a=Sw(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:Lw("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Hr,post:u},l=this.previewPath(c);Z(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=iu(`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(Rt(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)=>jn(i)>jn(r)?i:r),t=Math.ceil((jn(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<Ar.cols||this.rows<Ar.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}=Lr(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=Ds(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=Ds(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=Xb(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(Gr[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":fs(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<cf:/^[\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),lI)}pending(){let e=(t)=>this.view.settings[Gr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Ef(e("TTHEME_FIND_ORDER")),rating:yr(e("TTHEME_FIND_RATING")),narrow:lc(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:ls(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 gc(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=Gr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Gr[i];if(s)this.values.set(s.name,r.value)});let n=Gr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=yr(this.setting("TTHEME_FIND_RATING")),e.block=ti(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=Ef(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=ls(this.setting("TTHEME_FIND_SITES")),e.hide=Co(this.setting("TTHEME_FIND_HIDE")),e.hideTags=fs(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=Bt(this.home,"ttheme","config.zsh");try{let n=Ci(t)?xw(t,"utf8"):"";return Z(t,e.reduce((r,[i,s])=>Jm(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(!aI(t)){e.suggest=void 0;return}let n=[...new Map(Nm(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,II);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Ig(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,NI),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},cI)}async commit(e){let t=Go(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=iu(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await ds(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(Rt(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{QM(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=rI[e];if(i!==void 0){if(n.field===0)r.size=sI(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=Eg(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=hs(n.source),a=/^https?:\/\//i.test(o)?o:t===Hr&&o.startsWith("/")?Sw(o).href:void 0;return{page:t===Hr?"":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:(Zt(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}=Lr(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=Lr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Be.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)*vI)),this.draw(),this.gliding=setTimeout(t,EI)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Be.height}prebake(){let e=this.view;for(let t of lf({...e,scroll:e.top*Be.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?Pm(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(hc([...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=iu(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=hc(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})=>gc(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=Sf(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,Sf(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=Lr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+Hw)*e}need(){let{perRow:e,rowsVis:t}=Lr(this.cols,this.rows);return(t+Hw)*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=Mg(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===Ft?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{Bo(n,await qo(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<Un;let c=e.last.get(a);for(let l of u){let f=c&&$w(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:f};let d=Rt(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,...ww(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?pw(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(Rt(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=bf(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++,Tw(r.post)<=Tw(s.post))continue;for(let a of[...i,...bf(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(Rt(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:Nw},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Rt(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=_o(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<Iw&&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<Iw&&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=Zt(t);if(!Uo(e,t,this.view.rating)||Wo(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"||yg(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=OI(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 zo(e,t,this.signal),s=ni(e,t),o=(i===void 0?await Ng(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)FI(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Rt(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)=>yw(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(!Jo(n,r))return Promise.resolve();let i=Rt(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 Ko(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}gs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=rm(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 ds(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=vg(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(Ci(t))return XM(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await Yo(e,n,this.signal,r);return Z(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<Nw&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Rt(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Be.cols*this.cell.w,i=Be.rows*this.cell.h,s=_o(t,n),o=Bt(Xt(t),"tile",`${Aw(n.id,s.url)}-${r}x${i}.png`);if(!Ci(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(Rt(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),dI),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),!Zt(n.post))return;let{site:i}=n,s=this.board;try{await zo(i,n.post,r.signal);let o=Zt(n.post),a=this.origPath(i,e.id,o.ext);if(!Ci(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=ni(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&&Mi()&&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&&Fa(d.clear))l.using="cut";else so(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=Sf(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=Bt(Xt(e),"cut",`${t}.png`);if(Ci(i))return i;try{return VM(tI(i),{recursive:!0}),await xs(n,i,r),i}catch{so(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>=fI||!r||!Zt(r.post))continue;let{site:i,post:s}=r;this.prefetching++,zo(i,s,this.signal).then(async()=>{let o=Zt(s),a=this.origPath(i,s.id,o.ext),u=ni(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,bI),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!Cw(o,this.view.untuned),u=a?`-${o.size}-${o.at}-${Math.round(o.opacity*100)}`:"",c=Bt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}${u}.png`),l=`${e.site.key}:${e.id}:${t}:${i}x${s}`,f=this.clarity.get(l);if(f&&Ci(c))return e.fill=f.fill,{clear:f.clear,path:c};let d=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:c,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/Ec(n,r).width,...a?{tune:o}:{}});if(this.clarity.set(l,d),e.fill=d.fill,a)this.keepTuned(c);return{clear:d.clear,path:c}}keepTuned(e){this.tunedFiles.push(e);while(this.tunedFiles.length>wI){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;so(this.tunedFiles.splice(t,1)[0],{force:!0})}}async present(){let e=this.current;if(!e)return;let t=e.using,{clear:n,path:r}=await this.render(e,t);if(this.current!==e||e.using!==t)return;if(this.view.tuning&&e.fill)this.view.tuning.fill=e.fill;this.view.shown={id:e.key,clear:n,bytes:e.size,path:r,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;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=oI(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:hs(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,...r?{tune:r,aligns:Si(ce(this.home).terminals),user:DM()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),Lt(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${$t[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=lf(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)t+=Jb(s),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)t+=Bb(s,this.cell),this.placed.set(s.id,o)}for(let i of this.sent.keys())if(!n.has(i))t+=qb(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.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(Pe(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${oo},q=2;${n}\x1B\\`,vf)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${ao},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${ao},p=${ao},c=1,r=1,C=1,z=${kI},q=2\x1B\\`}if(this.covered=e,vf){let{x:n,y:r}=vf;return`${t}\x1B_Ga=p,i=${oo},p=${oo},P=${ao},Q=${ao},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${Rw},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${oo},p=${oo},c=${this.cols},r=${this.rows},C=1,z=${Rw},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()},yI);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:Bt(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<=MI)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),so(t.path,{force:!0})}}}async function Gw(e,t,n){let r=new Mf(e,yn(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function _w(e){let t=ge(),n=yn(t),r=Ir(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Mf(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
507
- `),0;return s}function Ww(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Uw(e,t){if(e.includes("/"))return e;let n=Mr(t,!1),r=n.filter((s)=>Zn(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function TI(e,t,n){let r=ce(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)un(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))gt(e,t,r);return{state:r,fresh:i}}function AI(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 jw(e,t,n){let r=$m(t),i=Ut(Et(r.name,Ac(r),n.palettes)),s=je(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 ${ve(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)ua(e,[...kn(e),i]);return i.name}var LI=["background","foreground","cursor"];function Kw(e){try{e();return}catch(t){return t.message}}function Jw(e,t,n){return je(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 Bw(e,t){let n=new Set(Ht(e,t).map((r)=>r.key));return{count:()=>Ht(e,t).length,added:()=>Ht(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(Ra(e,t)??[]).filter((r)=>!n.has(ft(r))),discard:()=>{let r=Ht(e,t).filter((i)=>!n.has(i.key));for(let i of r)ci(e,t,i.key),Do(e,t);if(r.length>0)Lt(e)}}}function xI(...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 qw(e,t,n,r){if(!_m(process.env))return;return async(i,s)=>{let o=Ut(Et(t,r(i),n.palettes)),{saved:a}=await Gw(e,o,s);return{...a?{note:a}:{},count:Ht(e,t).length}}}async function zw(e){let t=rr(process.env,process.stdout.isTTY===!0),n=t?await t.saved():new Map;try{return await gw(e,{color:!At(),...t?{only:t.slots}:{}})}finally{if(t)process.stdout.write(t.restore(n))}}async function Yw(e,t,n){let r=ge(),i=We(r),s=await db(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=en(o);if(a)throw Error(`${o} ${a}`);if(ve(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=Hc(r,o);if(co(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?Ir(je(r,i).palettes,t):void 0;if(!Ww())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(ve(c.name)?c.base:c.default?void 0:c.name),f=c?Tc(c,o,`kept from ${c.name}`):void 0,d=c?Ra(r,c.name)??c.pictures:void 0,{base:h,ansiSource:g,group:p,...b}=f??{name:o,signature:LI,...xr(Qa)},m=Bw(r,o),$=({colors:w,signature:S})=>{let y=xI(d,m.fresh());return Ac({...b,...w,signature:S,...l?{base:l}:{},...y?{pictures:y}:{}})},k=await zw({title:"New palette",name:o,...f?{colors:f}:{},signature:b.signature,...b.waive?{waive:b.waive}:{},palettes:Jw(r,i,o),pictures:m.count(),find:qw(r,o,i,$),check:(w)=>Kw(()=>Et(o,$(w),i.palettes))});if(!k){m.discard(),console.log("Nothing made");return}RI(HI(u),{recursive:!0}),Z(u,$(k));let{state:M}=TI(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
508
- ${u}`),await vn(r,je(r,i).palettes.filter((w)=>w.name===o),M.terminals),console.log(`
509
- \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function CI(e,t,n){let r=Ut(Et(e,t,n.palettes));return Ms(r).length>0?vs(r).filter((i)=>i.startsWith(" ✗")):[]}async function Qw(e){let t=ge(),n=We(t),r=ce(t),i=je(t,n,!1),s=Uw(e,t),o=su(t,s),a=o&&co(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=su(t,a);if(!u||!co(u)){let m=i.palettes.some(($)=>$.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(!Ww())throw Error("edit opens the palette editor — run it in a terminal");let c=If(u,"utf8"),l;try{l=Et(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let f=Bw(t,a),d=new Set((l.pictures??[]).map((m)=>ft(m))),h=({colors:m,signature:$})=>mm(km(xc(c,m),$),f.fresh().filter((k)=>!d.has(ft(k)))),g=await zw({title:"Edit palette",name:a,colors:Lc(l),signature:l.signatureSlots,waive:l.waive,palettes:Jw(t,n,a),pictures:f.count(),find:qw(t,a,n,h),check:(m)=>Kw(()=>Et(a,h(m),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let p=h(g);if(p===c){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(Z(u,p),r.palettes.includes(a))gt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let b=CI(a,p,n);if(b.length>0)console.log(`
504
+ }`;async function Vb(){if(gf())return;if(process.platform==="darwin"){let[e="",t=""]=(await ln("osascript",["-l","JavaScript","-e",GM])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Yb()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await ln("wl-paste",["--list-types"])).stdout:(await ln("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function Va(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:WM(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 WM(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 Ds=(e)=>Buffer.from(e).toString("base64"),ff=(e)=>Buffer.from(e,"base64");function Wb(e,t){return t.find((n)=>e.includes(n))}class mf{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=Ds(Ub("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;${lf.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=${Ds("ttheme")}:pw=${this.pw};${Ds(".")}\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?ff(e.mime).toString("utf8"):r.mime,t)r.chunks.push(ff(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=Wb(s,[...df,...HM]);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=${Ds(u)}:pw=${a};${Ds(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=lf.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=Wb(a,lf);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(ff(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"?Ai(a).find((c)=>MM(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(Qa(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}var Be={pitch:25,cols:22,rows:9,height:13},Gr={cols:25,rows:16},UM=2147483648,jM=-1073741826,KM=1600,Zb=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],JM=56,BM=4,Xb=20,qM=50,Db=[["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"]],zM="\x1B[0m",Qe="\x1B[1m",K="\x1B[2m",no="\x1B[32m",fn="\x1B[33m",YM={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 Da(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(YM[`${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===`
505
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var uw="\x1B]1337;ReportCellSize\x07\x1B[16t",ew="\x1B]1337;ReportCellSize=";function kf(e){let t=e.indexOf(ew);if(t!==-1){let i=e.slice(t+ew.length),s=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),o=s.length>0?Math.min(...s):-1,a=o===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,o));if(a){let u=Number(a[3]);return{cell:{h:Math.round(Number(a[1])*u),w:Math.round(Number(a[2])*u)},rest:e.slice(0,t)+i.slice(o+(i[o]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)}}function Wr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Be.pitch)),rowsVis:Math.max(1,Math.floor(n/Be.height)),height:n}}function cw(e){return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`}function lw(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 fw(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function xi(e){return`\x1B[38;2;${Me(e).join(";")}m`}function Xa(e){return`\x1B[48;2;${Me(e).join(";")}m`}var pf=!1;function eu(e){return pf=!0,e.beat}function Li(e){return Zb[eu(e)%Zb.length]}function _e(e){return $e(e)}function dw(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 Ci(e){return`\x1B[${30+e}m`}function _i(e,t,n,r){return n?[[`${Xi} `,r],[e,t,n]]:[[e,t]]}function bf(e){return e.reduce((t,[n])=>t+_e(n),0)}function QM(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([`${dw(i,r)}…`,s,o]);break}return n}class Za{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=dw(n,this.cols-t);e+=`\x1B[${t+1}G${r}${Fo(s,i)}${r?zM:""}`}return e}}function VM(e){return e.replace(/_\([^)]*\)?$/,"")}function hw(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<KM?fn:K]}function ro(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[bf(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=QM(s,Math.max(0,bf(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,Qe],[` ${f}`,K]])].forEach((l,f)=>{u=e.run(u+(f?3:0),l)}),o)e.right(t,[[o[0],Qe],[` ${o[1]}`,K]])}function ZM(e,t){if(e==="d")return K;if(e==="b")return Qe;if(e==="s")return Xa(t.colors.selection);if(e==="c")return Xa(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 XM(e,t,n,r,i){let s=At.indexOf(pa(r.scene)),o=At.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Qe+i:K]]),a=o.reduce((u,[c])=>u+_e(c),0)<=n;e?.run(t,a?o:[[pa(r.scene).name,Qe+i],[` ${s+1}/${At.length}`,K]])}function DM(e,t,n,r,i,s,o){let{ansi:a,cursor:u}=s.colors;XM(e[t-2],n,r,s,o);let c=r<Zm?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),xi(a[d]??u)+Xa(a[d+8]??u))??l)+1;let f=t+2;for(let d of pa(s.scene).lines){let h=Xm(d,r);if(!h)continue;if(f>i)return;e[f]?.run(n,h.map(([g,p])=>[g,ZM(p,s)])),f++}}function eS(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 tw(e){return e.replace(/^https?:\/\/(?:www\.)?/,"")}function tS(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Ci(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?_i(tw(s.page),"",s.page,a):[["—",K]]],["Source",s?.source?_i(tw(s.source),"",s.link,i):[["—",K]]],["Artist",[o.length>0?[o.join(" "),""]:["—",K]]]].forEach(([c,l],f)=>{e[t+f]?.put(n,c,K),e[t+f]?.run(n+12,l)})}function nS(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?[Aa(u.bytes)]:[]].join(" · "),d=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),h=(b,m)=>b.length>0?eS(b,l,m).map(($)=>[[$,""]]):[[["—",K]]],g=[["Characters",h(o.characters,2)],["Series",h(o.series,1)],["Tags",h(o.tags,3)],["Rating",[[[d,d==="—"?K:""]]]],["File",[[[f,""],...u?[[" ",""]]:[],...u?gw(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",K]]]]],p=t;for(let[b,m]of g){if(p+m.length-1>i)return;e[p]?.put(n,b,K);for(let $ of m)e[p]?.run(c,$),p++}}var rS=["Size","Position","Opacity"],iS=[0,3,6];function sS(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 oS(e){return e.toFixed(2)}function aS(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,Qe+s],[" Background",K],...a?[[" · ",K],..._i(`${a.site} ${a.id}`,K,a.page||void 0,Ci(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[f,d]of rS.entries()){let h=t+iS[f],g=o.field===f,p=g?Qe:K;if(g)e[h]?.put(n,"▶",s);e[h]?.put(n+2,d,p);let b;if(f===1){for(let m=1;m<=9;m++){let $=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,$?"■":"·",$?Qe+s:K)}b=$t[i.tune.at-1]??"center"}else{let m;if(f===0){let{size:$}=i.tune;m=$==="fill"?u-1:Math.floor(($-c)*(u-1)/(l-c+1)),b=$==="fill"?"fill":`${$}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),b=oS(i.tune.opacity);m=Math.max(0,Math.min(u-1,m)),e[h]?.run(n+12,[["━".repeat(m),s],["●",Qe],["─".repeat(u-1-m),K]])}if(e[h]?.right(r-2,[[b,p]]),sS(i,f))e[h]?.put(r-1,"↺",g?Qe+s:K)}}function uS(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 wf(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function to(e){return`${X[Math.floor(e/Bn)]?.name??"local"} ${e%Bn}`}function eo(e,t,n){let r=X[Math.floor(t/Bn)],i=to(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],..._i(i,n,r.pageUrl(t%Bn),Ci(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function cS(e,t,n){let r=[{name:"all",moved:!1},...X].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?wf(n,a):[` ${a} `,K];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+_e(o),0)<=t;e.run(0,i?r:[wf(n)])}function lS(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"}`,K);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":K]]),s=yr.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(" ")}`,K),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,K]);e.right(t,u)}}function gw(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,no]];if(e.cut==="off")return[["Opaque · x cuts out",fn]];if(e.cut==="failed")return[["Opaque · no cut-out",fn]];return[e.clear>0?[`${e.clear}% transparent`,no]:["Opaque",fn]]}function nw(e){return e.site==="all"?"any site":e.site}function $f(e,t){if(e.installing!==void 0)return eo(`${Li(e)} Installing ${e.palette} ← ${to(e.installing)}`,e.installing,fn);if(e.hint)return[[e.hint,no]];if(e.error)return[[e.error,fn]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,fn]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return eo(`${Li(e)} Fetching ${to(n)} · ${xa(r,i)}`,n,fn)}if(e.cutting!==void 0)return eo(`${Li(e)} Cutting out ${to(e.cutting)}`,e.cutting,fn);if(e.preparing!==void 0)return eo(`${Li(e)} Preparing ${to(e.preparing)}`,e.preparing,fn);if(t)return[t];if(e.saved)return eo(e.saved.text,e.saved.key,no);if(e.note)return[[e.note,K]];return}function mw(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 pw(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function fS(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=eu(r)%(Xb*2)/Xb,d=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(f<1?f:2-f)))),h=rt(s,o,i),g=rt(s,rt(a,s,0.15),i),p=Array.from({length:n},(m,$)=>{let k=(c>=0?$<c:$>=d&&$<d+l)?h:g;return $===0||$===n-1?rt(k,s,0.55):k}),b=0;for(let m=1;m<=n;m++)if(m===n||p[m]!==p[b])e?.put(t+b," ".repeat(m-b),Xa(p[b])),b=m}function dS(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(eu(i)-i.loaderFrom)/BM),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[mw(i),Qe+xi(rt(s,o,a))],[pw(i," "),xi(rt(s,rt(o,s,0.45),a))]]);let c=Math.min(JM,r-8);if(fS(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?[[" · ",xi(rt(s,o,0.25*a))]]:[],[l,xi(rt(s,f?rt(o,s,0.2):o,f?a:0.32*a))]]))}function hS(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:K)}}function gS(e,t,n){if(t)return[`${Li(e)} ${mw(e)}${pw(e," · ")}`,K];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Li(e)} Loading thumbnails · ${i}/${r.length}`,K]:void 0}function mS(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=Wr(n,r);lS(e[0],n,i,s),cS(e[1],n,i);let c=e.map((y,N)=>N>=2&&N<2+u?y:void 0),l=Math.floor(i.scroll/Be.height),f=Math.floor((i.scroll+u-1)/Be.height),d=[];for(let y=l;y<=f;y++){let N=2+y*Be.height-i.scroll;for(let O=0;O<o;O++){let T=y*o+O,A=O*Be.pitch,C=i.tiles[T];if(!C)continue;d.push(C);let G=T===i.focus;if(G)uS(c,N,A,Be.height,Be.pitch-1,s);let x=N+1,F=Math.max(x,2),J=Math.min(x+Be.rows,2+u);if(C.thumb&&J>F)t.push({id:C.key,path:C.thumb,row:F,col:A+1,cols:Be.cols,rows:J-F,...J-F<Be.rows?{crop:F-x}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",no]]:[],...C.page||i.site!=="all"?_i(String(C.id),G?Qe:"",C.page||void 0,Ci(C.siteAnsi)):[["● ",Ci(C.siteAnsi)],[String(C.id),G?Qe:""]],[" ",""],hw(C)],be=Be.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(A+1,bf(Ee)>be?Ee.map(([xe,de,ae])=>[xe.replace(/^(\S) $/,"$1"),de,ae]):Ee),C.mates.length>0)c[N+10]?.put(A+Be.cols,"≈",s);c[N+11]?.put(A+1,C.artist?VM(C.artist).slice(0,Be.cols-8):"—",K);let Y=[];if(C.score>0)Y.push([`★${C.score}`,K]);if(C.variants>1)Y.push([` ×${C.variants}`,s]);if(Y.length>0)c[N+11]?.right(A+Be.cols+1,Y)}}let h=Math.ceil(i.tiles.length/o)*Be.height;hS(e,n,i,u,h,s);let g=Math.max(2,2+h-i.scroll),p=2+u-g,b=i.searching&&p>=2;if(b)dS(c,g,p,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[y,N]=Db[Math.floor(eu(i)/qM)%Db.length];e[r-2]?.run(0,[["Tip ",K],[y,Qe],[` ${N}`,K]])}let $=i.top*o,k=i.tiles.length-(i.top+a)*o,S=[...$>0?[`↑ ${$} above`]:[],...k>0?[`↓ ${k} more`]:[]];if(S.length>0)e[r-2]?.put(0,S.join(" "),K);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 ${nw(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${nw(i)} — tab tries ${i.nextSite}`,K);let w=gS(i,b,d),M=$f(i,w);return ro(e[r-1],n,s,{badge:"IMAGE SEARCH",lead:M,keys:m&&M?.[0]===w?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:["esc","back"]}),b}function pS(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=[wf(i,o.site,o.siteAnsi),[" ",""],..._i(String(o.id),Qe,o.page||void 0,Ci(o.siteAnsi)),[" ",""],hw(o)];if(o.score>0)u.push([` · ★${o.score}`,K]);if(a)u.push([` · ${Aa(a.bytes)}`,K]);if(a)u.push([" ",""],...gw(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),K]]);if(tS(e,1,2,i,s),i.tuning)aS(e,8,2,2+Math.min(n-4,60),i,s);else if(i.details)nS(e,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else DM(e,7,2,n-4,r-2,i,s);if(i.shown)t.push({id:UM+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:jM});if(i.tuning){ro(e[r-1],n,s,{badge:"IMAGE EDIT",lead:$f(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["enter","keep"]],right:["esc","undo"]});return}let c=$f(i);ro(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 bS=[["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"]],wS={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",`⇧←→ ${At.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"]]},yf=6,$S=24;function io(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function kS(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function rw(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>kS(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function bw(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 _r(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 yS(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 ES(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?"":K}];let o=s?[]:e.value.split(" "),a=(s?e.choices:yS(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${K}`:K}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function iw(e){if(e.entry==="text")return[{text:" ".repeat($S),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(yf)}█ `,sgr:""}]:t}function vS(e){return e.reduce((t,n)=>t+_e(n.text)+1,0)-1}function sw(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 ow(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 aw(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 MS(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 SS(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((x)=>_e(x.label))),c=Math.max(...r.settings.map((x)=>_e(ow(x)))),l=u+Math.max(...r.settings.map((x)=>vS(iw(x))))+c+5,f=Math.min(t-2,Math.max(48,l)),d=f-u-c-5,h=f-7,g=[!1,!0].map((x)=>({advanced:x,rows:io({settings:r.settings,advanced:x}).slice(0,-1)})),p=r.settings.map((x)=>sw(iw(x),d).length),b=Math.max(...g.map((x)=>x.rows.reduce((F,J)=>F+p[J],0))),m=Math.max(...g.map((x)=>_r(rw({settings:r.settings,advanced:x.advanced}),h).length),...r.settings.map((x)=>_r(x.about,h).length)),$=`${r.tag}: ${X.map((x)=>`${x.name} 0,000,000`).join(" · ")}`,k=r.tag?Math.max(_r($,h).length,_r(aw(r),h).length):0,S=b+m+k+8,w=Math.floor((t-f)/2),M=Math.max(1,Math.floor((n-1-S)/2)),y=`\x1B[7;${30+r.siteAnsi}m`;e[M]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let x=M+1;x<M+S-1;x++)e[x]?.put(w,`│${" ".repeat(f-2)}│`);let N=M+2;for(let x of io(r).slice(0,-1)){let F=r.settings[x],J=x===s;if(J)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,F.label,J?Qe:""),F.value!==F.default)e[N]?.right(w+f-3,[[ow(F),K]]);sw(ES(F,J,r.typing,r.siteAnsi),d).forEach((Ee,be)=>{let Y=w+u;for(let xe of Ee)Y=e[N+be].put(Y,xe.text,xe.sgr)+1}),N+=p[x]}let O=g.find((x)=>x.advanced!==r.advanced)?.rows??[],T=e[M+3+b];if(s===o)T.put(w+2,"▶",i);let A=T.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?y:Qe);if(O.some((x)=>r.settings[x]?.value!==r.settings[x]?.default))T.put(A+1,"•",K);e[M+5+b]?.put(w+2,"─".repeat(f-4),K),_r(r.settings[s]?.about??rw(r),h).forEach((x,F)=>{e[M+6+b+F]?.put(w+4,x)}),_r(aw(r),h).forEach((x,F)=>{e[M+6+b+m+F]?.put(w+4,x,K)}),e[M+S-1]?.put(w,`╰${"─".repeat(f-2)}╯`);let{keys:C,right:G}=MS(r,r.settings[s]);ro(e[n-1],t,i,{keys:C,right:G})}function IS(e,t,n,r,i){let s=r.tuning?bS:wS[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,d])=>_e(d)+16))),a=s.map(([d,h])=>({label:d,parts:_r(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,Qe);for(let g of h)e[f]?.put(c+13,g),f++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),ro(e[n-1],t,i,{badge:"HELP",right:["? esc","close"]})}function NS(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?Qe+n:""]]),l?.right(2+s+2+o,[[i[u],K]])})}function Ef(e,t,n){let r=Array.from({length:n},()=>new Za(t)),i=[],s=xi(e.colors.cursor);if(pf=!1,t<Gr.cols||n<Gr.rows)return r[0]?.put(0,"ttheme find",Qe+s),r[1]?.put(0,`Needs ${Gr.cols}×${Gr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",K),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")pS(r,i,t,n,e,s);else o=mS(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 Za(t);return NS(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 Za(t);if(e.help)IS(r,t,n,e,s);else SS(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:pf}}var vf=5,PS=6,ww=0.05,OS=[1,2,3,4,5,6,9,10,11,12,13,14],$w=(e,t)=>(t-e+360)%360<=180?1:-1;function so(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 Lt(e,t,n){let r=0,i=t;if(so(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(so(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(so(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function RS(e,t){let{l:n,c:r}=Je(e);return Lt(n,r,(t+360)%360)}function FS(e,t,n){let{l:r,c:i,h:s}=Je(e),o=Ye(t)<0.18,a=(l)=>Lt(o?r+(1-r)*l:r*(1-l),i,s);if(Ke(a(1),t)<n+ww)return a(1);let u=0,c=1;for(let l=0;l<30;l++){let f=(u+c)/2;if(Ke(a(f),t)>=n+ww)c=f;else u=f}return a(c)}function HS(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(Ye(Lt(u,r,i))<=t-0.005)s=u;else o=u}return Lt(s,r,i)}function TS(e,t,n){let r=gn[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)=>Hn.every((h)=>{let g=(l>8?8:0)+h;if(g===l)return!0;let p=Je(e[g]);return p.c<es||Qt(p.h,f)>=Vr+1||Math.abs(p.l-d)>=Zr}),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(Qt(l,f)>_t-vf||!n.has(t+8)&&!a(t+8,f,s.l))continue;let d=Qt(l,i.h)+Qt(f,s.h);if(d<c)c=d,u=[l,f]}}return u}class kw{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,RS(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of Qr(this.theme)){let i=gn[Tn(n)];this.rehue(n,"ansi-role",i.center+$w(i.center,r)*(i.width-vf))}for(let{normal:n,gap:r}of pr(this.theme)){if(r<=_t)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+$w(o,a)*(_t-vf))}let t=Xr(this.theme);for(let[n,r]of br(this.theme)){let i=Tn(t.has(r)?n:r),s=TS(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(Ke(this.get(a),o)<s)this.set(a,r,FS(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",OS.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Ye(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",HS(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 tu(e){let t=new kw(e);for(let n=0;n<PS;n++)if(t.readability(),t.roles(),wr(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:wr(t.theme)}}var oo=[{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}],nu={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},yw=(e,t,n)=>Math.min(n,Math.max(t,e));function Ew(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:yw(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function Ur(e){let t=(r,i,s)=>Lt(yw(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 Hn){let i=gn[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 co=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],St=["Background","Foreground","Cursor","Selection"],au=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],ao=St.length+au.length,jr=[{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}],vw=5;function AS(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Ai(t).length>0}function ru(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function In(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function iu(e){if(e<St.length)return{name:St[e],about:co[e]};let t=e-St.length,n=au[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var su=(e,t,n)=>Math.min(n,Math.max(t,e));function xS(e){return su(Math.round(e),0,255).toString(16).padStart(2,"0")}function Mw(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)=>xS(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 Lt(su(s,0,1),Number(i[3]),Number(i[4])%360)}return}function ou(e){let t=pt.find((n)=>n.rule===e);return t?.min??t?.max??0}function uo(e,t,n){let r=In(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function LS(e,t,n){let r=uo(e,t,n),i=(f)=>!n.includes(f),{background:s,foreground:o,selection:a,ansi:u}=In(e),c=new Set,l=(f,d,h,g)=>{if(i(g)&&Ke(d,h)<ou(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")&&Ye(u[0])>ou("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:f}of Qr(r))c.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of pr(r))if(d>_t)c.add(4+f+8)}if(i("distinct"))for(let[f,d]of br(r))c.add(4+f).add(4+d);return c}function Sn(e,t,n,r,i){let s=Ke(e,t),o=ou(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 Sw(e,t,n,r){let i=In(e),s=uo(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce(($,k)=>Ke(i.ansi[$],i.background)<=Ke(i.ansi[k],i.background)?$:k);return[Sn(i.foreground,i.background,"foreground","Foreground on it",n),Sn(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),Sn(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[Sn(i.foreground,i.background,"foreground","On background",n),Sn(i.foreground,i.selection,"selection","On the selection",n)];if(r===2)return[{ok:void 0,text:`On background ${Ke(i.cursor,i.background).toFixed(2)}:1`}];if(r===3)return[Sn(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-St.length,a=i.ansi[o];if(o===0){let b=Ye(a),m=ou("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${b.toFixed(3)} · waived`}:{ok:b<=m,text:`Luminance ${b.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[Sn(a,i.background,"light-ansi","On background",n)];if(o===8)return[Sn(a,i.background,"ansi8-visible","On background",n)];let u=[Sn(a,i.background,"accents","On background",n)],c=Je(a),l=Tn(o),f=gn[l],d=`${f.name} ${f.center}±${f.width}°`;if(c.c<es)u.push({ok:void 0,text:"Too grey to have a hue"});else if(Xr(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 b=Qt(c.h,f.center)-f.width;u.push(b>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${b.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${d}`})}let h=o<8?o+8:o-8,g=pr(s).find((b)=>b.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<=_t,text:`${g.gap.toFixed(0)}° from ANSI ${h} · ≤ ${_t}°`});let p=br(s).flatMap(([b,m])=>b===o?[m]:m===o?[b]:[]);if(p.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${p.join(", ")} · within ${Vr}° and ${Zr} lightness`});return u}function Iw(e,t,n){let r=An(uo(e,t,n));return pt.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 CS=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class Mf{mode;seeds=nu;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=ru(e.colors??Ur(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 In(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<St.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 LS(this.list,this.signature,this.waive)}failing(){return wr(uo(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(AS(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=Mw(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=oo.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=oo[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:vw:1);this.seeds=Ew(this.seeds,n,r),this.list=ru(Ur(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"?ao-1:1))%ao,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:ao-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:St.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=jr.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=jr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:vw:1))}else if(/^[0-9]$/.test(e)){let n=jr[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=jr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=jr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:su(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=Lt(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=Mw(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=ru(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||CS.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Yt(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Je(t)}follow(){if(this.row<St.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:su(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=Lt(r.l,r.c,r.h),this.col=1,this.notice=`${iu(t).name} follows ${iu(e).name.toLowerCase()}`}mark(){let e=co[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=uo(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=tu({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=wr(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=ru({...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 If=80,Nf=24,uu=48,Sf=11;function _S(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?zt(t):"",bg:(t)=>e?`\x1B[48;2;${Me(t).join(";")}m`:""}}function GS(e){return Ye(e)>0.35?"#000000":"#ffffff"}function Pw(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(GS(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function WS(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 so(o.l,o.c,o.h)?Lt(o.l,o.c,o.h):void 0})}function Ow(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var Nw={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 Rw(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function Fw(e,t,n){let r=Iw(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=uu-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${Rw(e,a.ok)} ${dn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function US(e,t,n){let r=t.misses(),i=In(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(co[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Ke(i.foreground,i.selection):Ke(f,i.background),p=g===void 0?"":g.toFixed(1),b=r.has(l)?"✗":" ",$=`${e.color?`${e.fg(f)}${h}${d?e.fg(i.foreground):"\x1B[39m"} `:`${h} `}${f} ${p.padStart(4)}${b}`;return d?o(` ${$} `):` ${$} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<St.length;l++){let f=l===t.row,d=St[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=St.length;l<ao;l++){let f=l===t.row,d=au[l-St.length].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...Fw(e,t,n-c.length)]}function jS(e,t,n){let r=In(t.list),i=[` ${e.dim("Seeds")}`];oo.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:Sf},(p,b)=>{let m=s.min+(s.max-s.min)*b/(Sf-1);return Nw[s.key](Ur({...t.seeds,[s.key]:m}))}),l=Pw(e,c,Ow(u,s.min,s.max,Sf),a),f=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),d=Nw[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 Ve("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.",uu-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...Fw(e,t,n-i.length)]}function Hw(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} ${nt(f,n-2)} ${e.color?"\x1B[0m":""}`)}function KS(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}=iu(i),f=t.signature.includes(co[i]),d=[dn(`${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,[p,b,m]=Me(s),$=g??`${e.bold(s)}${u!==s?e.dim(` was ${e.color?`${e.fg(u)}■\x1B[39m `:""}${u}`):""}`;d.push(`${h}${$}`),d.push(`${h}${e.dim(`rgb ${p} ${b} ${m}`)}`),d.push(`${h}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let k=Math.max(8,Math.min(64,n-12));jr.forEach((M,y)=>{let N=t.mode==="tune"&&y===t.channel,O=o[M.key],T=`${O.toFixed(M.digits)}${M.wraps?"°":""}`.padStart(6),A=Pw(e,WS(o,M,k),Ow(O,M.min,M.max,k),N),C=M.key.toUpperCase();d.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${A} ${N?e.bold(T):e.dim(T)}`)}),d.push("");let S=Sw(t.list,t.signature,t.waive,i);if(a.c<o.c-0.005)S.push({ok:void 0,text:`Chroma held at the sRGB edge — ${a.c.toFixed(3)} of ${o.c.toFixed(3)}`});for(let M of S)Ve(M.text,n-2).forEach((y,N)=>{d.push(`${N===0?Rw(e,M.ok):" "} ${M.ok===!1?y:e.dim(y)}`)});let w=r-d.length-1;if(w>=3)d.push("",...Hw(e,In(t.shown()),n).slice(0,w));return d}function JS(e,t,n,r){return[dn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...Hw(e,In(t.list),n).slice(0,r-2)]}var BS=[["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 qS(e,t,n){let r=[` ${e.bold("Help")}`,""];for(let[i,s]of BS.filter(([o])=>o!=="Pictures"||t.options.find))Ve(s,n-16).forEach((o,a)=>{r.push(` ${e.bold((a===0?i:"").padEnd(11))} ${o}`)});return r}function zS(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=[dn(` ${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,p=e.color?`${e.bg(g.background)} ${[...g.ansi].map(($)=>`${e.fg($)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",b=h?"▌ ":" ",m=f.name.padEnd(l);a.push(`${b}${h?e.bold(m):m} ${p}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function YS(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?dn(f,c,n):nt(f,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function QS(e,t,n,r){let i=_S(r);if(t<If||n<Nf){let g=[i.bold("ttheme palette editor"),`Needs ${If}×${Nf} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(p,b)=>nt(g[b]??"",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=qS(i,e,t);else if(e.overlay==="open")d=zS(i,e,t,f);else{let g=t-uu-2,p=e.mode==="seeds"?jS(i,e,f):US(i,e,f),b=e.mode==="seeds"?JS(i,e,g,f):KS(i,e,g,f);d=Array.from({length:f},(m,$)=>`${nt(p[$]??"",uu)}${i.dim("│")} ${nt(b[$]??"",g)}`)}let h=[dn(l,u,t),""];for(let g=0;g<f;g++)h.push(nt(d[g]??"",t));return h.push("",YS(i,e,t)),h}async function Tw(e,t){let n=new Mf(e),{stdin:r,stdout:i}=process,s=i.columns||If,o=i.rows||Nf,a=[],u=[],c="",l,f=(k)=>i.write(k),d=()=>{l=void 0;let k="";if(n.shown().forEach((S,w)=>{if(u[w]!==S&&t.only?.includes(w))k+=rl(w,S),u[w]=S}),k)f(k)},h=()=>{let k=QS(n,s,o,t.color),S="";if(k.forEach((w,M)=>{if(a[M]!==w)S+=`\x1B[${M+1};1H\x1B[0m\x1B[2K${w}`}),a=k,S)f(`\x1B[?2026h${S}\x1B[0m\x1B[?2026l`);if(t.only)l??=setTimeout(d,33)},g,p,b=!1,m=()=>{f(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${ki}`),r.setRawMode(!0),r.resume()},$=(k)=>{if(g&&p)r[k?"on":"off"]("data",g),i[k?"on":"off"]("resize",p)};m();try{return await new Promise((k)=>{let S=async(w)=>{let M=e.find;if(!M)return;b=!0,$(!1),clearTimeout(l),l=void 0;try{n.found(await M(n.edited(),w))}catch(y){n.notice=y instanceof Error?y.message:String(y)}b=!1,m(),$(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,h()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],f(ki),h()},g=(w)=>{c+=w.toString("utf8");let M=Va(c);c=M.pending;for(let N of M.events)if(N.kind==="paste")n.paste(N.text);if(M.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(M.keys)&&n.typing===void 0)n.paste(M.keys);else for(let N of Da(M.keys))if(n.press(N),n.result||n.wants)break;if(n.result){k(n.result==="saved"?n.edited():void 0);return}let y=n.wants;if(y&&!b){n.wants=void 0,S(y.start);return}h()},$(!0),h()})}finally{clearTimeout(l),$(!1),r.setRawMode(!1),r.pause(),f("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as gI}from"node:child_process";import{createHash as e0}from"node:crypto";import{existsSync as Gi,mkdirSync as mI,mkdtempSync as pI,readFileSync as t0,rmSync as lo,statSync as bI}from"node:fs";import{homedir as wI,tmpdir as $I}from"node:os";import{dirname as kI,join as Bt}from"node:path";import{pathToFileURL as Kw}from"node:url";var VS=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),ZS=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),XS=0.04,DS=0.1,eI=0.05,tI=4096;function nI(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function rI(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...nI(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)+([...VS].some((l)=>o.has(l))?-3:0)+([...ZS].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 cu(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:rI(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 xw(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 Pf(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Aw(e,t,n){let[r,i,s]=[Pf(e),Pf(t),Pf(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 Lw(e,t){let n=t.map((o)=>Aw(...Me(o))).filter(([,o,a])=>Math.hypot(o,a)>=XS);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/tI))),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]=Aw(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([d,h,g],p)=>{if(Math.hypot(c-d,l-h,f-g)<DS)i[p]=i[p]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/eI),0)/n.length}import{mkdirSync as aI,readFileSync as Rf,writeFileSync as Uw}from"node:fs";import{dirname as uI}from"node:path";import{isMainThread as cI,parentPort as jw,Worker as lI}from"node:worker_threads";var iI=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,sI=[[/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 Of(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 Cw(e,t){let n=iI.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...sI.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function _w(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 Gw(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,p=e.data[g+3]/255,b=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=b*p+255*(1-p)}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 oI(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function Ww(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&&oI(e.hash,t.hash)<=2}var fI={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},lu;async function dI(e){if(e.job==="redraw")return _a(e.home,e.name,e.key,e.paint,e.blur,e.aligns,e.user);if(e.job==="show"){if(lu?.from!==e.from){let o=_n(new Uint8Array(Rf(e.from)),wt);lu={from:e.from,clear:mn(o),inked:Tc(o)}}let{image:r,fill:i,opacity:s}=fm(lu.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune,e.coloring);return aI(uI(e.to),{recursive:!0}),Uw(e.to,Gn(r)),{clear:lu.clear,fill:i,opacity:s}}let t=_n(new Uint8Array(Rf(e.from)),wt);if(e.job==="backdrop"){sa(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(Rf(e.source)),cut:e.from!==e.source},e,e.blur,e.coloring);let r=e.tune&&Tt(e.home,e.colors.name).find((i)=>i.key===ft(e.origin));if(e.tune&&r)Ms(Re(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:Lw(t,e.colors),hash:Gw(t)};if(e.job==="thumb")return Z(e.to,Gn(rg(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return Uw(e.to,Gn({width:t.width,height:e.height,data:n})),0}function hI(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 Ff{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 lI(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 Hf{lines=new Map;run(e){let t=fI[e.job],n=this.lines.get(t);if(!n)n=new Ff,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Tf{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Ff)}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(!cI&&jw)hI(jw);var Kr=[{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:ii,multi:{read:vr}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:yr,multi:{read:oi,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"]},...Ni()?[{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:Eg,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:vg,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:hs},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:mc,multi:{read:Uo,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 Jw(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 gs(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var yI=["fit","newest","score"];function Af(e){return yI.find((t)=>t===e)??"fit"}var EI={left:-1,right:1,"shift-left":-10,"shift-right":10};function vI(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 xf=vI(process.env.TTHEME_BG_MARGIN);function MI(e,t,n){if(t<0){if(e!=="fill")return Math.max(Qw,e+t);if(!n)return e;return Math.max(Qw,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function n0(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function SI(e,t){if(n0(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:$t[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function II(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var Bw=12,NI=4,PI=150,OI=300,qw=12,RI=2,FI=150,HI=30,TI=4000,AI=8000,zw=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,xI=process.platform==="win32"?"alt+v":"ctrl+v",Yw=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",LI=1280,CI=16,_I=$t.indexOf("top-right")+1,Qw=20,fo=2147483645,ho=2147483646,Vw=-1073741827,GI=-1073741828,Zw=2,WI=80,UI=16,jI=0.4,KI=3221225472,JI=256,BI=3,qI=8;function fu(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 go(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return go(e.errors[0]);if(e.cause)return go(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 Lf(e,t){return`${e}: ${go(t)}`}function Xw(e){return e.width*e.height}function Dw(e,t){return`${e}-${e0("sha1").update(t).digest("hex").slice(0,8)}`}function zI(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function YI(e,t){try{return JSON.parse(t0(Bt(Xt(e),t),"utf8"))}catch{return{}}}function QI(e,t,n){Z(Bt(Xt(e),t),`${JSON.stringify(n)}
506
+ `)}class Cf{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(Kr.map((e)=>[e.name,Jw(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 Hf;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=ip(process.env);bandFiles=new Map;nextBand=KI;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new mf((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=pI(Bt($I(),"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=di(n,n.signatureSlots),this.blurring=Fr(e),this.coloring=ba(e);let s={size:"fill",at:_I,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:Af(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:vr(this.setting("TTHEME_FIND_RATING")),block:oi(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:hs(this.setting("TTHEME_FIND_SITES")),hide:Uo(this.setting("TTHEME_FIND_HIDE")),hideTags:gs(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Kr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:Jw(o,ul(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,At.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=fu(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??NI}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 bc(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 Bt(Xt(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=Ko(e.site,e.post);return Bt(Xt(e.site),"thumb",`${Dw(e.post.id,t)}.${Jn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Ht(n,r.id),s=Zt(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===Cr?"":n.pageUrl(r.id),artist:n===Cr?Bb(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${ki}`);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\\${ki}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),lo(this.scratch,{recursive:!0,force:!0}),Lg(),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(uw)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=kf(this.input);n;n=kf(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=Va(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),zI(this.typed)){this.partial=setTimeout(this.flushKeys,HI);return}this.flushKeys()};flushKeys=()=>{let e=Da(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!jo(t,this.site??X[0]);return Ai(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 — ${Yw}`);return}this.pasted(e.text);return}await this.bring(()=>Ya(e.bytes,e.source))}notice(e,t=TI){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 Vb()}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 · ${xI} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},AI),this.draw()}async fromClipboard(){let e=this.view;if(gf()){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 Qb(Bt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${go(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await hf(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${Yw}`);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=jo(t,this.site??X[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ai(t).sort((i,s)=>Number(!zw.test(i))-Number(!zw.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)=>hf(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(go(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=zb(i.bytes);qb(s,i.source);let o=this.origPath(Cr,s,i.ext);Z(o,i.bytes);let a=Kw(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:e0("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Cr,post:u},l=this.previewPath(c);Z(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=fu(`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(Ht(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)=>Kn(i)>Kn(r)?i:r),t=Math.ceil((Kn(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<Gr.cols||this.rows<Gr.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}=Wr(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=io(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=io(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=bw(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(Kr[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":gs(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<yf:/^[\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),OI)}pending(){let e=(t)=>this.view.settings[Kr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Af(e("TTHEME_FIND_ORDER")),rating:vr(e("TTHEME_FIND_RATING")),narrow:bc(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:hs(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 yc(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=Kr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Kr[i];if(s)this.values.set(s.name,r.value)});let n=Kr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=vr(this.setting("TTHEME_FIND_RATING")),e.block=oi(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=Af(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=hs(this.setting("TTHEME_FIND_SITES")),e.hide=Uo(this.setting("TTHEME_FIND_HIDE")),e.hideTags=gs(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=Bt(this.home,"ttheme","config.zsh");try{let n=Gi(t)?t0(t,"utf8"):"";return Z(t,e.reduce((r,[i,s])=>lp(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(!II(t)){e.suggest=void 0;return}let n=[...new Map(Bm(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,BI);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await _g(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,qI),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},PI)}async commit(e){let t=jo(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=fu(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await ms(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(Ht(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{gI(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=EI[e];if(i!==void 0){if(n.field===0)r.size=MI(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=Ag(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=ps(n.source),a=/^https?:\/\//i.test(o)?o:t===Cr&&o.startsWith("/")?Kw(o).href:void 0;return{page:t===Cr?"":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:(Zt(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}=Wr(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=Wr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Be.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)*jI)),this.draw(),this.gliding=setTimeout(t,UI)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Be.height}prebake(){let e=this.view;for(let t of Ef({...e,scroll:e.top*Be.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?qm(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(kc([...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=fu(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=kc(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})=>yc(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=Lf(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,Lf(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=Wr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+Zw)*e}need(){let{perRow:e,rowsVis:t}=Wr(this.cols,this.rows);return(t+Zw)*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=Cg(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===Ft?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{Qo(n,await Vo(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<jn;let c=e.last.get(a);for(let l of u){let f=c&&_w(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:f};let d=Ht(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,...Cw(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?xw(i):i;else{let a=cu(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=[...cu(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(Ht(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=cu(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=Of(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++,Xw(r.post)<=Xw(s.post))continue;for(let a of[...i,...Of(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(Ht(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:qw},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Ht(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=Ko(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<Bw&&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<Bw&&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=Zt(t);if(!Bo(e,t,this.view.rating)||Jo(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"||Tg(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=YI(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 Zo(e,t,this.signal),s=ai(e,t),o=(i===void 0?await Gg(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)QI(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Ht(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)=>Ww(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(!Yo(n,r))return Promise.resolve();let i=Ht(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 zo(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}bs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=km(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 ms(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=xg(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(Gi(t))return bI(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await Xo(e,n,this.signal,r);return Z(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<qw&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Ht(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Be.cols*this.cell.w,i=Be.rows*this.cell.h,s=Ko(t,n),o=Bt(Xt(t),"tile",`${Dw(n.id,s.url)}-${r}x${i}.png`);if(!Gi(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(Ht(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),FI),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),!Zt(n.post))return;let{site:i}=n,s=this.board;try{await Zo(i,n.post,r.signal);let o=Zt(n.post),a=this.origPath(i,e.id,o.ext);if(!Gi(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=ai(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&&Ni()&&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&&La(d.clear))l.using="cut";else lo(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=Lf(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=Bt(Xt(e),"cut",`${t}.png`);if(Gi(i))return i;try{return mI(kI(i),{recursive:!0}),await Us(n,i,r),i}catch{lo(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>=RI||!r||!Zt(r.post))continue;let{site:i,post:s}=r;this.prefetching++,Zo(i,s,this.signal).then(async()=>{let o=Zt(s),a=this.origPath(i,s.id,o.ext),u=ai(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,LI),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!n0(o,this.view.untuned),u=o.opacity!==this.view.untuned.opacity,c=a?`-${o.size}-${o.at}${u?`-${Math.round(o.opacity*100)}`:""}`:"",l=Bt(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&&Gi(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/Fc(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>CI){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;lo(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=SI(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:ps(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,coloring:this.coloring,...r?{tune:r,aligns:Ar(ue(this.home).terminals),user:wI()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),Mt(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${$t[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=Ef(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)t+=cw(s),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)t+=lw(s,this.cell),this.placed.set(s.id,o)}for(let i of this.sent.keys())if(!n.has(i))t+=fw(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.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(Me(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${fo},q=2;${n}\x1B\\`,xf)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${ho},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${ho},p=${ho},c=1,r=1,C=1,z=${GI},q=2\x1B\\`}if(this.covered=e,xf){let{x:n,y:r}=xf;return`${t}\x1B_Ga=p,i=${fo},p=${fo},P=${ho},Q=${ho},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${Vw},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${fo},p=${fo},c=${this.cols},r=${this.rows},C=1,z=${Vw},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()},WI);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:Bt(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<=JI)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),lo(t.path,{force:!0})}}}async function r0(e,t,n){let r=new Cf(e,sn(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function i0(e){let t=ge(),n=sn(t),r=Pr(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Cf(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
507
+ `),0;return s}function s0(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function o0(e,t){if(e.includes("/"))return e;let n=Nr(t,!1),r=n.filter((s)=>Dn(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function XI(e,t,n){let r=ue(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)cn(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))gt(e,t,r);return{state:r,fresh:i}}function DI(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 a0(e,t,n){let r=Cm(t),i=Ut(Et(r.name,qc(r),n.palettes)),s=je(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 ${ve(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)ha(e,[...yn(e),i]);return i.name}var eN=["background","foreground","cursor"];function u0(e){try{e();return}catch(t){return t.message}}function c0(e,t,n){return je(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 l0(e,t){let n=new Set(Tt(e,t).map((r)=>r.key));return{count:()=>Tt(e,t).length,added:()=>Tt(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(Ca(e,t)??[]).filter((r)=>!n.has(ft(r))),discard:()=>{let r=Tt(e,t).filter((i)=>!n.has(i.key));for(let i of r)gi(e,t,i.key),ia(e,t);if(r.length>0)Mt(e)}}}function tN(...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 f0(e,t,n,r){if(!rp(process.env))return;return async(i,s)=>{let o=Ut(Et(t,r(i),n.palettes)),{saved:a}=await r0(e,o,s);return{...a?{note:a}:{},count:Tt(e,t).length}}}async function d0(e){let t=sr(process.env,process.stdout.isTTY===!0),n=t?await t.saved():new Map;try{return await Tw(e,{color:!xt(),...t?{only:t.slots}:{}})}finally{if(t)process.stdout.write(t.restore(n))}}async function h0(e,t,n){let r=ge(),i=We(r),s=await Fb(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=en(o);if(a)throw Error(`${o} ${a}`);if(ve(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=Jc(r,o);if(mo(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?Pr(je(r,i).palettes,t):void 0;if(!s0())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(ve(c.name)?c.base:c.default?void 0:c.name),f=c?Bc(c,o,`kept from ${c.name}`):void 0,d=c?Ca(r,c.name)??c.pictures:void 0,{base:h,ansiSource:g,group:p,...b}=f??{name:o,signature:eN,...Ur(nu)},m=l0(r,o),$=({colors:w,signature:M})=>{let y=tN(d,m.fresh());return qc({...b,...w,signature:M,...l?{base:l}:{},...y?{pictures:y}:{}})},k=await d0({title:"New palette",name:o,...f?{colors:f}:{},signature:b.signature,...b.waive?{waive:b.waive}:{},palettes:c0(r,i,o),pictures:m.count(),find:f0(r,o,i,$),check:(w)=>u0(()=>Et(o,$(w),i.palettes))});if(!k){m.discard(),console.log("Nothing made");return}VI(ZI(u),{recursive:!0}),Z(u,$(k));let{state:S}=XI(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
508
+ ${u}`),await vn(r,je(r,i).palettes.filter((w)=>w.name===o),S.terminals),console.log(`
509
+ \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function nN(e,t,n){let r=Ut(Et(e,t,n.palettes));return Rs(r).length>0?Ps(r).filter((i)=>i.startsWith(" ✗")):[]}async function g0(e){let t=ge(),n=We(t),r=ue(t),i=je(t,n,!1),s=o0(e,t),o=du(t,s),a=o&&mo(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=du(t,a);if(!u||!mo(u)){let m=i.palettes.some(($)=>$.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(!s0())throw Error("edit opens the palette editor — run it in a terminal");let c=_f(u,"utf8"),l;try{l=Et(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let f=l0(t,a),d=new Set((l.pictures??[]).map((m)=>ft(m))),h=({colors:m,signature:$})=>Tm(_m(Yc(c,m),$),f.fresh().filter((k)=>!d.has(ft(k)))),g=await d0({title:"Edit palette",name:a,colors:zc(l),signature:l.signatureSlots,waive:l.waive,palettes:c0(t,n,a),pictures:f.count(),find:f0(t,a,n,h),check:(m)=>u0(()=>Et(a,h(m),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let p=h(g);if(p===c){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(Z(u,p),r.palettes.includes(a))gt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let b=nN(a,p,n);if(b.length>0)console.log(`
510
510
  It misses the contrast gate:
511
511
  ${b.join(`
512
512
  `)}
513
- \`ttheme check --fix ${a}\` suggests colors that pass`)}function Vw(e,t,n){return Ir(e.palettes,e.palettes.some((r)=>r.name===t)?t:Uw(t,n))}function Zw(e,t=!1){let n=ge(),r=We(n),i=ce(n),s=Vw(je(n,r),e,n);if(console.log(`${s.name} · ${s.group}
514
- `),console.log(vs(s).join(`
515
- `)),Ms(s).length===0)return console.log(`
516
- Passes the gate`),0;let{theme:a,moves:u,left:c}=Ya(wn(s));if(u.length===0)return console.log(`
513
+ \`ttheme check --fix ${a}\` suggests colors that pass`)}function m0(e,t,n){return Pr(e.palettes,e.palettes.some((r)=>r.name===t)?t:o0(t,n))}function p0(e,t=!1){let n=ge(),r=We(n),i=ue(n),s=m0(je(n,r),e,n);if(console.log(`${s.name} · ${s.group}
514
+ `),console.log(Ps(s).join(`
515
+ `)),Rs(s).length===0)return console.log(`
516
+ Passes the gate`),0;let{theme:a,moves:u,left:c}=tu($n(s));if(u.length===0)return console.log(`
517
517
  No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
518
518
  ${c.length===0?"These colors pass":"These colors come closer"}:
519
- ${AI(u).join(`
520
- `)}`);let l=su(n,s.name);if(!l||!co(l))return console.log(`
519
+ ${DI(u).join(`
520
+ `)}`);let l=du(n,s.name);if(!l||!mo(l))return console.log(`
521
521
  \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
522
- \`ttheme check --fix ${s.name}\` writes them`),1;if(Z(l,xc(If(l,"utf8"),Lc(a))),i.palettes.includes(s.name))gt(n,r,i);return console.log(`
523
- Wrote ${l}`),c.length===0?0:1}function su(e,t){let n=ve(t);return n&&Mr(e,!1).some((r)=>r.id===n)?Hc(e,t):void 0}function GI(e,t){let n=su(e,t.name),r=n&&co(n)?Et(t.name,If(n,"utf8"),[t]).waiveReason:void 0,i=Ra(e,t.name)??t.pictures,{pictures:s,...o}=Tc(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Xw(e){let t=ge(),n=wm(GI(t,Vw(je(t,We(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
524
- Anyone with ttheme wears it with: ttheme add ${$n}…`)}function ou(e){console.log(`
525
- ${e} palettes installed — open a new tab, or reload your terminal config`)}function WI(e,t){return e.map((n)=>{if(n.startsWith($n))return n;let r=ve(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 Dw(e,t){let n=ge(),r=t?WI(e,(await Ll(n,t)).id):e,i=We(n),s=[...new Set(r.map((l)=>l.startsWith($n)?jw(n,l,i):l))],o=ce(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){gt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};un(n,i,o,c);for(let l of u)console.log(` + ${l}`);await vn(n,je(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),ou(c.palettes.length)}function e0(e){let t=ge(),n=We(t),r=ce(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};un(t,n,r,o),Na(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(ou(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function t0(e){let t=ge(),n=We(t),r=ce(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=un(t,n,r,{...s,startup:e},!0);console.log(i0(e,r.terminals,o).join(`
526
- `))}function n0(){let e=ge(),t=ce(e),n=Or(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=un(e,We(e),t,i);console.log(i0(n,i.terminals,s).join(`
527
- `))}function r0(){let e=ge(),t=ce(e);if(t.off){console.log("Already off");return}let n=un(e,We(e),t,{...t,off:!0}),r=Or(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 i0(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 s0(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of sa(e,t.palettes,!1))n.set(r.name,"mine");return n}function o0(e,t=!1){let n=ge(),r=We(n),i=new Set(ce(n).palettes),s=s0(n,r),o=Xe(je(n,r).palettes),a=vr(e?Im(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(`
528
- ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function a0(){let e=ge(),t=fi(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(Ae))try{console.log(` ${mb(e,d)}`)}catch(h){console.log(` ${n(d,h)}`)}let r=t.filter((d)=>!Ae(d)),i=new Set(r),s=cr(),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=Ol(await _s(e,d))}catch(g){h=n(d,g)}if(i.delete(d),i.size>0)o();else s.done();s.say(` ${h}`)})),s.done(),!_I(Yn(e)))return;let a=We(e),u=ce(e),c=s0(e,a),l=u.palettes.filter((d)=>!c.has(d)),f=new Map(kn(e).map((d)=>[d.name,d.pictures]));gt(e,a,u);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await vn(e,je(e,a,!1).palettes.filter((d)=>u.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Pi(d,f.get(d.name))),u.terminals)}async function Nf(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:vr(e.palettes),s=rr(process.env,process.stdout.isTTY===!0),o=s?await s.saved():new Map,a=new zl({entries:i,scope:n,installed:t,required:r,color:!At(),fx:xa(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(s.paint(c)):void 0}),u=await a.prompt();if(s)process.stdout.write(s.restore(o));if(ht(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Pf(e,t,n,r){let i;try{i=Ri(e,n)}catch{i=kt(n)?zn(n):ye(n)}let s=[];if(Ae(n))try{s=Xn(n,i,Fi(e,ee),!1)}catch{s=[]}else s=Fi(e,n);return{source:n,id:i,shown:ye(n),entries:s,auto:Qn(n,t.updates),status:Gl(e,n,r)}}function au(e){return e instanceof Error?e.message:String(e)}function jI(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of it(t.markets)){let a=i.get(o)??ye(o),u=n[o],c=Cs(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${Ws(u.at)}: ${u.error}`});if(o===ee)try{rn(u0(Kt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ye(Kt(e))}: ${au(l)}`})}else if(kt(o))if(!UI(jt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{Dn(e,o)}catch(l){s.push({where:a,source:o,message:`${ye(jt(e,o))}: ${au(l)}`})}else try{let l=yt(nn(o)),f=new Map;for(let d of Zn(o))try{let h=Es(d,f);if(h)throw Error(h);f.set(d.slug,d),Et(`${l}/${d.slug}`,u0(d.path,"utf8"),Fi(e,ee))}catch(h){s.push({where:ye(d.path),message:au(h)})}}catch(l){s.push({where:a,message:au(l)})}}return s}function KI(e,t,n,r){return{refresh:async(i)=>{if(Ae(i)){let o=Pf(e,t,i,Sn());return{market:o,refreshed:{source:i,id:o.id,count:Xe(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await _s(e,i,Nl);return{market:Pf(e,t,i,Sn()),refreshed:s}},fetch:async(i)=>{if(Ae(i)){let o=yt(nn(i));return{source:i,id:o,shown:ye(i),entries:Xn(i,o,Fi(e,ee),!1),auto:!1,status:"read in place"}}let s=await Gs(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ye(i),entries:s.entries,auto:Qn(i,{}),status:"not added yet"}},search:(i)=>Wl(i,r)}}function JI(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)=>(ve(a)??ee)===s);if(o.length>0)r.push(Cl(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 BI(e,t,n,r,i){let s=ce(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let m of r.adds){let $=i.get(m.source);if($)Oi(e,$)}for(let m of r.removes)xl(e,m);let a=[...it(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=Us(s,a,{...s.updates,...r.auto});if(o)an(e,u);let c=We(e,!1),l=je(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 Ha(e,s,t,r.refreshed),console.log("Nothing changed");return}let h={...u,palettes:l};un(e,c,s,h),Na(e,c,s.terminals,f);for(let m of JI(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])),p=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),b=je(e,c,!1).palettes;if(await vn(e,[...b.filter((m)=>d.includes(m.name)),...b.filter((m)=>l.includes(m.name)&&!d.includes(m.name)&&p.has(m.name)&&g.has(m.name)).map((m)=>Pi(m,g.get(m.name)))],h.terminals),d.length>0||f.length>0)ou(h.palettes.length)}async function c0(){let e=ge(),t=ce(e),n=kn(e),r=Sn(),i=it(t.markets).map((p)=>Pf(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((b)=>b.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=rr(process.env,process.stdout.isTTY===!0),l=c?await c.saved():new Map,f=Jt(t),d=new Vl({markets:i,kept:o,installed:t.palettes,...f?{startup:f}:{},problems:jI(e,t,r,i),due:Pl(e,t),io:KI(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:vr},color:!At(),fx:xa(process.env.TTHEME_FX),...c?{onFocus:(p)=>process.stdout.write(c.paint(p))}:{}}),h=await d.prompt();if(c)process.stdout.write(c.restore(l));u.abort(),await d.idle();let g=d.result();for(let p of g.refreshed){let b=Fl(p);if(b)console.log(b)}if(ht(h)){await Ha(e,ce(e),n,g.refreshed),console.log("Nothing changed");return}await BI(e,n,i,g,a)}import{rmSync as l0}from"node:fs";import{basename as qI,join as lo}from"node:path";var f0=lo(import.meta.dirname,".."),zI=lo(f0,"themes"),Of=lo(f0,"dist"),uu=vt.map((e)=>ur[e].emitter),YI=[el,Nc],PL=uu.map((e)=>e.id);async function cu({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?uu.filter((s)=>e.includes(s.id)):uu,n=Lg(zI),r=Cd(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===uu.length)l0(Of,{recursive:!0,force:!0});else for(let s of t)l0(lo(Of,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...YI]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(lo(Of,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>qI(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
529
- ${n.length} themes (${xg(n).length} in the new-tab rotation) -> ${i} files in dist/`)}function d0(e,t,n){let r=ge();if(Ir(yn(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=ci(r,e,n);return Lt(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
530
- `),0}if(t==="drop"){let{key:i,left:s}=Do(r,e,n);return Lt(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
531
- `),0}if(t==="tuned")return Lt(r),0;throw Error(`unknown image action ${t} — show, drop or tuned`)}import{execFileSync as XI,spawnSync as DI}from"node:child_process";import{chmodSync as eN,copyFileSync as tN,existsSync as _i,mkdirSync as g0,readdirSync as nN,readFileSync as hu,rmSync as m0}from"node:fs";import{homedir as rN}from"node:os";import{dirname as Gi,join as ze}from"node:path";import{availableParallelism as QI,homedir as VI}from"node:os";var ZI=4;async function lu(e,t,n=VI()){let r=lt(Te(e)),i=wi(e),s=new Map(yn(e).palettes.map((f)=>[f.name,f.backdrop])),o=Object.entries(r.palettes).flatMap(([f,d])=>{let h=s.get(f);return h?d.pictures.filter((g)=>g.tone===void 0||(g.blur??0)!==i).map((g)=>({name:f,key:g.key,hue:h})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=Si(ce(e).terminals),u=new yf(Math.min(ZI,QI()-1)),c=await u.map(o.map(({name:f,key:d,hue:h})=>({job:"redraw",home:e,user:n,name:f,key:d,hue: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})}),im(e,l),Lt(e,n),l.length}async function h0(){return await lu(ge(),(e)=>process.stderr.write(`${e}
532
- `)),0}function iN(e,t,n){for(let r of nN(t))e.push({from:ze(t,r),to:ze(n,r)})}function Tf(e){return JSON.parse(hu(ze(e,"dist","manifest.json"),"utf8"))}function du(e,t){let n=ze(t.configHome,"ttheme"),r=[{from:ze(t.root,"bin","ttheme.js"),to:ze(n,"ttheme.js")},{from:ze(t.root,"bin","ttheme.js.map"),to:ze(n,"ttheme.js.map")},{from:ze(t.root,"shell","ttheme.zsh"),to:ze(n,"ttheme.zsh")},{from:ze(t.root,"shell","launch-tab.zsh"),to:ze(n,"launch-tab.zsh"),executable:!0}];iN(r,ze(t.root,"shell","adapters"),ze(n,"adapters"));let i=[{file:ze(t.zdotdir,".zshrc"),block:Um(n)}],s=ze(n,"config.zsh"),o=Bm(_i(s)?hu(s,"utf8"):""),a={file:s,content:o},u={terminals:e.terminals,palettes:e.palettes,...Object.fromEntries(Ce(e.terminals).flatMap((l)=>Object.entries(l.installs?.(t)??{}).filter(([,f])=>f!==void 0))),...e.off?{off:!0}:{}},c=Gp(t.configHome,u,t.home);return{home:t.home,copies:r,edits:i,settings:a,catalog:Tf(t.root),installed:u,notes:c}}function b0(e){try{return ce(e)}catch{return}}function w0(e){try{return je(e,We(e),!1).palettes}catch{return[]}}function sN(e,t){let n=Tf(t.root),r=it(e.markets).includes(ee)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=w0(t.configHome).filter((o)=>!i.has(o.name)&&(ve(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function $0(e,t){let n=Or(e);return n&&t.includes(n)?n:void 0}function oN(e,t,n){let r=du(t,n),i=$0(e,t.palettes),s=new Set(["terminals","palettes","off","startup",...vt.flatMap((a)=>Object.keys(ur[a].installs?.(n)??{}))]),o=Object.fromEntries(Object.entries(e).filter(([a])=>!s.has(a)));return{...r,installed:{...o,...r.installed,...i?{startup:i}:{}}}}function aN(e,t){let n=du({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...w0(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 uN(e){try{return XI(process.execPath,[ze(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function k0(e){let t=Jt(e);return[Ce(e.terminals).map((n)=>n.name).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function Ff(e,t=Pr()){for(let o of e.copies)if(g0(Gi(o.to),{recursive:!0}),m0(o.to,{force:!0}),m0(`${o.to}.zwc`,{force:!0}),tN(o.from,o.to),o.executable)eN(o.to,493);Z(e.settings.file,e.settings.content);let n=Gi(Gi(e.settings.file)),r=b0(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=Sl(n,{...e.installed,...i},t,e.home);if(it(s.markets).includes(ee))oa(n,e.catalog);an(n,s),gt(n,We(n),s,e.home);for(let o of e.edits){g0(Gi(o.file),{recursive:!0});let a=_i(o.file)?hu(o.file,"utf8"):"";Ln(o.file,ir(a,o.block))}return Ls(n,s,!0,t,e.home)}class fr extends Error{}function fu(e){if(ht(e))throw Kr("Nothing changed"),new fr;return e}function Rf(e,t){return vt.filter((n)=>ur[n].offered(e,t))}async function cN(e,t,n,r){return fu(await Nd({message:"Wire which terminals?",options:Rf(n,r).map((i)=>({value:i,label:ur[i].name,hint:i===e?"detected":void 0})),initialValues:t,required:!0}))}function Hf(e){let t=[...e.copies.filter((n)=>!_i(n.to)).map((n)=>n.to),..._i(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!hu(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
522
+ \`ttheme check --fix ${s.name}\` writes them`),1;if(Z(l,Yc(_f(l,"utf8"),zc(a))),i.palettes.includes(s.name))gt(n,r,i);return console.log(`
523
+ Wrote ${l}`),c.length===0?0:1}function du(e,t){let n=ve(t);return n&&Nr(e,!1).some((r)=>r.id===n)?Jc(e,t):void 0}function rN(e,t){let n=du(e,t.name),r=n&&mo(n)?Et(t.name,_f(n,"utf8"),[t]).waiveReason:void 0,i=Ca(e,t.name)??t.pictures,{pictures:s,...o}=Bc(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function b0(e){let t=ge(),n=Lm(rN(t,m0(je(t,We(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
524
+ Anyone with ttheme wears it with: ttheme add ${kn}…`)}function hu(e){console.log(`
525
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}function sN(e,t){return e.map((n)=>{if(n.startsWith(kn))return n;let r=ve(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 w0(e,t){let n=ge(),r=t?sN(e,(await zl(n,t)).id):e,i=We(n),s=[...new Set(r.map((l)=>l.startsWith(kn)?a0(n,l,i):l))],o=ue(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){gt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};cn(n,i,o,c);for(let l of u)console.log(` + ${l}`);await vn(n,je(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),hu(c.palettes.length)}function $0(e){let t=ge(),n=We(t),r=ue(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))};cn(t,n,r,o),Ta(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 k0(e){let t=ge(),n=We(t),r=ue(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=cn(t,n,r,{...s,startup:e},!0);console.log(v0(e,r.terminals,o).join(`
526
+ `))}function y0(){let e=ge(),t=ue(e),n=Tr(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=cn(e,We(e),t,i);console.log(v0(n,i.terminals,s).join(`
527
+ `))}function E0(){let e=ge(),t=ue(e);if(t.off){console.log("Already off");return}let n=cn(e,We(e),t,{...t,off:!0}),r=Tr(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 v0(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 M0(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of la(e,t.palettes,!1))n.set(r.name,"mine");return n}function S0(e,t=!1){let n=ge(),r=We(n),i=new Set(ue(n).palettes),s=M0(n,r),o=Xe(je(n,r).palettes),a=Sr(e?Jm(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(`
528
+ ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function I0(){let e=ge(),t=pi(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(Ae))try{console.log(` ${Ab(e,d)}`)}catch(h){console.log(` ${n(d,h)}`)}let r=t.filter((d)=>!Ae(d)),i=new Set(r),s=fr(),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=Ul(await Js(e,d))}catch(g){h=n(d,g)}if(i.delete(d),i.size>0)o();else s.done();s.say(` ${h}`)})),s.done(),!iN(Vn(e)))return;let a=We(e),u=ue(e),c=M0(e,a),l=u.palettes.filter((d)=>!c.has(d)),f=new Map(yn(e).map((d)=>[d.name,d.pictures]));gt(e,a,u);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await vn(e,je(e,a,!1).palettes.filter((d)=>u.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Ri(d,f.get(d.name))),u.terminals)}async function Gf(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Sr(e.palettes),s=sr(process.env,process.stdout.isTTY===!0),o=s?await s.saved():new Map,a=new of({entries:i,scope:n,installed:t,required:r,color:!xt(),fx:Ka(process.env.TTHEME_FX),onFocus:s?(c)=>process.stdout.write(s.paint(c)):void 0}),u=await a.prompt();if(s)process.stdout.write(s.restore(o));if(ht(u))return;return e.palettes.filter((c)=>a.picked.has(c.name)).map((c)=>c.name)}function Wf(e,t,n,r){let i;try{i=Ti(e,n)}catch{i=kt(n)?Qn(n):ye(n)}let s=[];if(Ae(n))try{s=er(n,i,Hi(e,ee),!1)}catch{s=[]}else s=Hi(e,n);return{source:n,id:i,shown:ye(n),entries:s,auto:Zn(n,t.updates),status:Vl(e,n,r)}}function gu(e){return e instanceof Error?e.message:String(e)}function aN(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of it(t.markets)){let a=i.get(o)??ye(o),u=n[o],c=js(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${Bs(u.at)}: ${u.error}`});if(o===ee)try{rn(N0(Kt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ye(Kt(e))}: ${gu(l)}`})}else if(kt(o))if(!oN(jt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{tr(e,o)}catch(l){s.push({where:a,source:o,message:`${ye(jt(e,o))}: ${gu(l)}`})}else try{let l=yt(nn(o)),f=new Map;for(let d of Dn(o))try{let h=Ns(d,f);if(h)throw Error(h);f.set(d.slug,d),Et(`${l}/${d.slug}`,N0(d.path,"utf8"),Hi(e,ee))}catch(h){s.push({where:ye(d.path),message:gu(h)})}}catch(l){s.push({where:a,message:gu(l)})}}return s}function uN(e,t,n,r){return{refresh:async(i)=>{if(Ae(i)){let o=Wf(e,t,i,Mn());return{market:o,refreshed:{source:i,id:o.id,count:Xe(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await Js(e,i,Gl);return{market:Wf(e,t,i,Mn()),refreshed:s}},fetch:async(i)=>{if(Ae(i)){let o=yt(nn(i));return{source:i,id:o,shown:ye(i),entries:er(i,o,Hi(e,ee),!1),auto:!1,status:"read in place"}}let s=await Ks(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ye(i),entries:s.entries,auto:Zn(i,{}),status:"not added yet"}},search:(i)=>Xl(i,r)}}function cN(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)=>(ve(a)??ee)===s);if(o.length>0)r.push(Ql(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 lN(e,t,n,r,i){let s=ue(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let m of r.adds){let $=i.get(m.source);if($)Fi(e,$)}for(let m of r.removes)Yl(e,m);let a=[...it(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=qs(s,a,{...s.updates,...r.auto});if(o)un(e,u);let c=We(e,!1),l=je(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 Ga(e,s,t,r.refreshed),console.log("Nothing changed");return}let h={...u,palettes:l};cn(e,c,s,h),Ta(e,c,s.terminals,f);for(let m of cN(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])),p=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),b=je(e,c,!1).palettes;if(await vn(e,[...b.filter((m)=>d.includes(m.name)),...b.filter((m)=>l.includes(m.name)&&!d.includes(m.name)&&p.has(m.name)&&g.has(m.name)).map((m)=>Ri(m,g.get(m.name)))],h.terminals),d.length>0||f.length>0)hu(h.palettes.length)}async function P0(){let e=ge(),t=ue(e),n=yn(e),r=Mn(),i=it(t.markets).map((p)=>Wf(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((b)=>b.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=sr(process.env,process.stdout.isTTY===!0),l=c?await c.saved():new Map,f=Jt(t),d=new cf({markets:i,kept:o,installed:t.palettes,...f?{startup:f}:{},problems:aN(e,t,r,i),due:Wl(e,t),io:uN(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Sr},color:!xt(),fx:Ka(process.env.TTHEME_FX),...c?{onFocus:(p)=>process.stdout.write(c.paint(p))}:{}}),h=await d.prompt();if(c)process.stdout.write(c.restore(l));u.abort(),await d.idle();let g=d.result();for(let p of g.refreshed){let b=jl(p);if(b)console.log(b)}if(ht(h)){await Ga(e,ue(e),n,g.refreshed),console.log("Nothing changed");return}await lN(e,n,i,g,a)}import{rmSync as O0}from"node:fs";import{basename as fN,join as po}from"node:path";var R0=po(import.meta.dirname,".."),dN=po(R0,"themes"),Uf=po(R0,"dist"),mu=vt.map((e)=>lr[e].emitter),hN=[dl,Gc],qx=mu.map((e)=>e.id);async function pu({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?mu.filter((s)=>e.includes(s.id)):mu,n=zg(dN),r=Qd(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===mu.length)O0(Uf,{recursive:!0,force:!0});else for(let s of t)O0(po(Uf,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...hN]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(po(Uf,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>fN(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
529
+ ${n.length} themes (${Yg(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{availableParallelism as gN,homedir as F0}from"node:os";var mN=4;async function bu(e,t,n=F0()){let r=ct(Re(e)),i=Fr(e),s=new Map(sn(e).palettes.map((f)=>[f.name,Es(f)])),o=Object.entries(r.palettes).flatMap(([f,d])=>{let h=s.get(f);return h?d.pictures.filter((g)=>vs(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=Ar(ue(e).terminals),u=new Tf(Math.min(mN,gN()-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})}),_c(e,l),Mt(e,n),l.length}async function H0(e,t,n,r,i=F0()){let s=ct(Re(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(Yn(o)===n)return{key:o.key,changed:!1};let a=sn(e).palettes.find((l)=>l.name===t);if(!a)throw Error(`no palette called ${t}`);let u=Ar(ue(e).terminals),c=await _a(e,t,o.key,Es(a),Fr(e),u,i,n);if(!c)throw Error(`${t} ${o.key} has no original to draw it from`);return _c(e,[{name:t,picture:c}]),Mt(e,i),{key:o.key,changed:!0}}async function T0(){return await bu(ge(),(e)=>process.stderr.write(`${e}
530
+ `)),0}async function A0(e,t,n){let r=ge();if(Pr(sn(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=gi(r,e,n);return Mt(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
531
+ `),0}if(t==="drop"){let{key:i,left:s}=ia(r,e,n);return Mt(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
532
+ `),0}if(t==="tone"||t==="original"){let i=await H0(r,e,t,n);return process.stderr.write(`Background · ${e} ${i.key} ${t==="tone"?"tinted":"in its own colors"}
533
+ `),0}if(t==="tuned")return Mt(r),0;throw Error(`unknown image action ${t} — show, drop, tone, original or tuned`)}import{execFileSync as pN,spawnSync as bN}from"node:child_process";import{chmodSync as wN,copyFileSync as $N,existsSync as Ui,mkdirSync as x0,readdirSync as kN,readFileSync as ku,rmSync as L0}from"node:fs";import{homedir as yN}from"node:os";import{dirname as Wi,join as ze}from"node:path";function EN(e,t,n){for(let r of kN(t))e.push({from:ze(t,r),to:ze(n,r)})}function Bf(e){return JSON.parse(ku(ze(e,"dist","manifest.json"),"utf8"))}function $u(e,t){let n=ze(t.configHome,"ttheme"),r=[{from:ze(t.root,"bin","ttheme.js"),to:ze(n,"ttheme.js")},{from:ze(t.root,"bin","ttheme.js.map"),to:ze(n,"ttheme.js.map")},{from:ze(t.root,"shell","ttheme.zsh"),to:ze(n,"ttheme.zsh")},{from:ze(t.root,"shell","launch-tab.zsh"),to:ze(n,"launch-tab.zsh"),executable:!0}];EN(r,ze(t.root,"shell","adapters"),ze(n,"adapters"));let i=[{file:ze(t.zdotdir,".zshrc"),block:ap(n)}],s=ze(n,"config.zsh"),o=fp(Ui(s)?ku(s,"utf8"):""),a={file:s,content:o},u={terminals:e.terminals,palettes:e.palettes,...Object.fromEntries(Ce(e.terminals).flatMap((l)=>Object.entries(l.installs?.(t)??{}).filter(([,f])=>f!==void 0))),...e.off?{off:!0}:{}},c=ib(t.configHome,u,t.home);return{home:t.home,copies:r,edits:i,settings:a,catalog:Bf(t.root),installed:u,notes:c}}function _0(e){try{return ue(e)}catch{return}}function G0(e){try{return je(e,We(e),!1).palettes}catch{return[]}}function vN(e,t){let n=Bf(t.root),r=it(e.markets).includes(ee)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=G0(t.configHome).filter((o)=>!i.has(o.name)&&(ve(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function W0(e,t){let n=Tr(e);return n&&t.includes(n)?n:void 0}function MN(e,t,n){let r=$u(t,n),i=W0(e,t.palettes),s=new Set(["terminals","palettes","off","startup",...vt.flatMap((a)=>Object.keys(lr[a].installs?.(n)??{}))]),o=Object.fromEntries(Object.entries(e).filter(([a])=>!s.has(a)));return{...r,installed:{...o,...r.installed,...i?{startup:i}:{}}}}function SN(e,t){let n=$u({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...G0(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 IN(e){try{return pN(process.execPath,[ze(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function U0(e){let t=Jt(e);return[Ce(e.terminals).map((n)=>n.name).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function jf(e,t=Hr()){for(let o of e.copies)if(x0(Wi(o.to),{recursive:!0}),L0(o.to,{force:!0}),L0(`${o.to}.zwc`,{force:!0}),$N(o.from,o.to),o.executable)wN(o.to,493);Z(e.settings.file,e.settings.content);let n=Wi(Wi(e.settings.file)),r=_0(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=Ll(n,{...e.installed,...i},t,e.home);if(it(s.markets).includes(ee))fa(n,e.catalog);un(n,s),gt(n,We(n),s,e.home);for(let o of e.edits){x0(Wi(o.file),{recursive:!0});let a=Ui(o.file)?ku(o.file,"utf8"):"";xn(o.file,or(a,o.block))}return Ws(n,s,!0,t,e.home)}class hr extends Error{}function wu(e){if(ht(e))throw Yr("Nothing changed"),new hr;return e}function Kf(e,t){return vt.filter((n)=>lr[n].offered(e,t))}async function NN(e,t,n,r){return wu(await Gd({message:"Wire which terminals?",options:Kf(n,r).map((i)=>({value:i,label:lr[i].name,hint:i===e?"detected":void 0})),initialValues:t,required:!0}))}function Jf(e){let t=[...e.copies.filter((n)=>!Ui(n.to)).map((n)=>n.to),...Ui(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!ku(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
533
534
  ${t.join(`
534
- `)}`)}function y0(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function lN(e,t){let n=e.palettes.find((i)=>i.name===Jt(t)),r=n&&rr(process.env,process.stdout.isTTY===!0)?.wear(n,t.terminals);if(!r)return!1;return process.stdout.write(r),!0}function fN(e,t){let n=Jt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Or(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function dN(e){DI("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ze(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function hN(e,t,n,r){let i=y0(e.catalog,t.palettes);hr([`${i.join(", ")} (${t.palettes.length})`,...fN(e.installed,n)].join(`
535
- `),`Installed ${t.palettes.length} palettes`),hr(["exec zsh The ttheme command in this tab",...Af(e,r)].join(`
536
- `),"Next"),Fu("Done")}function Af(e,t){return[..._p(Gi(Gi(e.settings.file)),e.installed,t,e.home),...e.notes]}function E0(e){return e?(t)=>Pn.step(t):(t)=>console.log(t)}async function p0(e,t,n,r){let i=aN(e,t),s=Ff(i,n);Hf(i),await lu(t.configHome,E0(r),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...Af(i,s)],a=`Updated to ${ot.version} — kept ${k0(i.installed)}`;if(!r){console.log([a,...o].join(`
537
- `));return}hr(o.join(`
538
- `),a),Fu("Done")}function gN(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}`),...Af(e,t),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
539
- `))}async function v0(e={}){let t=ze(import.meta.dirname,"..");if(!_i(ze(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!_i(ze(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await cu()}let n=rN(),r=ge(),i=process.env.ZDOTDIR??n,s=Pr(),o=Rp(s),a=process.env.WT_PROFILE_ID,u={root:t,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...a?{wtProfile:a}:{}},c=Nr(process.env),l=Rf(u,s).filter((S)=>S===c||ur[S].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=b0(r);if(e.yes&&f){await p0(f,u,s,!1);return}if(e.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${Ce(Rf(u,s)).map((O)=>O.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let y=du({terminals:l,palettes:[]},u),N=Ff(y,s);Hf(y),gN(y,N);return}if(So("ttheme init"),f){let S=uN(r);if(fu(await Fn({message:`ttheme${S?` ${S}`:""} is installed — ${k0(f)}
540
- ${S===ot.version?"Reinstall":"Update to"} ${ot.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await p0(f,u,s,!0);return}}let d=await cN(c,f?.terminals??l,u,s),h=f?sN(f,u):Tf(t),g=f?await Nf(h,f.palettes,"palette",!0):await Nf(h,[],"series",!0);if(!g)throw Kr("Nothing changed"),new fr;let p=(f&&$0(f,g))??g[0],b=g.length>1&&nr[Nr(process.env)].paints,m=fu(await Fn({message:b?"Pick a default palette in ttheme preview once installed?":`Wear ${p} in every tab?`,initialValue:f?!f.off:!0})),$={terminals:d,palettes:g,off:!m},k=f?oN(f,$,u):du($,u);if(hr([`Install ${g.length} palettes — ${y0(h,g).join(", ")}`,`Copy ${k.copies.length} files under ${r}`,`Write ${k.settings.file}`,...k.edits.map((S)=>`Edit ${S.file} — a ttheme block: source ttheme.zsh`),...Cp(r,k.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",m?b?`Open ttheme preview — every tab wears the palette picked there, ${p} until then`:`Paint every tab with ${p}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...m&&p?Ce(d).flatMap((S)=>S.defaults?[`Make "${S.defaults.profile(p)}" the ${S.name} default profile`]:[]):[]].join(`
541
- `),`Wiring ${Ce(d).map((S)=>S.name).join(", ")}`),!fu(await Fn({message:"Apply these changes?"})))throw Kr("Nothing changed"),new fr;let M=Ff(k,s);if(Hf(k),await lu(r,E0(!0),n),m&&b)dN(r);let w=ce(r);hN({...k,catalog:h,installed:w},$,lN(h,w),M)}import{existsSync as S0,rmSync as mN,utimesSync as pN}from"node:fs";import{homedir as bN}from"node:os";import{join as fo}from"node:path";function wN(e){try{return ce(e)}catch{return}}function $N(e){let{home:t,configHome:n}=e,r=wN(n),i={configHome:n,home:t},s=Ce(vt),o=s.map((u)=>u.unwire(i,r)),a=[fo(n,"ttheme"),e.cacheDir,e.stateDir];return{edits:[...sn(fo(e.zdotdir,".zshrc"),sr),...o.flatMap((u)=>u.edits)],removals:[...s.flatMap((u)=>u.shelf?ha(u.shelf.dir(i)):[]),...o.flatMap((u)=>u.removals),...a.filter((u)=>S0(u))],touches:o.flatMap((u)=>u.touches),...r?{state:r}:{}}}function kN(e,t,n=Pr()){let r=[];for(let{file:s,content:o}of e.edits){let a=Wd(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=Ls(t.configHome,{...e.state,off:!0},!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)mN(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)pN(s,i,i);return r}function yN(){let e=bN();return{home:e,configHome:ge(),zdotdir:process.env.ZDOTDIR??e,cacheDir:ri(),stateDir:fo(process.env.XDG_STATE_HOME??fo(e,".local","state"),"ttheme")}}async function M0(e=!1){let t=yN(),n=$N(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=fo(t.configHome,"ttheme");So("ttheme uninstall"),hr([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${S0(ra(t.configHome))?`, and your markets under ${ra(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
542
- `),"Uninstall");let i=await Fn({message:"Remove ttheme?"});if(ht(i)||!i)throw Kr("Nothing changed"),new fr}for(let r of kN(n,t))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var vN=new Set(["add","remove","market","default","on","off"]),SN={default:([e])=>t0(e),on:()=>n0(),off:()=>r0(),browse:()=>c0(),list:([e],{json:t})=>o0(e,t),add:(e,{market:t})=>Dw(e,t),remove:(e)=>e0(e),update:()=>a0(),market:([e,t])=>gb(e,t),new:([e],{from:t,in:n})=>Yw(e,t,n),edit:([e])=>Qw(e),check:([e],{fix:t})=>Zw(e,t),share:([e])=>Xw(e),init:(e,{yes:t})=>v0({yes:t}),uninstall:(e,{yes:t})=>M0(t),build:(e,{only:t})=>cu({only:t}),find:([e])=>_w(e),image:([e,t,n])=>d0(e,t,n),redraw:()=>h0()},MN=Ns.map((e)=>({...e,run:SN[e.name]}));class _r extends Error{verb;constructor(e,t){super(e);this.verb=t}}function I0(e){let t=MN.find((n)=>n.name===e);if(!t)throw new _r(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function IN(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 EN({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new _r(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function NN(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:I0(n[0]),code:0}}let r=I0(t),i=IN(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 _r(`--${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 _r(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new _r(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function N0(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function Lf(e,t=!1){if(!e)return Ps(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Is(e)}`,"",e.about,...e.actions?["","Actions:",...N0(e.actions)]:[],...n.length>0?["","Options:",...N0(n)]:[]].join(`
543
- `)}async function P0(e){let t;try{let n=NN(e);if(n.kind==="version")return console.log(ot.version),0;if(n.kind==="help"){if(n.code===0)console.log(Lf(n.verb,n.all));else console.error(Lf(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(vN.has(n.verb.name))await Xp();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof _r)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
535
+ `)}`)}function j0(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function PN(e,t){let n=e.palettes.find((i)=>i.name===Jt(t)),r=n&&sr(process.env,process.stdout.isTTY===!0)?.wear(n,t.terminals);if(!r)return!1;return process.stdout.write(r),!0}function ON(e,t){let n=Jt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Tr(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function RN(e){bN("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ze(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function FN(e,t,n,r){let i=j0(e.catalog,t.palettes);mr([`${i.join(", ")} (${t.palettes.length})`,...ON(e.installed,n)].join(`
536
+ `),`Installed ${t.palettes.length} palettes`),mr(["exec zsh The ttheme command in this tab",...qf(e,r)].join(`
537
+ `),"Next"),Cu("Done")}function qf(e,t){return[...sb(Wi(Wi(e.settings.file)),e.installed,t,e.home),...e.notes]}function K0(e){return e?(t)=>Pn.step(t):(t)=>console.log(t)}async function C0(e,t,n,r){let i=SN(e,t),s=jf(i,n);Jf(i),await bu(t.configHome,K0(r),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...qf(i,s)],a=`Updated to ${ot.version} — kept ${U0(i.installed)}`;if(!r){console.log([a,...o].join(`
538
+ `));return}mr(o.join(`
539
+ `),a),Cu("Done")}function HN(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}`),...qf(e,t),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
540
+ `))}async function J0(e={}){let t=ze(import.meta.dirname,"..");if(!Ui(ze(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Ui(ze(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await pu()}let n=yN(),r=ge(),i=process.env.ZDOTDIR??n,s=Hr(),o=Zp(s),a=process.env.WT_PROFILE_ID,u={root:t,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...a?{wtProfile:a}:{}},c=Or(process.env),l=Kf(u,s).filter((M)=>M===c||lr[M].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=_0(r);if(e.yes&&f){await C0(f,u,s,!1);return}if(e.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${Ce(Kf(u,s)).map((O)=>O.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let y=$u({terminals:l,palettes:[]},u),N=jf(y,s);Jf(y),HN(y,N);return}if(Oo("ttheme init"),f){let M=IN(r);if(wu(await Rn({message:`ttheme${M?` ${M}`:""} is installed — ${U0(f)}
541
+ ${M===ot.version?"Reinstall":"Update to"} ${ot.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await C0(f,u,s,!0);return}}let d=await NN(c,f?.terminals??l,u,s),h=f?vN(f,u):Bf(t),g=f?await Gf(h,f.palettes,"palette",!0):await Gf(h,[],"series",!0);if(!g)throw Yr("Nothing changed"),new hr;let p=(f&&W0(f,g))??g[0],b=g.length>1&&ir[Or(process.env)].paints,m=wu(await Rn({message:b?"Pick a default palette in ttheme preview once installed?":`Wear ${p} in every tab?`,initialValue:f?!f.off:!0})),$={terminals:d,palettes:g,off:!m},k=f?MN(f,$,u):$u($,u);if(mr([`Install ${g.length} palettes — ${j0(h,g).join(", ")}`,`Copy ${k.copies.length} files under ${r}`,`Write ${k.settings.file}`,...k.edits.map((M)=>`Edit ${M.file} — a ttheme block: source ttheme.zsh`),...rb(r,k.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",m?b?`Open ttheme preview — every tab wears the palette picked there, ${p} until then`:`Paint every tab with ${p}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...m&&p?Ce(d).flatMap((M)=>M.defaults?[`Make "${M.defaults.profile(p)}" the ${M.name} default profile`]:[]):[]].join(`
542
+ `),`Wiring ${Ce(d).map((M)=>M.name).join(", ")}`),!wu(await Rn({message:"Apply these changes?"})))throw Yr("Nothing changed"),new hr;let S=jf(k,s);if(Jf(k),await bu(r,K0(!0),n),m&&b)RN(r);let w=ue(r);FN({...k,catalog:h,installed:w},$,PN(h,w),S)}import{existsSync as B0,rmSync as TN,utimesSync as AN}from"node:fs";import{homedir as xN}from"node:os";import{join as bo}from"node:path";function LN(e){try{return ue(e)}catch{return}}function CN(e){let{home:t,configHome:n}=e,r=LN(n),i={configHome:n,home:t},s=Ce(vt),o=s.map((u)=>u.unwire(i,r)),a=[bo(n,"ttheme"),e.cacheDir,e.stateDir];return{edits:[...on(bo(e.zdotdir,".zshrc"),ar),...o.flatMap((u)=>u.edits)],removals:[...s.flatMap((u)=>u.shelf?$a(u.shelf.dir(i)):[]),...o.flatMap((u)=>u.removals),...a.filter((u)=>B0(u))],touches:o.flatMap((u)=>u.touches),...r?{state:r}:{}}}function _N(e,t,n=Hr()){let r=[];for(let{file:s,content:o}of e.edits){let a=Xd(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=Ws(t.configHome,{...e.state,off:!0},!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)TN(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)AN(s,i,i);return r}function GN(){let e=xN();return{home:e,configHome:ge(),zdotdir:process.env.ZDOTDIR??e,cacheDir:ui(),stateDir:bo(process.env.XDG_STATE_HOME??bo(e,".local","state"),"ttheme")}}async function q0(e=!1){let t=GN(),n=CN(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=bo(t.configHome,"ttheme");Oo("ttheme uninstall"),mr([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${B0(ua(t.configHome))?`, and your markets under ${ua(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
543
+ `),"Uninstall");let i=await Rn({message:"Remove ttheme?"});if(ht(i)||!i)throw Yr("Nothing changed"),new hr}for(let r of _N(n,t))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var UN=new Set(["add","remove","market","default","on","off"]),jN={default:([e])=>k0(e),on:()=>y0(),off:()=>E0(),browse:()=>P0(),list:([e],{json:t})=>S0(e,t),add:(e,{market:t})=>w0(e,t),remove:(e)=>$0(e),update:()=>I0(),market:([e,t])=>Tb(e,t),new:([e],{from:t,in:n})=>h0(e,t,n),edit:([e])=>g0(e),check:([e],{fix:t})=>p0(e,t),share:([e])=>b0(e),init:(e,{yes:t})=>J0({yes:t}),uninstall:(e,{yes:t})=>q0(t),build:(e,{only:t})=>pu({only:t}),find:([e])=>i0(e),image:([e,t,n])=>A0(e,t,n),redraw:()=>T0()},KN=Hs.map((e)=>({...e,run:jN[e.name]}));class Jr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function z0(e){let t=KN.find((n)=>n.name===e);if(!t)throw new Jr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function JN(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 WN({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Jr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function BN(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:z0(n[0]),code:0}}let r=z0(t),i=JN(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 Jr(`--${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 Jr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new Jr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function Y0(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function zf(e,t=!1){if(!e)return Ts(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${Fs(e)}`,"",e.about,...e.actions?["","Actions:",...Y0(e.actions)]:[],...n.length>0?["","Options:",...Y0(n)]:[]].join(`
544
+ `)}async function Q0(e){let t;try{let n=BN(e);if(n.kind==="version")return console.log(ot.version),0;if(n.kind==="help"){if(n.code===0)console.log(zf(n.verb,n.all));else console.error(zf(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(UN.has(n.verb.name))await bb();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Jr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
544
545
 
545
- ${Lf(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof fr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
546
- ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(ON)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=PN(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await P0(process.argv.slice(2));
546
+ ${zf(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof hr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
547
+ ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(zN)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=qN(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await Q0(process.argv.slice(2));
547
548
 
548
- //# debugId=DA18B60B92B48EDA64756E2164756E21
549
+ //# debugId=B98FA3A5911EDAF264756E2164756E21
549
550
  //# sourceMappingURL=ttheme.js.map