@kecan0406/ttheme 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ttheme.js CHANGED
@@ -1,74 +1,74 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as G$}from"node:module";var H$=Object.create;var{getPrototypeOf:T$,defineProperty:Sd,getOwnPropertyNames:x$}=Object;var A$=Object.prototype.hasOwnProperty;function L$(e){return this[e]}var C$,_$,Fo=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?C$??=new WeakMap:_$??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?H$(T$(e)):{};let o=t||!e||!e.__esModule?Sd(n,"default",{value:e,enumerable:!0}):n;for(let a of x$(e))if(!A$.call(o,a))Sd(o,a,{get:L$.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=G$(import.meta.url);var ju=Te((qP,Wd)=>{var Uu={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"},ek={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},tk={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?Uu.up():"");if(e)t+=Uu.left;return t}};Wd.exports={cursor:Uu,scroll:ek,erase:tk,beep:"\x07"}});var $h=Te((IO,Ko)=>{var wh=wh||function(e){return Buffer.from(e).toString("base64")};function Qk(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,f,d=Array(65535),h=Array(65535),g=Array(64),b=Array(64),p=[],m=0,$=7,E=Array(64),M=Array(64),w=Array(64),S=Array(256),k=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],x=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],W=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],A=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],F=[0,1,2,3,4,5,6,7,8,9,10,11],q=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ee=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function be(y){var G=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var z=0;z<64;z++){var j=r((G[z]*y+50)/100);if(j<1)j=1;else if(j>255)j=255;i[O[z]]=j}var te=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var ne=0;ne<64;ne++){var me=r((te[ne]*y+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 Q(y,G){var z=0,j=0,te=[];for(var ne=1;ne<=16;ne++){for(var me=1;me<=y[ne];me++)te[G[j]]=[],te[G[j]][0]=z,te[G[j]][1]=ne,j++,z++;z*=2}return te}function Ae(){u=Q(T,x),c=Q(A,F),l=Q(C,W),f=Q(q,Ee)}function he(){var y=1,G=2;for(var z=1;z<=15;z++){for(var j=y;j<G;j++)h[32767+j]=z,d[32767+j]=[],d[32767+j][1]=z,d[32767+j][0]=j;for(var te=-(G-1);te<=-y;te++)h[32767+te]=z,d[32767+te]=[],d[32767+te][1]=z,d[32767+te][0]=G-1+te;y<<=1,G<<=1}}function ue(){for(var y=0;y<256;y++)k[y]=19595*y,k[y+256>>0]=38470*y,k[y+512>>0]=7471*y+32768,k[y+768>>0]=-11059*y,k[y+1024>>0]=-21709*y,k[y+1280>>0]=32768*y+8421375,k[y+1536>>0]=-27439*y,k[y+1792>>0]=-5329*y}function ie(y){var G=y[0],z=y[1]-1;while(z>=0){if(G&1<<z)m|=1<<$;if(z--,$--,$<0){if(m==255)v(255),v(0);else v(m);$=7,m=0}}}function v(y){p.push(y)}function U(y){v(y>>8&255),v(y&255)}function Ne(y,G){var z,j,te,ne,me,pe,Ue,He,P=0,L,Z=8,Ge=64;for(L=0;L<Z;++L){z=y[P],j=y[P+1],te=y[P+2],ne=y[P+3],me=y[P+4],pe=y[P+5],Ue=y[P+6],He=y[P+7];var re=z+He,ce=z-He,Oe=j+Ue,Y=j-Ue,we=te+pe,tt=te-pe,Le=ne+me,Ot=ne-me,Zt=re+Le,Er=re-Le,Dr=Oe+we,ei=Oe-we;y[P]=Zt+Dr,y[P+4]=Zt-Dr;var Qi=(ei+Er)*0.707106781;y[P+2]=Er+Qi,y[P+6]=Er-Qi,Zt=Ot+tt,Dr=tt+Y,ei=Y+ce;var Vi=(Zt-ei)*0.382683433,No=0.5411961*Zt+Vi,Zi=1.306562965*ei+Vi,Xi=Dr*0.707106781,Di=ce+Xi,es=ce-Xi;y[P+5]=es+No,y[P+3]=es-No,y[P+1]=Di+Zi,y[P+7]=Di-Zi,P+=8}P=0;for(L=0;L<Z;++L){z=y[P],j=y[P+8],te=y[P+16],ne=y[P+24],me=y[P+32],pe=y[P+40],Ue=y[P+48],He=y[P+56];var dd=z+He,Lu=z-He,hd=j+Ue,gd=j-Ue,md=te+pe,pd=te-pe,bd=ne+me,F$=ne-me,ts=dd+bd,Cu=dd-bd,Po=hd+md,Oo=hd-md;y[P]=ts+Po,y[P+32]=ts-Po;var wd=(Oo+Cu)*0.707106781;y[P+16]=Cu+wd,y[P+48]=Cu-wd,ts=F$+pd,Po=pd+gd,Oo=gd+Lu;var $d=(ts-Oo)*0.382683433,kd=0.5411961*ts+$d,yd=1.306562965*Oo+$d,Ed=Po*0.707106781,vd=Lu+Ed,Md=Lu-Ed;y[P+40]=Md+kd,y[P+24]=Md-kd,y[P+8]=vd+yd,y[P+56]=vd-yd,P++}var Ro;for(L=0;L<Ge;++L)Ro=y[L]*G[L],g[L]=Ro>0?Ro+0.5|0:Ro-0.5|0;return g}function Pe(){U(65504),U(16),v(74),v(70),v(73),v(70),v(0),v(1),v(1),v(0),U(1),U(1),v(0),v(0)}function fe(y){if(!y)return;if(U(65505),y[0]===69&&y[1]===120&&y[2]===105&&y[3]===102)U(y.length+2);else U(y.length+5+2),v(69),v(120),v(105),v(102),v(0);for(var G=0;G<y.length;G++)v(y[G])}function de(y,G){U(65472),U(17),v(8),U(G),U(y),v(3),v(1),v(17),v(0),v(2),v(17),v(1),v(3),v(17),v(1)}function oe(){U(65499),U(132),v(0);for(var y=0;y<64;y++)v(i[y]);v(1);for(var G=0;G<64;G++)v(s[G])}function H(){U(65476),U(418),v(0);for(var y=0;y<16;y++)v(T[y+1]);for(var G=0;G<=11;G++)v(x[G]);v(16);for(var z=0;z<16;z++)v(C[z+1]);for(var j=0;j<=161;j++)v(W[j]);v(1);for(var te=0;te<16;te++)v(A[te+1]);for(var ne=0;ne<=11;ne++)v(F[ne]);v(17);for(var me=0;me<16;me++)v(q[me+1]);for(var pe=0;pe<=161;pe++)v(Ee[pe])}function R(y){if(typeof y>"u"||y.constructor!==Array)return;y.forEach((G)=>{if(typeof G!=="string")return;U(65534);var z=G.length;U(z+2);var j;for(j=0;j<z;j++)v(G.charCodeAt(j))})}function Fe(){U(65498),U(12),v(3),v(1),v(0),v(2),v(17),v(3),v(17),v(0),v(63),v(0)}function V(y,G,z,j,te){var ne=te[0],me=te[240],pe,Ue=16,He=63,P=64,L=Ne(y,G);for(var Z=0;Z<P;++Z)b[O[Z]]=L[Z];var Ge=b[0]-z;if(z=b[0],Ge==0)ie(j[0]);else pe=32767+Ge,ie(j[h[pe]]),ie(d[pe]);var re=63;for(;re>0&&b[re]==0;re--);if(re==0)return ie(ne),z;var ce=1,Oe;while(ce<=re){var Y=ce;for(;b[ce]==0&&ce<=re;++ce);var we=ce-Y;if(we>=Ue){Oe=we>>4;for(var tt=1;tt<=Oe;++tt)ie(me);we=we&15}pe=32767+b[ce],ie(te[(we<<4)+h[pe]]),ie(d[pe]),ce++}if(re!=He)ie(ne);return z}function ae(){var y=String.fromCharCode;for(var G=0;G<256;G++)S[G]=y(G)}this.encode=function(y,G){var z=new Date().getTime();if(G)Pt(G);p=[],m=0,$=7,U(65496),Pe(),R(y.comments),fe(y.exifBuffer),oe(),de(y.width,y.height),H(),Fe();var j=0,te=0,ne=0;m=0,$=7,this.encode.displayName="_encode_";var{data:me,width:pe,height:Ue}=y,He=pe*4,P=pe*3,L,Z=0,Ge,re,ce,Oe,Y,we,tt,Le;while(Z<Ue){L=0;while(L<He){Oe=He*Z+L,Y=Oe,we=-1,tt=0;for(Le=0;Le<64;Le++){if(tt=Le>>3,we=(Le&7)*4,Y=Oe+tt*He+we,Z+tt>=Ue)Y-=He*(Z+1+tt-Ue);if(L+we>=He)Y-=L+we-He+4;Ge=me[Y++],re=me[Y++],ce=me[Y++],E[Le]=(k[Ge]+k[re+256>>0]+k[ce+512>>0]>>16)-128,M[Le]=(k[Ge+768>>0]+k[re+1024>>0]+k[ce+1280>>0]>>16)-128,w[Le]=(k[Ge+1280>>0]+k[re+1536>>0]+k[ce+1792>>0]>>16)-128}j=V(E,o,j,u,l),te=V(M,a,te,c,f),ne=V(w,a,ne,c,f),L+=32}Z+=8}if($>=0){var Ot=[];Ot[1]=$+1,Ot[0]=(1<<$+1)-1,ie(Ot)}if(U(65497),typeof Ko>"u")return new Uint8Array(p);return Buffer.from(p);var Zt,Er};function Pt(y){if(y<=0)y=1;if(y>100)y=100;if(N==y)return;var G=0;if(y<50)G=Math.floor(5000/y);else G=Math.floor(200-y*2);be(G),N=y}function Wt(){var y=new Date().getTime();if(!e)e=50;ae(),Ae(),he(),ue(),Pt(e);var G=new Date().getTime()-y}Wt()}if(typeof Ko<"u")Ko.exports=bh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=bh;function bh(e,t){if(typeof t>"u")t=50;var n=new Qk(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var yh=Te((NO,uc)=>{var ac=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($,E){var M=0,w=[],S,k,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(k=0;k<$[S];k++){O=w.pop(),O.children[O.index]=E[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($,E,M,w,S,k,N,O,T,x){var{precision:C,samplesPerLine:W,scanLines:A,mcusPerLine:F,progressive:q,maxH:Ee,maxV:be}=M,Q=E,Ae=0,he=0;function ue(){if(he>0)return he--,Ae>>he&1;if(Ae=$[E++],Ae==255){var P=$[E++];if(P)throw Error("unexpected marker: "+(Ae<<8|P).toString(16))}return he=7,Ae>>>7}function ie(P){var L=P,Z;while((Z=ue())!==null){if(L=L[Z],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 Z=ue();if(Z===null)return;L=L<<1|Z,P--}return L}function U(P){var L=v(P);if(L>=1<<P-1)return L;return L+(-1<<P)+1}function Ne(P,L){var Z=ie(P.huffmanTableDC),Ge=Z===0?0:U(Z);L[0]=P.pred+=Ge;var re=1;while(re<64){var ce=ie(P.huffmanTableAC),Oe=ce&15,Y=ce>>4;if(Oe===0){if(Y<15)break;re+=16;continue}re+=Y;var we=t[re];L[we]=U(Oe),re++}}function Pe(P,L){var Z=ie(P.huffmanTableDC),Ge=Z===0?0:U(Z)<<T;L[0]=P.pred+=Ge}function fe(P,L){L[0]|=ue()<<T}var de=0;function oe(P,L){if(de>0){de--;return}var Z=k,Ge=N;while(Z<=Ge){var re=ie(P.huffmanTableAC),ce=re&15,Oe=re>>4;if(ce===0){if(Oe<15){de=v(Oe)+(1<<Oe)-1;break}Z+=16;continue}Z+=Oe;var Y=t[Z];L[Y]=U(ce)*(1<<T),Z++}}var H=0,R;function Fe(P,L){var Z=k,Ge=N,re=0;while(Z<=Ge){var ce=t[Z],Oe=L[ce]<0?-1:1;switch(H){case 0:var Y=ie(P.huffmanTableAC),we=Y&15,re=Y>>4;if(we===0)if(re<15)de=v(re)+(1<<re),H=4;else re=16,H=1;else{if(we!==1)throw Error("invalid ACn encoding");R=U(we),H=re?2:3}continue;case 1:case 2:if(L[ce])L[ce]+=(ue()<<T)*Oe;else if(re--,re===0)H=H==2?3:0;break;case 3:if(L[ce])L[ce]+=(ue()<<T)*Oe;else L[ce]=R<<T,H=0;break;case 4:if(L[ce])L[ce]+=(ue()<<T)*Oe;break}Z++}if(H===4){if(de--,de===0)H=0}}function V(P,L,Z,Ge,re){var ce=Z/F|0,Oe=Z%F,Y=ce*P.v+Ge,we=Oe*P.h+re;if(P.blocks[Y]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[Y][we])}function ae(P,L,Z){var Ge=Z/P.blocksPerLine|0,re=Z%P.blocksPerLine;if(P.blocks[Ge]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[Ge][re])}var Pt=w.length,Wt,y,G,z,j,te;if(q)if(k===0)te=O===0?Pe:fe;else te=O===0?oe:Fe;else te=Ne;var ne=0,me,pe;if(Pt==1)pe=w[0].blocksPerLine*w[0].blocksPerColumn;else pe=F*M.mcusPerColumn;if(!S)S=pe;var Ue,He;while(ne<pe){for(y=0;y<Pt;y++)w[y].pred=0;if(de=0,Pt==1){Wt=w[0];for(j=0;j<S;j++)ae(Wt,te,ne),ne++}else for(j=0;j<S;j++){for(y=0;y<Pt;y++){Wt=w[y],Ue=Wt.h,He=Wt.v;for(G=0;G<He;G++)for(z=0;z<Ue;z++)V(Wt,te,ne,G,z)}if(ne++,ne===pe)break}if(ne===pe)do{if($[E]===255){if($[E+1]!==0)break}E+=1}while(E<$.length-2);if(he=0,me=$[E]<<8|$[E+1],me<65280)throw Error("marker was not found");if(me>=65488&&me<=65495)E+=2;else break}return E-Q}function h($,E){var M=[],w=E.blocksPerLine,S=E.blocksPerColumn,k=w<<3,N=new Int32Array(64),O=new Uint8Array(64);function T(Q,Ae,he){var ue=E.quantizationTable,ie,v,U,Ne,Pe,fe,de,oe,H,R=he,Fe;for(Fe=0;Fe<64;Fe++)R[Fe]=Q[Fe]*ue[Fe];for(Fe=0;Fe<8;++Fe){var V=8*Fe;if(R[1+V]==0&&R[2+V]==0&&R[3+V]==0&&R[4+V]==0&&R[5+V]==0&&R[6+V]==0&&R[7+V]==0){H=u*R[0+V]+512>>10,R[0+V]=H,R[1+V]=H,R[2+V]=H,R[3+V]=H,R[4+V]=H,R[5+V]=H,R[6+V]=H,R[7+V]=H;continue}ie=u*R[0+V]+128>>8,v=u*R[4+V]+128>>8,U=R[2+V],Ne=R[6+V],Pe=c*(R[1+V]-R[7+V])+128>>8,oe=c*(R[1+V]+R[7+V])+128>>8,fe=R[3+V]<<4,de=R[5+V]<<4,H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=U*a+Ne*o+128>>8,U=U*o-Ne*a+128>>8,Ne=H,H=Pe-de+1>>1,Pe=Pe+de+1>>1,de=H,H=oe+fe+1>>1,fe=oe-fe+1>>1,oe=H,H=ie-Ne+1>>1,ie=ie+Ne+1>>1,Ne=H,H=v-U+1>>1,v=v+U+1>>1,U=H,H=Pe*s+oe*i+2048>>12,Pe=Pe*i-oe*s+2048>>12,oe=H,H=fe*r+de*n+2048>>12,fe=fe*n-de*r+2048>>12,de=H,R[0+V]=ie+oe,R[7+V]=ie-oe,R[1+V]=v+de,R[6+V]=v-de,R[2+V]=U+fe,R[5+V]=U-fe,R[3+V]=Ne+Pe,R[4+V]=Ne-Pe}for(Fe=0;Fe<8;++Fe){var ae=Fe;if(R[8+ae]==0&&R[16+ae]==0&&R[24+ae]==0&&R[32+ae]==0&&R[40+ae]==0&&R[48+ae]==0&&R[56+ae]==0){H=u*he[Fe+0]+8192>>14,R[0+ae]=H,R[8+ae]=H,R[16+ae]=H,R[24+ae]=H,R[32+ae]=H,R[40+ae]=H,R[48+ae]=H,R[56+ae]=H;continue}ie=u*R[0+ae]+2048>>12,v=u*R[32+ae]+2048>>12,U=R[16+ae],Ne=R[48+ae],Pe=c*(R[8+ae]-R[56+ae])+2048>>12,oe=c*(R[8+ae]+R[56+ae])+2048>>12,fe=R[24+ae],de=R[40+ae],H=ie-v+1>>1,ie=ie+v+1>>1,v=H,H=U*a+Ne*o+2048>>12,U=U*o-Ne*a+2048>>12,Ne=H,H=Pe-de+1>>1,Pe=Pe+de+1>>1,de=H,H=oe+fe+1>>1,fe=oe-fe+1>>1,oe=H,H=ie-Ne+1>>1,ie=ie+Ne+1>>1,Ne=H,H=v-U+1>>1,v=v+U+1>>1,U=H,H=Pe*s+oe*i+2048>>12,Pe=Pe*i-oe*s+2048>>12,oe=H,H=fe*r+de*n+2048>>12,fe=fe*n-de*r+2048>>12,de=H,R[0+ae]=ie+oe,R[56+ae]=ie-oe,R[8+ae]=v+de,R[48+ae]=v-de,R[16+ae]=U+fe,R[40+ae]=U-fe,R[24+ae]=Ne+Pe,R[32+ae]=Ne-Pe}for(Fe=0;Fe<64;++Fe){var Pt=128+(R[Fe]+8>>4);Ae[Fe]=Pt<0?0:Pt>255?255:Pt}}m(k*S*8);var x,C;for(var W=0;W<S;W++){var A=W<<3;for(x=0;x<8;x++)M.push(new Uint8Array(k));for(var F=0;F<w;F++){T(E.blocks[W][F],O,N);var q=0,Ee=F<<3;for(C=0;C<8;C++){var be=M[A+C];for(x=0;x<8;x++)be[Ee+x]=O[q++]}}}return M}function g($){return $<0?0:$>255?255:$}l.prototype={load:function(E){var M=new XMLHttpRequest;M.open("GET",E,!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(E){var M=this.opts.maxResolutionInMP*1000*1000,w=0,S=E.length;function k(){var Y=E[w]<<8|E[w+1];return w+=2,Y}function N(){var Y=k(),we=E.subarray(w,w+Y-2);return w+=we.length,we}function O(Y){var we=1,tt=1,Le,Ot;for(Ot in Y.components)if(Y.components.hasOwnProperty(Ot)){if(Le=Y.components[Ot],we<Le.h)we=Le.h;if(tt<Le.v)tt=Le.v}var Zt=Math.ceil(Y.samplesPerLine/8/we),Er=Math.ceil(Y.scanLines/8/tt);for(Ot in Y.components)if(Y.components.hasOwnProperty(Ot)){Le=Y.components[Ot];var Dr=Math.ceil(Math.ceil(Y.samplesPerLine/8)*Le.h/we),ei=Math.ceil(Math.ceil(Y.scanLines/8)*Le.v/tt),Qi=Zt*Le.h,Vi=Er*Le.v,No=Vi*Qi,Zi=[];m(No*256);for(var Xi=0;Xi<Vi;Xi++){var Di=[];for(var es=0;es<Qi;es++)Di.push(new Int32Array(64));Zi.push(Di)}Le.blocksPerLine=Dr,Le.blocksPerColumn=ei,Le.blocks=Zi}Y.maxH=we,Y.maxV=tt,Y.mcusPerLine=Zt,Y.mcusPerColumn=Er}var T=null,x=null,C=null,W,A,F=[],q=[],Ee=[],be=[],Q=k(),Ae=-1;if(this.comments=[],Q!=65496)throw Error("SOI not found");Q=k();while(Q!=65497){var he,ue,ie;switch(Q){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(Q===65534){var U=String.fromCharCode.apply(null,v);this.comments.push(U)}if(Q===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(Q===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(Q===65518){if(v[0]===65&&v[1]===100&&v[2]===111&&v[3]===98&&v[4]===101&&v[5]===0)x={version:v[6],flags0:v[7]<<8|v[8],flags1:v[9]<<8|v[10],transformCode:v[11]}}break;case 65499:var Ne=k(),Pe=Ne+w-2;while(w<Pe){var fe=E[w++];m(256);var de=new Int32Array(64);if(fe>>4===0)for(ue=0;ue<64;ue++){var oe=t[ue];de[oe]=E[w++]}else if(fe>>4===1)for(ue=0;ue<64;ue++){var oe=t[ue];de[oe]=k()}else throw Error("DQT: invalid table spec");F[fe&15]=de}break;case 65472:case 65473:case 65474:k(),W={},W.extended=Q===65473,W.progressive=Q===65474,W.precision=E[w++],W.scanLines=k(),W.samplesPerLine=k(),W.components={},W.componentsOrder=[];var H=W.scanLines*W.samplesPerLine;if(H>M){var R=Math.ceil((H-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${R}MP`)}var Fe=E[w++],V,ae=0,Pt=0;for(he=0;he<Fe;he++){V=E[w];var Wt=E[w+1]>>4,y=E[w+1]&15,G=E[w+2];if(Wt<=0||y<=0)throw Error("Invalid sampling factor, expected values above 0");W.componentsOrder.push(V),W.components[V]={h:Wt,v:y,quantizationIdx:G},w+=3}O(W),q.push(W);break;case 65476:var z=k();for(he=2;he<z;){var j=E[w++],te=new Uint8Array(16),ne=0;for(ue=0;ue<16;ue++,w++)ne+=te[ue]=E[w];m(16+ne);var me=new Uint8Array(ne);for(ue=0;ue<ne;ue++,w++)me[ue]=E[w];he+=17+ne,(j>>4===0?be:Ee)[j&15]=f(te,me)}break;case 65501:k(),A=k();break;case 65500:k(),k();break;case 65498:var pe=k(),Ue=E[w++],He=[],P;for(he=0;he<Ue;he++){P=W.components[E[w++]];var L=E[w++];P.huffmanTableDC=be[L>>4],P.huffmanTableAC=Ee[L&15],He.push(P)}var Z=E[w++],Ge=E[w++],re=E[w++],ce=d(E,w,W,He,A,Z,Ge,re>>4,re&15,this.opts);w+=ce;break;case 65535:if(E[w]!==255)w--;break;default:if(E[w-3]==255&&E[w-2]>=192&&E[w-2]<=254){w-=3;break}else if(Q===224||Q==225){if(Ae!==-1)throw Error(`first unknown JPEG marker at offset ${Ae.toString(16)}, second unknown JPEG marker ${Q.toString(16)} at offset ${(w-1).toString(16)}`);Ae=w-1;let Y=k();if(E[w+Y-2]===255){w+=Y-2;break}}throw Error("unknown JPEG marker "+Q.toString(16))}Q=k()}if(q.length!=1)throw Error("only single frame JPEGs supported");for(var he=0;he<q.length;he++){var Oe=q[he].components;for(var ue in Oe)Oe[ue].quantizationTable=F[Oe[ue].quantizationIdx],delete Oe[ue].quantizationIdx}this.width=W.samplesPerLine,this.height=W.scanLines,this.jfif=T,this.adobe=x,this.components=[];for(var he=0;he<W.componentsOrder.length;he++){var P=W.components[W.componentsOrder[he]];this.components.push({lines:h(W,P),scaleX:P.h/W.maxH,scaleY:P.v/W.maxV})}},getData:function(E,M){var w=this.width/E,S=this.height/M,k,N,O,T,x,C,W,A,F,q,Ee=0,be,Q,Ae,he,ue,ie,v,U,Ne,Pe,fe,de=E*M*this.components.length;m(de);var oe=new Uint8Array(de);switch(this.components.length){case 1:k=this.components[0];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S];for(F=0;F<E;F++)be=x[0|F*k.scaleX*w],oe[Ee++]=be}break;case 2:k=this.components[0],N=this.components[1];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S];for(F=0;F<E;F++)be=x[0|F*k.scaleX*w],oe[Ee++]=be,be=C[0|F*N.scaleX*w],oe[Ee++]=be}break;case 3:if(fe=!0,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;k=this.components[0],N=this.components[1],O=this.components[2];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S],W=O.lines[0|q*O.scaleY*S];for(F=0;F<E;F++){if(!fe)U=x[0|F*k.scaleX*w],Ne=C[0|F*N.scaleX*w],Pe=W[0|F*O.scaleX*w];else be=x[0|F*k.scaleX*w],Q=C[0|F*N.scaleX*w],Ae=W[0|F*O.scaleX*w],U=g(be+1.402*(Ae-128)),Ne=g(be-0.3441363*(Q-128)-0.71413636*(Ae-128)),Pe=g(be+1.772*(Q-128));oe[Ee++]=U,oe[Ee++]=Ne,oe[Ee++]=Pe}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(fe=!1,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;k=this.components[0],N=this.components[1],O=this.components[2],T=this.components[3];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S],W=O.lines[0|q*O.scaleY*S],A=T.lines[0|q*T.scaleY*S];for(F=0;F<E;F++){if(!fe)ue=x[0|F*k.scaleX*w],ie=C[0|F*N.scaleX*w],v=W[0|F*O.scaleX*w],he=A[0|F*T.scaleX*w];else be=x[0|F*k.scaleX*w],Q=C[0|F*N.scaleX*w],Ae=W[0|F*O.scaleX*w],he=A[0|F*T.scaleX*w],ue=255-g(be+1.402*(Ae-128)),ie=255-g(be-0.3441363*(Q-128)-0.71413636*(Ae-128)),v=255-g(be+1.772*(Q-128));oe[Ee++]=255-ue,oe[Ee++]=255-ie,oe[Ee++]=255-v,oe[Ee++]=255-he}}break;default:throw Error("Unsupported color mode")}return oe},copyToImageData:function(E,M){var{width:w,height:S,data:k}=E,N=this.getData(w,S),O=0,T=0,x,C,W,A,F,q,Ee,be,Q;switch(this.components.length){case 1:for(C=0;C<S;C++)for(x=0;x<w;x++)if(W=N[O++],k[T++]=W,k[T++]=W,k[T++]=W,M)k[T++]=255;break;case 3:for(C=0;C<S;C++)for(x=0;x<w;x++)if(Ee=N[O++],be=N[O++],Q=N[O++],k[T++]=Ee,k[T++]=be,k[T++]=Q,M)k[T++]=255;break;case 4:for(C=0;C<S;C++)for(x=0;x<w;x++)if(F=N[O++],q=N[O++],W=N[O++],A=N[O++],Ee=255-g(F*(1-A/255)+A),be=255-g(q*(1-A/255)+A),Q=255-g(W*(1-A/255)+A),k[T++]=Ee,k[T++]=be,k[T++]=Q,M)k[T++]=255;break;default:throw Error("Unsupported color mode")}}};var b=0,p=0;function m($=0){var E=b+$;if(E>p){var M=Math.ceil((E-p)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}b=E}return l.resetMaxMemoryUsage=function($){b=0,p=$},l.getBytesAllocated=function(){return b},l.requestMemoryAllocation=m,l}();if(typeof uc<"u")uc.exports=kh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=kh;function kh(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 ac;s.opts=r,ac.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{ac.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 vh=Te((PO,Eh)=>{var Vk=$h(),Zk=yh();Eh.exports={encode:Vk,decode:Zk}});var cc=Te((OO,Sh)=>{var Xk=st("util"),Mh=st("stream"),jt=Sh.exports=function(){Mh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Xk.inherits(jt,Mh);jt.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))};jt.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};jt.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()};jt.prototype.destroySoon=jt.prototype.end;jt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};jt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};jt.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)};jt.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)};jt.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 lc=Te((Dk)=>{var Wn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Dk.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<Wn.length;a++){let u=Wn[a],c=s*u.x.length,l=o*u.y.length;for(let f=0;f<u.x.length;f++)if(u.x[f]<r)c++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};Dk.getInterlaceIterator=function(e){return function(t,n,r){let i=t%Wn[r].x.length,s=(t-i)/Wn[r].x.length*8+Wn[r].x[i],o=n%Wn[r].y.length,a=(n-o)/Wn[r].y.length*8+Wn[r].y[o];return s*4+a*e*4}}});var fc=Te((FO,Ih)=>{Ih.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 dc=Te((HO,Ph)=>{var ny=lc(),ry=fc();function Nh(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var ui=Ph.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=ny.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Nh(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Nh(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};ui.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ui.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}};ui.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}};ui.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}};ui.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=ry(c,u,l);t[o]=a+f}};ui.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 Fh=Te((TO,Rh)=>{var iy=st("util"),Oh=cc(),sy=dc(),oy=Rh.exports=function(e){Oh.call(this);let t=[],n=this;this._filter=new sy(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};iy.inherits(oy,Oh)});var ci=Te((xO,Hh)=>{Hh.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 mc=Te((AO,Th)=>{var hc=[];(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;hc[e]=t}})();var gc=Th.exports=function(){this._crc=-1};gc.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=hc[(this._crc^e[t])&255]^this._crc>>>8;return!0};gc.prototype.crc32=function(){return this._crc^-1};gc.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=hc[(t^e[n])&255]^t>>>8;return t^-1}});var pc=Te((LO,xh)=>{var Ze=ci(),ay=mc(),et=xh.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 ay,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 bc=Te((hy)=>{var Ah=lc(),uy=[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]}],cy=[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 ly(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 fy(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);uy[r](t,i,f,s),s+=r}return s}function dy(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);cy[r](t,f,d,s)}i.resetAfterLine()}}hy.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=ly(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=Ah.getImagePasses(n,r),d=Ah.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=fy(f[h],u,d,s,e,l);else dy(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 wc=Te((_O,Lh)=>{function my(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 py(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 by(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}}Lh.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)my(e,c,i,s,u);else{if(a)py(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);by(e,c,i,s,r)}}return c}});var Gh=Te((GO,_h)=>{var wy=st("util"),$c=st("zlib"),Ch=cc(),$y=Fh(),ky=pc(),yy=bc(),Ey=wc(),tn=_h.exports=function(e){Ch.call(this),this._parser=new ky(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()};wy.inherits(tn,Ch);tn.prototype._handleError=function(e){if(this.emit("error",e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};tn.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=$c.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,$c.Z_MIN_CHUNK);this._inflate=$c.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};tn.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new $y(this._bitmapInfo)};tn.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};tn.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};tn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};tn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};tn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};tn.prototype._complete=function(e){if(this.errord)return;let t;try{let n=yy.dataToBitMap(e,this._bitmapInfo);t=Ey(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Uh=Te((WO,Wh)=>{var Tt=ci();Wh.exports=function(e,t,n,r){let i=[Tt.COLORTYPE_COLOR_ALPHA,Tt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=Tt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=Tt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,f=0,d=r.bgColor||{};if(d.red===void 0)d.red=o;if(d.green===void 0)d.green=o;if(d.blue===void 0)d.blue=o;function h(){let g,b,p,m=o;switch(r.inputColorType){case Tt.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],b=s[l+1],p=s[l+2];break;case Tt.COLORTYPE_COLOR:g=s[l],b=s[l+1],p=s[l+2];break;case Tt.COLORTYPE_ALPHA:m=s[l+1],g=s[l],b=g,p=g;break;case Tt.COLORTYPE_GRAYSCALE:g=s[l],b=g,p=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)m/=o,g=Math.min(Math.max(Math.round((1-m)*d.red+m*g),0),o),b=Math.min(Math.max(Math.round((1-m)*d.green+m*b),0),o),p=Math.min(Math.max(Math.round((1-m)*d.blue+m*p),0),o)}return{red:g,green:b,blue:p,alpha:m}}for(let g=0;g<n;g++)for(let b=0;b<t;b++){let p=h(s,l);switch(r.colorType){case Tt.COLORTYPE_COLOR_ALPHA:case Tt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[f]=p.red,c[f+1]=p.green,c[f+2]=p.blue,i)c[f+3]=p.alpha}else if(c.writeUInt16BE(p.red,f),c.writeUInt16BE(p.green,f+2),c.writeUInt16BE(p.blue,f+4),i)c.writeUInt16BE(p.alpha,f+6);break;case Tt.COLORTYPE_ALPHA:case Tt.COLORTYPE_GRAYSCALE:{let m=(p.red+p.green+p.blue)/3;if(r.bitDepth===8){if(c[f]=m,i)c[f+1]=p.alpha}else if(c.writeUInt16BE(m,f),i)c.writeUInt16BE(p.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=u}return c}});var Bh=Te((UO,Kh)=>{var jh=fc();function vy(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function My(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Sy(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 Iy(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 Ny(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 Py(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 Oy(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 Ry(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 Fy(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]-jh(a,u,c);r[i+o]=l}}function Hy(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]-jh(o,a,u);i+=Math.abs(c)}return i}var Ty={0:vy,1:Sy,2:Ny,3:Oy,4:Fy},xy={0:My,1:Iy,2:Py,3:Ry,4:Hy};Kh.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=xy[s[h]](e,u,o,i);if(g<d)l=s[h],d=g}}c[a]=l,a++,Ty[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var kc=Te((jO,Jh)=>{var ut=ci(),Ay=mc(),Ly=Uh(),Cy=Bh(),_y=st("zlib"),Un=Jh.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||_y.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:ut.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:ut.COLORTYPE_COLOR_ALPHA,[ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw Error("option bit depth:"+e.bitDepth+" is not supported at present")};Un.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Un.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Un.prototype.filterData=function(e,t,n){let r=Ly(e,t,n,this._options),i=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Cy(r,t,n,this._options,i)};Un.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(Ay.crc32(r.slice(4,r.length-4)),r.length-4),r};Un.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*ut.GAMMA_DIVISION),0),this._packChunk(ut.TYPE_gAMA,t)};Un.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(ut.TYPE_IHDR,n)};Un.prototype.packIDAT=function(e){return this._packChunk(ut.TYPE_IDAT,e)};Un.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var Qh=Te((KO,Yh)=>{var Gy=st("util"),qh=st("stream"),Wy=ci(),Uy=kc(),zh=Yh.exports=function(e){qh.call(this);let t=e||{};this._packer=new Uy(t),this._deflate=this._packer.createDeflate(),this.readable=!0};Gy.inherits(zh,qh);zh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(Wy.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 tg=Te((us,eg)=>{var Vh=st("assert").ok,li=st("zlib"),jy=st("util"),Zh=st("buffer").kMaxLength;function Nr(e){if(!(this instanceof Nr))return new Nr(e);if(e&&e.chunkSize<li.Z_MIN_CHUNK)e.chunkSize=li.Z_MIN_CHUNK;if(li.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 Ky(e){return new Nr(e)}function Xh(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Nr.prototype._processChunk=function(e,t,n){if(typeof n==="function")return li.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function f(g,b){if(r._hadError)return;let p=s-b;if(Vh(p>=0,"have should not go down"),p>0){let m=r._buffer.slice(r._offset,r._offset+p);if(r._offset+=p,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(b===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(b===0)return a+=i-g,i=g,!0;return!1}Vh(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>=Zh)throw Xh(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+Zh.toString(16)+" bytes");let h=Buffer.concat(u,c);return Xh(this),h};jy.inherits(Nr,li.Inflate);function By(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=li.Z_FINISH;return e._processChunk(t,n)}function Dh(e,t){return By(new Nr(t),e)}eg.exports=us=Dh;us.Inflate=Nr;us.createInflate=Ky;us.inflateSync=Dh});var yc=Te((BO,rg)=>{var ng=rg.exports=function(e){this._buffer=e,this._reads=[]};ng.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};ng.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 ig=Te((zy)=>{var Jy=yc(),qy=dc();zy.process=function(e,t){let n=[],r=new Jy(e);return new qy(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var ug=Te((qO,ag)=>{var sg=!0,og=st("zlib"),Qy=tg();if(!og.deflateSync)sg=!1;var Vy=yc(),Zy=ig(),Xy=pc(),Dy=bc(),e1=wc();ag.exports=function(e,t){if(!sg)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 Vy(e);if(new Xy(t,{read:h.read.bind(h),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:d,simpleTransparency:u}).start(),h.process(),n)throw n;let b=Buffer.concat(f);f.length=0;let p;if(i.interlace)p=og.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;p=Qy(b,{chunkSize:w,maxLength:w})}if(b=null,!p||!p.length)throw Error("bad png - invalid inflate data response");let m=Zy.process(p,i);b=null;let $=Dy.dataToBitMap(m,i);m=null;let E=e1($,i,t.skipRescale);return i.data=E,i.gamma=c||0,i}});var dg=Te((zO,fg)=>{var cg=!0,lg=st("zlib");if(!lg.deflateSync)cg=!1;var t1=ci(),n1=kc();fg.exports=function(e,t){if(!cg)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new n1(t||{}),i=[];if(i.push(Buffer.from(t1.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=lg.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 hg=Te((s1)=>{var r1=ug(),i1=dg();s1.read=function(e,t){return r1(e,t||{})};s1.write=function(e,t){return i1(e,t)}});var mg=Te((d1)=>{var u1=st("util"),gg=st("stream"),c1=Gh(),l1=Qh(),f1=hg(),lt=d1.PNG=function(e){if(gg.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 c1(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 l1(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"))};u1.inherits(lt,gg);lt.sync=f1;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 xP}from"node:child_process";import{isMainThread as AP}from"node:worker_threads";import{parseArgs as PP}from"node:util";var ot={name:"@kecan0406/ttheme",version:"1.2.3",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal, Warp and Konsole",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2","konsole"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","@xterm/headless":"6.0.0","fast-string-width":"^3.0.2","jpeg-js":"^0.4.4",pngjs:"7.0.0","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{existsSync as zN,readFileSync as i$}from"node:fs";import{styleText as Lo}from"node:util";import{stdout as Kd,stdin as nk}from"node:process";import rk from"node:readline";var Id=(()=>{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}})(),Nd=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Pd=(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 U$=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,j$=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Od=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,K$=/\t{1,1000}/y,Rd=/[\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,B$=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,J$=/\p{M}+/gu,q$={limit:1/0,ellipsis:""},Fd=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Fd(i,q$,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,f=n.regularWidth??1,d=n.wideWidth??2,h=[[B$,f],[U$,0],[j$,a],[K$,u],[Rd,c],[Od,d]],g=0,b=0,p=e.length,m=0,$=!1,E=p,M=Math.max(0,r-s),w=0,S=0,k=0,N=0;e:while(!0){if(S>w||b>=p&&b>g){let O=e.slice(w,S)||e.slice(g,b);m=0;for(let T of O.replaceAll(J$,"")){let x=T.codePointAt(0)||0;if(Nd(x))N=2;else if(Pd(x))N=d;else N=f;if(k+N>M)E=Math.min(E,Math.max(w,g)+m);if(k+N>r){$=!0;break e}m+=T.length,k+=N}w=S=0}if(b>=p)break e;for(let O=0,T=h.length;O<T;O++){let[x,C]=h[O];if(x.lastIndex=b,x.test(e)){if(m=x===Od?Id(e.slice(b,x.lastIndex)):x===Rd?1:x.lastIndex-b,N=m*C,k+N>M)E=Math.min(E,b+Math.floor((M-k)/C));if(k+N>r){$=!0;break e}k+=N,w=g,S=b,b=g=x.lastIndex;continue e}}b+=1}return{width:$?M:k,index:$?E:p,truncated:$,ellipsed:$&&r>=s}},Hd=Fd;var z$={limit:1/0,ellipsis:"",ellipsisWidth:0},Y$=(e,t={})=>{return Hd(e,z$,t).width},$e=Y$;var Ho="\x1B",Cd="›",Q$=39,Gu="\x07",_d="[",V$="]",Gd="m",Wu=`${V$}8;;`,Td=new RegExp(`(?:\\${_d}(?<code>\\d+)m|\\${Wu}(?<uri>.*)${Gu})`,"y"),xd=(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},Ad=(e)=>`${Ho}${_d}${e}${Gd}`,Ld=(e)=>`${Ho}${Wu}${e}${Gu}`,_u=(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===Ho||f===Cd)i=!0,s=t.startsWith(Wu,l+1);if(i){if(s){if(f===Gu)i=!1,s=!1}else if(f===Gd)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()},Z$=(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("")},X$=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let f=0;f<o.length;f++){let d=o[f];if(n.trim!==!1){let g=a.at(-1)??"",b=g.trimStart();if(g.length!==b.length)a[a.length-1]=b,u=$e(b)}if(f!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let h=$e(d);if(n.hard&&h>t){let g=t-u,b=1+Math.floor((h-g-1)/t);if(Math.floor((h-1)/t)<b)a.push("");_u(a,d,t),u=$e(a.at(-1)??"");continue}if(u+h>t&&u&&h){if(n.wordWrap===!1&&u<t){_u(a,d,t),u=$e(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>t&&n.wordWrap===!1){_u(a,d,t),u=$e(a.at(-1)??"");continue}a[a.length-1]+=d,u+=h}if(n.trim!==!1)a=a.map((f)=>Z$(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===Ho||d===Cd){Td.lastIndex=f+1;let g=Td.exec(c)?.groups;if(g?.code!==void 0){let b=Number.parseFloat(g.code);i=b===Q$?void 0:b}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[f+1]===`
4
- `){if(s)r+=Ld("");let h=i?xd(i):void 0;if(i&&h)r+=Ad(h)}else if(d===`
5
- `){if(i&&xd(i))r+=Ad(i);if(s)r+=Ld(s)}}return r},D$=/\r?\n/;function Hn(e,t,n){return String(e).normalize().split(D$).map((r)=>X$(r,t,n)).join(`
6
- `)}var pt=Fo(ju(),1);function ti(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?ti(s,t<0?-1:1,n):s}function To(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 ik=["up","down","left","right","space","enter","cancel"],sk=["January","February","March","April","May","June","July","August","September","October","November","December"],at={actions:new Set(ik),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:[...sk],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 Bd(e,t){if(typeof e=="string")return at.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Bd(n,t))return!0;return!1}function ok(e,t){if(e===t)return;let n=e.split(`
2
+ import{createRequire as K$}from"node:module";var L$=Object.create;var{getPrototypeOf:C$,defineProperty:Pd,getOwnPropertyNames:_$}=Object;var G$=Object.prototype.hasOwnProperty;function W$(e){return this[e]}var U$,j$,To=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?U$??=new WeakMap:j$??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?L$(C$(e)):{};let o=t||!e||!e.__esModule?Pd(n,"default",{value:e,enumerable:!0}):n;for(let a of _$(e))if(!G$.call(o,a))Pd(o,a,{get:W$.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var He=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ot=K$(import.meta.url);var Ju=He((uR,Kd)=>{var Bu={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ik={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},sk={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Bu.up():"");if(e)t+=Bu.left;return t}};Kd.exports={cursor:Bu,scroll:ik,erase:sk,beep:"\x07"}});var Eh=He((jR,Bo)=>{var yh=yh||function(e){return Buffer.from(e).toString("base64")};function Dk(e){var t=this,n=Math.round,r=Math.floor,i=Array(64),s=Array(64),o=Array(64),a=Array(64),u,c,l,f,d=Array(65535),h=Array(65535),g=Array(64),b=Array(64),p=[],m=0,$=7,E=Array(64),M=Array(64),w=Array(64),S=Array(256),k=Array(2048),N,R=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],H=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],x=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],W=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],A=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],F=[0,1,2,3,4,5,6,7,8,9,10,11],q=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Ee=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function be(y){var G=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var z=0;z<64;z++){var j=r((G[z]*y+50)/100);if(j<1)j=1;else if(j>255)j=255;i[R[z]]=j}var te=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var re=0;re<64;re++){var me=r((te[re]*y+50)/100);if(me<1)me=1;else if(me>255)me=255;s[R[re]]=me}var pe=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],Ue=0;for(var Te=0;Te<8;Te++)for(var P=0;P<8;P++)o[Ue]=1/(i[R[Ue]]*pe[Te]*pe[P]*8),a[Ue]=1/(s[R[Ue]]*pe[Te]*pe[P]*8),Ue++}function Y(y,G){var z=0,j=0,te=[];for(var re=1;re<=16;re++){for(var me=1;me<=y[re];me++)te[G[j]]=[],te[G[j]][0]=z,te[G[j]][1]=re,j++,z++;z*=2}return te}function Ae(){u=Y(H,x),c=Y(A,F),l=Y(C,W),f=Y(q,Ee)}function he(){var y=1,G=2;for(var z=1;z<=15;z++){for(var j=y;j<G;j++)h[32767+j]=z,d[32767+j]=[],d[32767+j][1]=z,d[32767+j][0]=j;for(var te=-(G-1);te<=-y;te++)h[32767+te]=z,d[32767+te]=[],d[32767+te][1]=z,d[32767+te][0]=G-1+te;y<<=1,G<<=1}}function ce(){for(var y=0;y<256;y++)k[y]=19595*y,k[y+256>>0]=38470*y,k[y+512>>0]=7471*y+32768,k[y+768>>0]=-11059*y,k[y+1024>>0]=-21709*y,k[y+1280>>0]=32768*y+8421375,k[y+1536>>0]=-27439*y,k[y+1792>>0]=-5329*y}function se(y){var G=y[0],z=y[1]-1;while(z>=0){if(G&1<<z)m|=1<<$;if(z--,$--,$<0){if(m==255)v(255),v(0);else v(m);$=7,m=0}}}function v(y){p.push(y)}function U(y){v(y>>8&255),v(y&255)}function Ne(y,G){var z,j,te,re,me,pe,Ue,Te,P=0,L,Z=8,Ge=64;for(L=0;L<Z;++L){z=y[P],j=y[P+1],te=y[P+2],re=y[P+3],me=y[P+4],pe=y[P+5],Ue=y[P+6],Te=y[P+7];var ie=z+Te,le=z-Te,Re=j+Ue,V=j-Ue,we=te+pe,nt=te-pe,Le=re+me,Ot=re-me,Zt=ie+Le,Er=ie-Le,Dr=Re+we,ei=Re-we;y[P]=Zt+Dr,y[P+4]=Zt-Dr;var Yi=(ei+Er)*0.707106781;y[P+2]=Er+Yi,y[P+6]=Er-Yi,Zt=Ot+nt,Dr=nt+V,ei=V+le;var Qi=(Zt-ei)*0.382683433,Po=0.5411961*Zt+Qi,Zi=1.306562965*ei+Qi,Xi=Dr*0.707106781,Di=le+Xi,es=le-Xi;y[P+5]=es+Po,y[P+3]=es-Po,y[P+1]=Di+Zi,y[P+7]=Di-Zi,P+=8}P=0;for(L=0;L<Z;++L){z=y[P],j=y[P+8],te=y[P+16],re=y[P+24],me=y[P+32],pe=y[P+40],Ue=y[P+48],Te=y[P+56];var md=z+Te,Gu=z-Te,pd=j+Ue,bd=j-Ue,wd=te+pe,$d=te-pe,kd=re+me,A$=re-me,ts=md+kd,Wu=md-kd,Ro=pd+wd,Oo=pd-wd;y[P]=ts+Ro,y[P+32]=ts-Ro;var yd=(Oo+Wu)*0.707106781;y[P+16]=Wu+yd,y[P+48]=Wu-yd,ts=A$+$d,Ro=$d+bd,Oo=bd+Gu;var Ed=(ts-Oo)*0.382683433,vd=0.5411961*ts+Ed,Md=1.306562965*Oo+Ed,Sd=Ro*0.707106781,Id=Gu+Sd,Nd=Gu-Sd;y[P+40]=Nd+vd,y[P+24]=Nd-vd,y[P+8]=Id+Md,y[P+56]=Id-Md,P++}var Fo;for(L=0;L<Ge;++L)Fo=y[L]*G[L],g[L]=Fo>0?Fo+0.5|0:Fo-0.5|0;return g}function Pe(){U(65504),U(16),v(74),v(70),v(73),v(70),v(0),v(1),v(1),v(0),U(1),U(1),v(0),v(0)}function fe(y){if(!y)return;if(U(65505),y[0]===69&&y[1]===120&&y[2]===105&&y[3]===102)U(y.length+2);else U(y.length+5+2),v(69),v(120),v(105),v(102),v(0);for(var G=0;G<y.length;G++)v(y[G])}function de(y,G){U(65472),U(17),v(8),U(G),U(y),v(3),v(1),v(17),v(0),v(2),v(17),v(1),v(3),v(17),v(1)}function oe(){U(65499),U(132),v(0);for(var y=0;y<64;y++)v(i[y]);v(1);for(var G=0;G<64;G++)v(s[G])}function T(){U(65476),U(418),v(0);for(var y=0;y<16;y++)v(H[y+1]);for(var G=0;G<=11;G++)v(x[G]);v(16);for(var z=0;z<16;z++)v(C[z+1]);for(var j=0;j<=161;j++)v(W[j]);v(1);for(var te=0;te<16;te++)v(A[te+1]);for(var re=0;re<=11;re++)v(F[re]);v(17);for(var me=0;me<16;me++)v(q[me+1]);for(var pe=0;pe<=161;pe++)v(Ee[pe])}function O(y){if(typeof y>"u"||y.constructor!==Array)return;y.forEach((G)=>{if(typeof G!=="string")return;U(65534);var z=G.length;U(z+2);var j;for(j=0;j<z;j++)v(G.charCodeAt(j))})}function Fe(){U(65498),U(12),v(3),v(1),v(0),v(2),v(17),v(3),v(17),v(0),v(63),v(0)}function Q(y,G,z,j,te){var re=te[0],me=te[240],pe,Ue=16,Te=63,P=64,L=Ne(y,G);for(var Z=0;Z<P;++Z)b[R[Z]]=L[Z];var Ge=b[0]-z;if(z=b[0],Ge==0)se(j[0]);else pe=32767+Ge,se(j[h[pe]]),se(d[pe]);var ie=63;for(;ie>0&&b[ie]==0;ie--);if(ie==0)return se(re),z;var le=1,Re;while(le<=ie){var V=le;for(;b[le]==0&&le<=ie;++le);var we=le-V;if(we>=Ue){Re=we>>4;for(var nt=1;nt<=Re;++nt)se(me);we=we&15}pe=32767+b[le],se(te[(we<<4)+h[pe]]),se(d[pe]),le++}if(ie!=Te)se(re);return z}function ae(){var y=String.fromCharCode;for(var G=0;G<256;G++)S[G]=y(G)}this.encode=function(y,G){var z=new Date().getTime();if(G)Rt(G);p=[],m=0,$=7,U(65496),Pe(),O(y.comments),fe(y.exifBuffer),oe(),de(y.width,y.height),T(),Fe();var j=0,te=0,re=0;m=0,$=7,this.encode.displayName="_encode_";var{data:me,width:pe,height:Ue}=y,Te=pe*4,P=pe*3,L,Z=0,Ge,ie,le,Re,V,we,nt,Le;while(Z<Ue){L=0;while(L<Te){Re=Te*Z+L,V=Re,we=-1,nt=0;for(Le=0;Le<64;Le++){if(nt=Le>>3,we=(Le&7)*4,V=Re+nt*Te+we,Z+nt>=Ue)V-=Te*(Z+1+nt-Ue);if(L+we>=Te)V-=L+we-Te+4;Ge=me[V++],ie=me[V++],le=me[V++],E[Le]=(k[Ge]+k[ie+256>>0]+k[le+512>>0]>>16)-128,M[Le]=(k[Ge+768>>0]+k[ie+1024>>0]+k[le+1280>>0]>>16)-128,w[Le]=(k[Ge+1280>>0]+k[ie+1536>>0]+k[le+1792>>0]>>16)-128}j=Q(E,o,j,u,l),te=Q(M,a,te,c,f),re=Q(w,a,re,c,f),L+=32}Z+=8}if($>=0){var Ot=[];Ot[1]=$+1,Ot[0]=(1<<$+1)-1,se(Ot)}if(U(65497),typeof Bo>"u")return new Uint8Array(p);return Buffer.from(p);var Zt,Er};function Rt(y){if(y<=0)y=1;if(y>100)y=100;if(N==y)return;var G=0;if(y<50)G=Math.floor(5000/y);else G=Math.floor(200-y*2);be(G),N=y}function Ut(){var y=new Date().getTime();if(!e)e=50;ae(),Ae(),he(),ce(),Rt(e);var G=new Date().getTime()-y}Ut()}if(typeof Bo<"u")Bo.exports=kh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=kh;function kh(e,t){if(typeof t>"u")t=50;var n=new Dk(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}});var Mh=He((KR,fc)=>{var lc=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($,E){var M=0,w=[],S,k,N=16;while(N>0&&!$[N-1])N--;w.push({children:[],index:0});var R=w[0],H;for(S=0;S<N;S++){for(k=0;k<$[S];k++){R=w.pop(),R.children[R.index]=E[M];while(R.index>0){if(w.length===0)throw Error("Could not recreate Huffman Table");R=w.pop()}R.index++,w.push(R);while(w.length<=S)w.push(H={children:[],index:0}),R.children[R.index]=H.children,R=H;M++}if(S+1<N)w.push(H={children:[],index:0}),R.children[R.index]=H.children,R=H}return w[0].children}function d($,E,M,w,S,k,N,R,H,x){var{precision:C,samplesPerLine:W,scanLines:A,mcusPerLine:F,progressive:q,maxH:Ee,maxV:be}=M,Y=E,Ae=0,he=0;function ce(){if(he>0)return he--,Ae>>he&1;if(Ae=$[E++],Ae==255){var P=$[E++];if(P)throw Error("unexpected marker: "+(Ae<<8|P).toString(16))}return he=7,Ae>>>7}function se(P){var L=P,Z;while((Z=ce())!==null){if(L=L[Z],typeof L==="number")return L;if(typeof L!=="object")throw Error("invalid huffman sequence")}return null}function v(P){var L=0;while(P>0){var Z=ce();if(Z===null)return;L=L<<1|Z,P--}return L}function U(P){var L=v(P);if(L>=1<<P-1)return L;return L+(-1<<P)+1}function Ne(P,L){var Z=se(P.huffmanTableDC),Ge=Z===0?0:U(Z);L[0]=P.pred+=Ge;var ie=1;while(ie<64){var le=se(P.huffmanTableAC),Re=le&15,V=le>>4;if(Re===0){if(V<15)break;ie+=16;continue}ie+=V;var we=t[ie];L[we]=U(Re),ie++}}function Pe(P,L){var Z=se(P.huffmanTableDC),Ge=Z===0?0:U(Z)<<H;L[0]=P.pred+=Ge}function fe(P,L){L[0]|=ce()<<H}var de=0;function oe(P,L){if(de>0){de--;return}var Z=k,Ge=N;while(Z<=Ge){var ie=se(P.huffmanTableAC),le=ie&15,Re=ie>>4;if(le===0){if(Re<15){de=v(Re)+(1<<Re)-1;break}Z+=16;continue}Z+=Re;var V=t[Z];L[V]=U(le)*(1<<H),Z++}}var T=0,O;function Fe(P,L){var Z=k,Ge=N,ie=0;while(Z<=Ge){var le=t[Z],Re=L[le]<0?-1:1;switch(T){case 0:var V=se(P.huffmanTableAC),we=V&15,ie=V>>4;if(we===0)if(ie<15)de=v(ie)+(1<<ie),T=4;else ie=16,T=1;else{if(we!==1)throw Error("invalid ACn encoding");O=U(we),T=ie?2:3}continue;case 1:case 2:if(L[le])L[le]+=(ce()<<H)*Re;else if(ie--,ie===0)T=T==2?3:0;break;case 3:if(L[le])L[le]+=(ce()<<H)*Re;else L[le]=O<<H,T=0;break;case 4:if(L[le])L[le]+=(ce()<<H)*Re;break}Z++}if(T===4){if(de--,de===0)T=0}}function Q(P,L,Z,Ge,ie){var le=Z/F|0,Re=Z%F,V=le*P.v+Ge,we=Re*P.h+ie;if(P.blocks[V]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[V][we])}function ae(P,L,Z){var Ge=Z/P.blocksPerLine|0,ie=Z%P.blocksPerLine;if(P.blocks[Ge]===void 0&&x.tolerantDecoding)return;L(P,P.blocks[Ge][ie])}var Rt=w.length,Ut,y,G,z,j,te;if(q)if(k===0)te=R===0?Pe:fe;else te=R===0?oe:Fe;else te=Ne;var re=0,me,pe;if(Rt==1)pe=w[0].blocksPerLine*w[0].blocksPerColumn;else pe=F*M.mcusPerColumn;if(!S)S=pe;var Ue,Te;while(re<pe){for(y=0;y<Rt;y++)w[y].pred=0;if(de=0,Rt==1){Ut=w[0];for(j=0;j<S;j++)ae(Ut,te,re),re++}else for(j=0;j<S;j++){for(y=0;y<Rt;y++){Ut=w[y],Ue=Ut.h,Te=Ut.v;for(G=0;G<Te;G++)for(z=0;z<Ue;z++)Q(Ut,te,re,G,z)}if(re++,re===pe)break}if(re===pe)do{if($[E]===255){if($[E+1]!==0)break}E+=1}while(E<$.length-2);if(he=0,me=$[E]<<8|$[E+1],me<65280)throw Error("marker was not found");if(me>=65488&&me<=65495)E+=2;else break}return E-Y}function h($,E){var M=[],w=E.blocksPerLine,S=E.blocksPerColumn,k=w<<3,N=new Int32Array(64),R=new Uint8Array(64);function H(Y,Ae,he){var ce=E.quantizationTable,se,v,U,Ne,Pe,fe,de,oe,T,O=he,Fe;for(Fe=0;Fe<64;Fe++)O[Fe]=Y[Fe]*ce[Fe];for(Fe=0;Fe<8;++Fe){var Q=8*Fe;if(O[1+Q]==0&&O[2+Q]==0&&O[3+Q]==0&&O[4+Q]==0&&O[5+Q]==0&&O[6+Q]==0&&O[7+Q]==0){T=u*O[0+Q]+512>>10,O[0+Q]=T,O[1+Q]=T,O[2+Q]=T,O[3+Q]=T,O[4+Q]=T,O[5+Q]=T,O[6+Q]=T,O[7+Q]=T;continue}se=u*O[0+Q]+128>>8,v=u*O[4+Q]+128>>8,U=O[2+Q],Ne=O[6+Q],Pe=c*(O[1+Q]-O[7+Q])+128>>8,oe=c*(O[1+Q]+O[7+Q])+128>>8,fe=O[3+Q]<<4,de=O[5+Q]<<4,T=se-v+1>>1,se=se+v+1>>1,v=T,T=U*a+Ne*o+128>>8,U=U*o-Ne*a+128>>8,Ne=T,T=Pe-de+1>>1,Pe=Pe+de+1>>1,de=T,T=oe+fe+1>>1,fe=oe-fe+1>>1,oe=T,T=se-Ne+1>>1,se=se+Ne+1>>1,Ne=T,T=v-U+1>>1,v=v+U+1>>1,U=T,T=Pe*s+oe*i+2048>>12,Pe=Pe*i-oe*s+2048>>12,oe=T,T=fe*r+de*n+2048>>12,fe=fe*n-de*r+2048>>12,de=T,O[0+Q]=se+oe,O[7+Q]=se-oe,O[1+Q]=v+de,O[6+Q]=v-de,O[2+Q]=U+fe,O[5+Q]=U-fe,O[3+Q]=Ne+Pe,O[4+Q]=Ne-Pe}for(Fe=0;Fe<8;++Fe){var ae=Fe;if(O[8+ae]==0&&O[16+ae]==0&&O[24+ae]==0&&O[32+ae]==0&&O[40+ae]==0&&O[48+ae]==0&&O[56+ae]==0){T=u*he[Fe+0]+8192>>14,O[0+ae]=T,O[8+ae]=T,O[16+ae]=T,O[24+ae]=T,O[32+ae]=T,O[40+ae]=T,O[48+ae]=T,O[56+ae]=T;continue}se=u*O[0+ae]+2048>>12,v=u*O[32+ae]+2048>>12,U=O[16+ae],Ne=O[48+ae],Pe=c*(O[8+ae]-O[56+ae])+2048>>12,oe=c*(O[8+ae]+O[56+ae])+2048>>12,fe=O[24+ae],de=O[40+ae],T=se-v+1>>1,se=se+v+1>>1,v=T,T=U*a+Ne*o+2048>>12,U=U*o-Ne*a+2048>>12,Ne=T,T=Pe-de+1>>1,Pe=Pe+de+1>>1,de=T,T=oe+fe+1>>1,fe=oe-fe+1>>1,oe=T,T=se-Ne+1>>1,se=se+Ne+1>>1,Ne=T,T=v-U+1>>1,v=v+U+1>>1,U=T,T=Pe*s+oe*i+2048>>12,Pe=Pe*i-oe*s+2048>>12,oe=T,T=fe*r+de*n+2048>>12,fe=fe*n-de*r+2048>>12,de=T,O[0+ae]=se+oe,O[56+ae]=se-oe,O[8+ae]=v+de,O[48+ae]=v-de,O[16+ae]=U+fe,O[40+ae]=U-fe,O[24+ae]=Ne+Pe,O[32+ae]=Ne-Pe}for(Fe=0;Fe<64;++Fe){var Rt=128+(O[Fe]+8>>4);Ae[Fe]=Rt<0?0:Rt>255?255:Rt}}m(k*S*8);var x,C;for(var W=0;W<S;W++){var A=W<<3;for(x=0;x<8;x++)M.push(new Uint8Array(k));for(var F=0;F<w;F++){H(E.blocks[W][F],R,N);var q=0,Ee=F<<3;for(C=0;C<8;C++){var be=M[A+C];for(x=0;x<8;x++)be[Ee+x]=R[q++]}}}return M}function g($){return $<0?0:$>255?255:$}l.prototype={load:function(E){var M=new XMLHttpRequest;M.open("GET",E,!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(E){var M=this.opts.maxResolutionInMP*1000*1000,w=0,S=E.length;function k(){var V=E[w]<<8|E[w+1];return w+=2,V}function N(){var V=k(),we=E.subarray(w,w+V-2);return w+=we.length,we}function R(V){var we=1,nt=1,Le,Ot;for(Ot in V.components)if(V.components.hasOwnProperty(Ot)){if(Le=V.components[Ot],we<Le.h)we=Le.h;if(nt<Le.v)nt=Le.v}var Zt=Math.ceil(V.samplesPerLine/8/we),Er=Math.ceil(V.scanLines/8/nt);for(Ot in V.components)if(V.components.hasOwnProperty(Ot)){Le=V.components[Ot];var Dr=Math.ceil(Math.ceil(V.samplesPerLine/8)*Le.h/we),ei=Math.ceil(Math.ceil(V.scanLines/8)*Le.v/nt),Yi=Zt*Le.h,Qi=Er*Le.v,Po=Qi*Yi,Zi=[];m(Po*256);for(var Xi=0;Xi<Qi;Xi++){var Di=[];for(var es=0;es<Yi;es++)Di.push(new Int32Array(64));Zi.push(Di)}Le.blocksPerLine=Dr,Le.blocksPerColumn=ei,Le.blocks=Zi}V.maxH=we,V.maxV=nt,V.mcusPerLine=Zt,V.mcusPerColumn=Er}var H=null,x=null,C=null,W,A,F=[],q=[],Ee=[],be=[],Y=k(),Ae=-1;if(this.comments=[],Y!=65496)throw Error("SOI not found");Y=k();while(Y!=65497){var he,ce,se;switch(Y){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var v=N();if(Y===65534){var U=String.fromCharCode.apply(null,v);this.comments.push(U)}if(Y===65504){if(v[0]===74&&v[1]===70&&v[2]===73&&v[3]===70&&v[4]===0)H={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)x={version:v[6],flags0:v[7]<<8|v[8],flags1:v[9]<<8|v[10],transformCode:v[11]}}break;case 65499:var Ne=k(),Pe=Ne+w-2;while(w<Pe){var fe=E[w++];m(256);var de=new Int32Array(64);if(fe>>4===0)for(ce=0;ce<64;ce++){var oe=t[ce];de[oe]=E[w++]}else if(fe>>4===1)for(ce=0;ce<64;ce++){var oe=t[ce];de[oe]=k()}else throw Error("DQT: invalid table spec");F[fe&15]=de}break;case 65472:case 65473:case 65474:k(),W={},W.extended=Y===65473,W.progressive=Y===65474,W.precision=E[w++],W.scanLines=k(),W.samplesPerLine=k(),W.components={},W.componentsOrder=[];var T=W.scanLines*W.samplesPerLine;if(T>M){var O=Math.ceil((T-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${O}MP`)}var Fe=E[w++],Q,ae=0,Rt=0;for(he=0;he<Fe;he++){Q=E[w];var Ut=E[w+1]>>4,y=E[w+1]&15,G=E[w+2];if(Ut<=0||y<=0)throw Error("Invalid sampling factor, expected values above 0");W.componentsOrder.push(Q),W.components[Q]={h:Ut,v:y,quantizationIdx:G},w+=3}R(W),q.push(W);break;case 65476:var z=k();for(he=2;he<z;){var j=E[w++],te=new Uint8Array(16),re=0;for(ce=0;ce<16;ce++,w++)re+=te[ce]=E[w];m(16+re);var me=new Uint8Array(re);for(ce=0;ce<re;ce++,w++)me[ce]=E[w];he+=17+re,(j>>4===0?be:Ee)[j&15]=f(te,me)}break;case 65501:k(),A=k();break;case 65500:k(),k();break;case 65498:var pe=k(),Ue=E[w++],Te=[],P;for(he=0;he<Ue;he++){P=W.components[E[w++]];var L=E[w++];P.huffmanTableDC=be[L>>4],P.huffmanTableAC=Ee[L&15],Te.push(P)}var Z=E[w++],Ge=E[w++],ie=E[w++],le=d(E,w,W,Te,A,Z,Ge,ie>>4,ie&15,this.opts);w+=le;break;case 65535:if(E[w]!==255)w--;break;default:if(E[w-3]==255&&E[w-2]>=192&&E[w-2]<=254){w-=3;break}else if(Y===224||Y==225){if(Ae!==-1)throw Error(`first unknown JPEG marker at offset ${Ae.toString(16)}, second unknown JPEG marker ${Y.toString(16)} at offset ${(w-1).toString(16)}`);Ae=w-1;let V=k();if(E[w+V-2]===255){w+=V-2;break}}throw Error("unknown JPEG marker "+Y.toString(16))}Y=k()}if(q.length!=1)throw Error("only single frame JPEGs supported");for(var he=0;he<q.length;he++){var Re=q[he].components;for(var ce in Re)Re[ce].quantizationTable=F[Re[ce].quantizationIdx],delete Re[ce].quantizationIdx}this.width=W.samplesPerLine,this.height=W.scanLines,this.jfif=H,this.adobe=x,this.components=[];for(var he=0;he<W.componentsOrder.length;he++){var P=W.components[W.componentsOrder[he]];this.components.push({lines:h(W,P),scaleX:P.h/W.maxH,scaleY:P.v/W.maxV})}},getData:function(E,M){var w=this.width/E,S=this.height/M,k,N,R,H,x,C,W,A,F,q,Ee=0,be,Y,Ae,he,ce,se,v,U,Ne,Pe,fe,de=E*M*this.components.length;m(de);var oe=new Uint8Array(de);switch(this.components.length){case 1:k=this.components[0];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S];for(F=0;F<E;F++)be=x[0|F*k.scaleX*w],oe[Ee++]=be}break;case 2:k=this.components[0],N=this.components[1];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S];for(F=0;F<E;F++)be=x[0|F*k.scaleX*w],oe[Ee++]=be,be=C[0|F*N.scaleX*w],oe[Ee++]=be}break;case 3:if(fe=!0,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;k=this.components[0],N=this.components[1],R=this.components[2];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S],W=R.lines[0|q*R.scaleY*S];for(F=0;F<E;F++){if(!fe)U=x[0|F*k.scaleX*w],Ne=C[0|F*N.scaleX*w],Pe=W[0|F*R.scaleX*w];else be=x[0|F*k.scaleX*w],Y=C[0|F*N.scaleX*w],Ae=W[0|F*R.scaleX*w],U=g(be+1.402*(Ae-128)),Ne=g(be-0.3441363*(Y-128)-0.71413636*(Ae-128)),Pe=g(be+1.772*(Y-128));oe[Ee++]=U,oe[Ee++]=Ne,oe[Ee++]=Pe}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(fe=!1,this.adobe&&this.adobe.transformCode)fe=!0;else if(typeof this.opts.colorTransform<"u")fe=!!this.opts.colorTransform;k=this.components[0],N=this.components[1],R=this.components[2],H=this.components[3];for(q=0;q<M;q++){x=k.lines[0|q*k.scaleY*S],C=N.lines[0|q*N.scaleY*S],W=R.lines[0|q*R.scaleY*S],A=H.lines[0|q*H.scaleY*S];for(F=0;F<E;F++){if(!fe)ce=x[0|F*k.scaleX*w],se=C[0|F*N.scaleX*w],v=W[0|F*R.scaleX*w],he=A[0|F*H.scaleX*w];else be=x[0|F*k.scaleX*w],Y=C[0|F*N.scaleX*w],Ae=W[0|F*R.scaleX*w],he=A[0|F*H.scaleX*w],ce=255-g(be+1.402*(Ae-128)),se=255-g(be-0.3441363*(Y-128)-0.71413636*(Ae-128)),v=255-g(be+1.772*(Y-128));oe[Ee++]=255-ce,oe[Ee++]=255-se,oe[Ee++]=255-v,oe[Ee++]=255-he}}break;default:throw Error("Unsupported color mode")}return oe},copyToImageData:function(E,M){var{width:w,height:S,data:k}=E,N=this.getData(w,S),R=0,H=0,x,C,W,A,F,q,Ee,be,Y;switch(this.components.length){case 1:for(C=0;C<S;C++)for(x=0;x<w;x++)if(W=N[R++],k[H++]=W,k[H++]=W,k[H++]=W,M)k[H++]=255;break;case 3:for(C=0;C<S;C++)for(x=0;x<w;x++)if(Ee=N[R++],be=N[R++],Y=N[R++],k[H++]=Ee,k[H++]=be,k[H++]=Y,M)k[H++]=255;break;case 4:for(C=0;C<S;C++)for(x=0;x<w;x++)if(F=N[R++],q=N[R++],W=N[R++],A=N[R++],Ee=255-g(F*(1-A/255)+A),be=255-g(q*(1-A/255)+A),Y=255-g(W*(1-A/255)+A),k[H++]=Ee,k[H++]=be,k[H++]=Y,M)k[H++]=255;break;default:throw Error("Unsupported color mode")}}};var b=0,p=0;function m($=0){var E=b+$;if(E>p){var M=Math.ceil((E-p)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}b=E}return l.resetMaxMemoryUsage=function($){b=0,p=$},l.getBytesAllocated=function(){return b},l.requestMemoryAllocation=m,l}();if(typeof fc<"u")fc.exports=vh;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=vh;function vh(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 lc;s.opts=r,lc.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,a=s.width*s.height*o;try{lc.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 Ih=He((BR,Sh)=>{var ey=Eh(),ty=Mh();Sh.exports={encode:ey,decode:ty}});var dc=He((JR,Ph)=>{var ny=ot("util"),Nh=ot("stream"),Kt=Ph.exports=function(){Nh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};ny.inherits(Kt,Nh);Kt.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Kt.prototype.write=function(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(e))n=e;else n=Buffer.from(e,t||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Kt.prototype.end=function(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Kt.prototype.destroySoon=Kt.prototype.end;Kt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Kt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Kt.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)};Kt.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);while(t<e.length){let i=this._buffers[n++],s=Math.min(i.length,e.length-t);if(i.copy(r,t,0,s),t+=s,s!==i.length)this._buffers[--n]=i.slice(s)}if(n>0)this._buffers.splice(0,n);this._buffered-=e.length,e.func.call(this,r)};Kt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}if(this._buffers&&!this.writable)this._end()}catch(e){this.emit("error",e)}}});var hc=He((ry)=>{var Wn=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];ry.getImagePasses=function(e,t){let n=[],r=e%8,i=t%8,s=(e-r)/8,o=(t-i)/8;for(let a=0;a<Wn.length;a++){let u=Wn[a],c=s*u.x.length,l=o*u.y.length;for(let f=0;f<u.x.length;f++)if(u.x[f]<r)c++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)l++;else break;if(c>0&&l>0)n.push({width:c,height:l,index:a})}return n};ry.getInterlaceIterator=function(e){return function(t,n,r){let i=t%Wn[r].x.length,s=(t-i)/Wn[r].x.length*8+Wn[r].x[i],o=n%Wn[r].y.length,a=(n-o)/Wn[r].y.length*8+Wn[r].y[o];return s*4+a*e*4}}});var gc=He((zR,Rh)=>{Rh.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 mc=He((VR,Fh)=>{var oy=hc(),ay=gc();function Oh(e,t,n){let r=e*t;if(n!==8)r=Math.ceil(r/(8/n));return r}var ui=Fh.exports=function(e,t){let{width:n,height:r,interlace:i,bpp:s,depth:o}=e;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],i){let a=oy.getImagePasses(n,r);for(let u=0;u<a.length;u++)this._images.push({byteWidth:Oh(a[u].width,s,o),height:a[u].height,lineIndex:0})}else this._images.push({byteWidth:Oh(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};ui.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ui.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}};ui.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}};ui.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}};ui.prototype._unFilterType4=function(e,t,n){let r=this._xComparison,i=r-1,s=this._lastLine;for(let o=0;o<n;o++){let a=e[1+o],u=s?s[o]:0,c=o>i?t[o-r]:0,l=o>i&&s?s[o-r]:0,f=ay(c,u,l);t[o]=a+f}};ui.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 xh=He((YR,Hh)=>{var uy=ot("util"),Th=dc(),cy=mc(),ly=Hh.exports=function(e){Th.call(this);let t=[],n=this;this._filter=new cy(e,{read:this.read.bind(this),write:function(r){t.push(r)},complete:function(){n.emit("complete",Buffer.concat(t))}}),this._filter.start()};uy.inherits(ly,Th)});var ci=He((QR,Ah)=>{Ah.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 wc=He((ZR,Lh)=>{var pc=[];(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;pc[e]=t}})();var bc=Lh.exports=function(){this._crc=-1};bc.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=pc[(this._crc^e[t])&255]^this._crc>>>8;return!0};bc.prototype.crc32=function(){return this._crc^-1};bc.crc32=function(e){let t=-1;for(let n=0;n<e.length;n++)t=pc[(t^e[n])&255]^t>>>8;return t^-1}});var $c=He((XR,Ch)=>{var Ze=ci(),fy=wc(),tt=Ch.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ze.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ze.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ze.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ze.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ze.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ze.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};tt.prototype.start=function(){this.read(Ze.PNG_SIGNATURE.length,this._parseSignature.bind(this))};tt.prototype._parseSignature=function(e){let t=Ze.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};tt.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r="";for(let s=4;s<8;s++)r+=String.fromCharCode(e[s]);let i=Boolean(e[4]&32);if(!this._hasIHDR&&n!==Ze.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new fy,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](t);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(t+4,this._skipChunk.bind(this))};tt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};tt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};tt.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error("Crc error - "+t+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};tt.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))};tt.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),n=e.readUInt32BE(4),r=e[8],i=e[9],s=e[10],o=e[11],a=e[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ze.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(s!==0){this.error(Error("Unsupported compression method"));return}if(o!==0){this.error(Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Ze.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:n,depth:r,interlace:Boolean(a),palette:Boolean(i&Ze.COLORTYPE_PALETTE),color:Boolean(i&Ze.COLORTYPE_COLOR),alpha:Boolean(i&Ze.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};tt.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))};tt.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};tt.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))};tt.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===Ze.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(e.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}if(this._colorType===Ze.COLORTYPE_GRAYSCALE)this.transColor([e.readUInt16BE(0)]);if(this._colorType===Ze.COLORTYPE_COLOR)this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]);this._handleChunkEnd()};tt.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))};tt.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/Ze.GAMMA_DIVISION),this._handleChunkEnd()};tt.prototype._handleIDAT=function(e){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-e,this._parseIDAT.bind(this,e))};tt.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===Ze.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(t);let n=e-t.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};tt.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))};tt.prototype._parseIEND=function(e){if(this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var kc=He((by)=>{var _h=hc(),dy=[function(){},function(e,t,n,r){if(r===t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error("Ran out of data");let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error("Ran out of data");e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],hy=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function gy(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error("Ran out of data");let s=e[r];r++;let o,a,u,c,l,f,d,h;switch(t){default:throw Error("unrecognised depth");case 16:d=e[r],r++,n.push((s<<8)+d);break;case 4:d=s&15,h=s>>4,n.push(h,d);break;case 2:l=s&3,f=s>>2&3,d=s>>4&3,h=s>>6&3,n.push(h,d,f,l);break;case 1:o=s&1,a=s>>1&1,u=s>>2&1,c=s>>3&1,l=s>>4&1,f=s>>5&1,d=s>>6&1,h=s>>7&1,n.push(h,d,f,l,c,u,a,o);break}}return{get:function(s){while(n.length<s)i();let o=n.slice(0,s);return n=n.slice(s),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error("extra data found")}}}function my(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++)for(let l=0;l<o;l++){let f=n(l,c,u);dy[r](t,i,f,s),s+=r}return s}function py(e,t,n,r,i,s){let{width:o,height:a,index:u}=e;for(let c=0;c<a;c++){for(let l=0;l<o;l++){let f=i.get(r),d=n(l,c,u);hy[r](t,f,d,s)}i.resetAfterLine()}}by.dataToBitMap=function(e,t){let{width:n,height:r,depth:i,bpp:s,interlace:o}=t,a;if(i!==8)a=gy(e,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let c=Math.pow(2,i)-1,l=0,f,d;if(o)f=_h.getImagePasses(n,r),d=_h.getInterlaceIterator(n,r);else{let h=0;d=function(){let g=h;return h+=4,g},f=[{width:n,height:r}]}for(let h=0;h<f.length;h++)if(i===8)l=my(f[h],u,d,s,e,l);else py(f[h],u,d,s,a,c);if(i===8){if(l!==e.length)throw Error("extra data found")}else a.end();return u}});var yc=He((eO,Gh)=>{function $y(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=i[e[s]];if(!u)throw Error("index "+e[s]+" not in palette");for(let c=0;c<4;c++)t[s+c]=u[c];s+=4}}function ky(e,t,n,r,i){let s=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let u=!1;if(i.length===1){if(i[0]===e[s])u=!0}else if(i[0]===e[s]&&i[1]===e[s+1]&&i[2]===e[s+2])u=!0;if(u)for(let c=0;c<4;c++)t[s+c]=0;s+=4}}function yy(e,t,n,r,i){let s=255,o=Math.pow(2,i)-1,a=0;for(let u=0;u<r;u++)for(let c=0;c<n;c++){for(let l=0;l<4;l++)t[a+l]=Math.floor(e[a+l]*s/o+0.5);a+=4}}Gh.exports=function(e,t,n=!1){let{depth:r,width:i,height:s,colorType:o,transColor:a,palette:u}=t,c=e;if(o===3)$y(e,c,i,s,u);else{if(a)ky(e,c,i,s,a);if(r!==8&&!n){if(r===16)c=Buffer.alloc(i*s*4);yy(e,c,i,s,r)}}return c}});var jh=He((tO,Uh)=>{var Ey=ot("util"),Ec=ot("zlib"),Wh=dc(),vy=xh(),My=$c(),Sy=kc(),Iy=yc(),tn=Uh.exports=function(e){Wh.call(this),this._parser=new My(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};Ey.inherits(tn,Wh);tn.prototype._handleError=function(e){if(this.emit("error",e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};tn.prototype._inflateData=function(e){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ec.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,Ec.Z_MIN_CHUNK);this._inflate=Ec.createInflate({chunkSize:r});let i=n,s=this.emit.bind(this,"error");this._inflate.on("error",function(a){if(!i)return;s(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){if(!i)return;if(a.length>i)a=a.slice(0,i);i-=a.length,o(a)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(e)};tn.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new vy(this._bitmapInfo)};tn.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e};tn.prototype._handlePalette=function(e){this._bitmapInfo.palette=e};tn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};tn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};tn.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};tn.prototype._complete=function(e){if(this.errord)return;let t;try{let n=Sy.dataToBitMap(e,this._bitmapInfo);t=Iy(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",t)}});var Bh=He((nO,Kh)=>{var xt=ci();Kh.exports=function(e,t,n,r){let i=[xt.COLORTYPE_COLOR_ALPHA,xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=function(){let b=new ArrayBuffer(2);return new DataView(b).setInt16(0,256,!0),new Int16Array(b)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&g)return e}let s=r.bitDepth!==16?e:new Uint16Array(e.buffer),o=255,a=xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(a===4&&!r.inputHasAlpha)a=3;let u=xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)o=65535,u*=2;let c=Buffer.alloc(t*n*u),l=0,f=0,d=r.bgColor||{};if(d.red===void 0)d.red=o;if(d.green===void 0)d.green=o;if(d.blue===void 0)d.blue=o;function h(){let g,b,p,m=o;switch(r.inputColorType){case xt.COLORTYPE_COLOR_ALPHA:m=s[l+3],g=s[l],b=s[l+1],p=s[l+2];break;case xt.COLORTYPE_COLOR:g=s[l],b=s[l+1],p=s[l+2];break;case xt.COLORTYPE_ALPHA:m=s[l+1],g=s[l],b=g,p=g;break;case xt.COLORTYPE_GRAYSCALE:g=s[l],b=g,p=g;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)m/=o,g=Math.min(Math.max(Math.round((1-m)*d.red+m*g),0),o),b=Math.min(Math.max(Math.round((1-m)*d.green+m*b),0),o),p=Math.min(Math.max(Math.round((1-m)*d.blue+m*p),0),o)}return{red:g,green:b,blue:p,alpha:m}}for(let g=0;g<n;g++)for(let b=0;b<t;b++){let p=h(s,l);switch(r.colorType){case xt.COLORTYPE_COLOR_ALPHA:case xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(c[f]=p.red,c[f+1]=p.green,c[f+2]=p.blue,i)c[f+3]=p.alpha}else if(c.writeUInt16BE(p.red,f),c.writeUInt16BE(p.green,f+2),c.writeUInt16BE(p.blue,f+4),i)c.writeUInt16BE(p.alpha,f+6);break;case xt.COLORTYPE_ALPHA:case xt.COLORTYPE_GRAYSCALE:{let m=(p.red+p.green+p.blue)/3;if(r.bitDepth===8){if(c[f]=m,i)c[f+1]=p.alpha}else if(c.writeUInt16BE(m,f),i)c.writeUInt16BE(p.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}l+=a,f+=u}return c}});var zh=He((rO,qh)=>{var Jh=gc();function Ny(e,t,n,r,i){for(let s=0;s<n;s++)r[i+s]=e[t+s]}function Py(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++)r+=Math.abs(e[s]);return r}function Ry(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=e[t+o]-a;r[i+o]=u}}function Oy(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=e[t+s]-o;i+=Math.abs(a)}return i}function Fy(e,t,n,r,i){for(let s=0;s<n;s++){let o=t>0?e[t+s-n]:0,a=e[t+s]-o;r[i+s]=a}}function Ty(e,t,n){let r=0,i=t+n;for(let s=t;s<i;s++){let o=t>0?e[s-n]:0,a=e[s]-o;r+=Math.abs(a)}return r}function Hy(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=e[t+o]-(a+u>>1);r[i+o]=c}}function xy(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=e[t+s]-(o+a>>1);i+=Math.abs(u)}return i}function Ay(e,t,n,r,i,s){for(let o=0;o<n;o++){let a=o>=s?e[t+o-s]:0,u=t>0?e[t+o-n]:0,c=t>0&&o>=s?e[t+o-(n+s)]:0,l=e[t+o]-Jh(a,u,c);r[i+o]=l}}function Ly(e,t,n,r){let i=0;for(let s=0;s<n;s++){let o=s>=r?e[t+s-r]:0,a=t>0?e[t+s-n]:0,u=t>0&&s>=r?e[t+s-(n+r)]:0,c=e[t+s]-Jh(o,a,u);i+=Math.abs(c)}return i}var Cy={0:Ny,1:Ry,2:Fy,3:Hy,4:Ay},_y={0:Py,1:Oy,2:Ty,3:xy,4:Ly};qh.exports=function(e,t,n,r,i){let s;if(!("filterType"in r)||r.filterType===-1)s=[0,1,2,3,4];else if(typeof r.filterType==="number")s=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let o=t*i,a=0,u=0,c=Buffer.alloc((o+1)*n),l=s[0];for(let f=0;f<n;f++){if(s.length>1){let d=1/0;for(let h=0;h<s.length;h++){let g=_y[s[h]](e,u,o,i);if(g<d)l=s[h],d=g}}c[a]=l,a++,Cy[l](e,u,o,c,a,i),a+=o,u+=o}return c}});var vc=He((iO,Vh)=>{var ut=ci(),Gy=wc(),Wy=Bh(),Uy=zh(),jy=ot("zlib"),Un=Vh.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel!=null?e.deflateLevel:9,e.deflateStrategy=e.deflateStrategy!=null?e.deflateStrategy:3,e.inputHasAlpha=e.inputHasAlpha!=null?e.inputHasAlpha:!0,e.deflateFactory=e.deflateFactory||jy.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==="number"?e.colorType:ut.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==="number"?e.inputColorType:ut.COLORTYPE_COLOR_ALPHA,[ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error("option color type:"+e.colorType+" is not supported at present");if([ut.COLORTYPE_GRAYSCALE,ut.COLORTYPE_COLOR,ut.COLORTYPE_COLOR_ALPHA,ut.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error("option input color type:"+e.inputColorType+" is not supported at present");if(e.bitDepth!==8&&e.bitDepth!==16)throw Error("option bit depth:"+e.bitDepth+" is not supported at present")};Un.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Un.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Un.prototype.filterData=function(e,t,n){let r=Wy(e,t,n,this._options),i=ut.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Uy(r,t,n,this._options,i)};Un.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t)t.copy(r,8);return r.writeInt32BE(Gy.crc32(r.slice(4,r.length-4)),r.length-4),r};Un.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*ut.GAMMA_DIVISION),0),this._packChunk(ut.TYPE_gAMA,t)};Un.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(ut.TYPE_IHDR,n)};Un.prototype.packIDAT=function(e){return this._packChunk(ut.TYPE_IDAT,e)};Un.prototype.packIEND=function(){return this._packChunk(ut.TYPE_IEND,null)}});var Xh=He((sO,Zh)=>{var Ky=ot("util"),Yh=ot("stream"),By=ci(),Jy=vc(),Qh=Zh.exports=function(e){Yh.call(this);let t=e||{};this._packer=new Jy(t),this._deflate=this._packer.createDeflate(),this.readable=!0};Ky.inherits(Qh,Yh);Qh.prototype.pack=function(e,t,n,r){if(this.emit("data",Buffer.from(By.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(t,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(s){this.emit("data",this._packer.packIDAT(s))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var ig=He((us,rg)=>{var Dh=ot("assert").ok,li=ot("zlib"),qy=ot("util"),eg=ot("buffer").kMaxLength;function Nr(e){if(!(this instanceof Nr))return new Nr(e);if(e&&e.chunkSize<li.Z_MIN_CHUNK)e.chunkSize=li.Z_MIN_CHUNK;if(li.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 zy(e){return new Nr(e)}function tg(e,t){if(t)process.nextTick(t);if(!e._handle)return;e._handle.close(),e._handle=null}Nr.prototype._processChunk=function(e,t,n){if(typeof n==="function")return li.Inflate._processChunk.call(this,e,t,n);let r=this,i=e&&e.length,s=this._chunkSize-this._offset,o=this._maxLength,a=0,u=[],c=0,l;this.on("error",function(g){l=g});function f(g,b){if(r._hadError)return;let p=s-b;if(Dh(p>=0,"have should not go down"),p>0){let m=r._buffer.slice(r._offset,r._offset+p);if(r._offset+=p,m.length>o)m=m.slice(0,o);if(u.push(m),c+=m.length,o-=m.length,o===0)return!1}if(b===0||r._offset>=r._chunkSize)s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(b===0)return a+=i-g,i=g,!0;return!1}Dh(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>=eg)throw tg(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+eg.toString(16)+" bytes");let h=Buffer.concat(u,c);return tg(this),h};qy.inherits(Nr,li.Inflate);function Vy(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=li.Z_FINISH;return e._processChunk(t,n)}function ng(e,t){return Vy(new Nr(t),e)}rg.exports=us=ng;us.Inflate=Nr;us.createInflate=zy;us.inflateSync=ng});var Mc=He((oO,og)=>{var sg=og.exports=function(e){this._buffer=e,this._reads=[]};sg.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})};sg.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 ag=He((Zy)=>{var Yy=Mc(),Qy=mc();Zy.process=function(e,t){let n=[],r=new Yy(e);return new Qy(t,{read:r.read.bind(r),write:function(s){n.push(s)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var fg=He((uO,lg)=>{var ug=!0,cg=ot("zlib"),Dy=ig();if(!cg.deflateSync)ug=!1;var e1=Mc(),t1=ag(),n1=$c(),r1=kc(),i1=yc();lg.exports=function(e,t){if(!ug)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(M){n=M}let i;function s(M){i=M}function o(M){i.transColor=M}function a(M){i.palette=M}function u(){i.alpha=!0}let c;function l(M){c=M}let f=[];function d(M){f.push(M)}let h=new e1(e);if(new n1(t,{read:h.read.bind(h),error:r,metadata:s,gamma:l,palette:a,transColor:o,inflateData:d,simpleTransparency:u}).start(),h.process(),n)throw n;let b=Buffer.concat(f);f.length=0;let p;if(i.interlace)p=cg.inflateSync(b);else{let w=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;p=Dy(b,{chunkSize:w,maxLength:w})}if(b=null,!p||!p.length)throw Error("bad png - invalid inflate data response");let m=t1.process(p,i);b=null;let $=r1.dataToBitMap(m,i);m=null;let E=i1($,i,t.skipRescale);return i.data=E,i.gamma=c||0,i}});var mg=He((cO,gg)=>{var dg=!0,hg=ot("zlib");if(!hg.deflateSync)dg=!1;var s1=ci(),o1=vc();gg.exports=function(e,t){if(!dg)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new o1(t||{}),i=[];if(i.push(Buffer.from(s1.PNG_SIGNATURE)),i.push(r.packIHDR(e.width,e.height)),e.gamma)i.push(r.packGAMA(e.gamma));let s=r.filterData(e.data,e.width,e.height),o=hg.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 pg=He((c1)=>{var a1=fg(),u1=mg();c1.read=function(e,t){return a1(e,t||{})};c1.write=function(e,t){return u1(e,t)}});var wg=He((p1)=>{var d1=ot("util"),bg=ot("stream"),h1=jh(),g1=Xh(),m1=pg(),lt=p1.PNG=function(e){if(bg.call(this),e=e||{},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new h1(e),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new g1(e),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};d1.inherits(lt,bg);lt.sync=m1;lt.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};lt.prototype.parse=function(e,t){if(t){let n,r;n=function(i){this.removeListener("error",r),this.data=i,t(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),t(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(e),this};lt.prototype.write=function(e){return this._parser.write(e),!0};lt.prototype.end=function(e){this._parser.end(e)};lt.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit("metadata",e)};lt.prototype._gamma=function(e){this.gamma=e};lt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};lt.bitblt=function(e,t,n,r,i,s,o,a){if(n|=0,r|=0,i|=0,s|=0,o|=0,a|=0,n>e.width||r>e.height||n+i>e.width||r+s>e.height)throw Error("bitblt reading outside image");if(o>t.width||a>t.height||o+i>t.width||a+s>t.height)throw Error("bitblt writing outside image");for(let u=0;u<s;u++)e.data.copy(t.data,(a+u)*t.width+o<<2,(r+u)*e.width+n<<2,(r+u)*e.width+n+i<<2)};lt.prototype.bitblt=function(e,t,n,r,i,s,o){return lt.bitblt(this,e,t,n,r,i,s,o),this};lt.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let i=0;i<3;i++){let s=e.data[r+i]/255;s=Math.pow(s,0.45454545454545453/e.gamma),e.data[r+i]=Math.round(s*255)}}e.gamma=0}};lt.prototype.adjustGamma=function(){lt.adjustGamma(this)}});import{spawnSync as QP}from"node:child_process";import{isMainThread as ZP}from"node:worker_threads";import{parseArgs as jP}from"node:util";var et={name:"@kecan0406/ttheme",version:"1.2.4",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal, Warp and Konsole",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2","konsole"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","@xterm/headless":"6.0.0","fast-string-width":"^3.0.2","jpeg-js":"^0.4.4",pngjs:"7.0.0","smol-toml":"^1.9.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{existsSync as ZN,readFileSync as o$}from"node:fs";import{styleText as Co}from"node:util";import{stdout as qd,stdin as ok}from"node:process";import ak from"node:readline";var Rd=(()=>{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}})(),Od=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Fd=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var J$=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,q$=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Td=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,z$=/\t{1,1000}/y,Hd=/[\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,V$=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Y$=/\p{M}+/gu,Q$={limit:1/0,ellipsis:""},xd=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?xd(i,Q$,n).width:0),o=0,a=n.controlWidth??0,u=n.tabWidth??8,c=n.emojiWidth??2,l=2,f=n.regularWidth??1,d=n.wideWidth??2,h=[[V$,f],[J$,0],[q$,a],[z$,u],[Hd,c],[Td,d]],g=0,b=0,p=e.length,m=0,$=!1,E=p,M=Math.max(0,r-s),w=0,S=0,k=0,N=0;e:while(!0){if(S>w||b>=p&&b>g){let R=e.slice(w,S)||e.slice(g,b);m=0;for(let H of R.replaceAll(Y$,"")){let x=H.codePointAt(0)||0;if(Od(x))N=2;else if(Fd(x))N=d;else N=f;if(k+N>M)E=Math.min(E,Math.max(w,g)+m);if(k+N>r){$=!0;break e}m+=H.length,k+=N}w=S=0}if(b>=p)break e;for(let R=0,H=h.length;R<H;R++){let[x,C]=h[R];if(x.lastIndex=b,x.test(e)){if(m=x===Td?Rd(e.slice(b,x.lastIndex)):x===Hd?1:x.lastIndex-b,N=m*C,k+N>M)E=Math.min(E,b+Math.floor((M-k)/C));if(k+N>r){$=!0;break e}k+=N,w=g,S=b,b=g=x.lastIndex;continue e}}b+=1}return{width:$?M:k,index:$?E:p,truncated:$,ellipsed:$&&r>=s}},Ad=xd;var Z$={limit:1/0,ellipsis:"",ellipsisWidth:0},X$=(e,t={})=>{return Ad(e,Z$,t).width},$e=X$;var Ho="\x1B",Wd="›",D$=39,ju="\x07",Ud="[",ek="]",jd="m",Ku=`${ek}8;;`,Ld=new RegExp(`(?:\\${Ud}(?<code>\\d+)m|\\${Ku}(?<uri>.*)${ju})`,"y"),Cd=(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},_d=(e)=>`${Ho}${Ud}${e}${jd}`,Gd=(e)=>`${Ho}${Ku}${e}${ju}`,Uu=(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===Ho||f===Wd)i=!0,s=t.startsWith(Ku,l+1);if(i){if(s){if(f===ju)i=!1,s=!1}else if(f===jd)i=!1}else if(a+=d,a===n&&!c.done)e.push(""),a=0;u=c,c=r.next(),l+=f.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},tk=(e)=>{let t=e.split(" "),n=t.length;while(n){if($e(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},nk=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],u=0;for(let f=0;f<o.length;f++){let d=o[f];if(n.trim!==!1){let g=a.at(-1)??"",b=g.trimStart();if(g.length!==b.length)a[a.length-1]=b,u=$e(b)}if(f!==0){if(u>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),u=0;if(u||n.trim===!1)a[a.length-1]+=" ",u++}let h=$e(d);if(n.hard&&h>t){let g=t-u,b=1+Math.floor((h-g-1)/t);if(Math.floor((h-1)/t)<b)a.push("");Uu(a,d,t),u=$e(a.at(-1)??"");continue}if(u+h>t&&u&&h){if(n.wordWrap===!1&&u<t){Uu(a,d,t),u=$e(a.at(-1)??"");continue}a.push(""),u=0}if(u+h>t&&n.wordWrap===!1){Uu(a,d,t),u=$e(a.at(-1)??"");continue}a[a.length-1]+=d,u+=h}if(n.trim!==!1)a=a.map((f)=>tk(f));let c=a.join(`
3
+ `),l=!1;for(let f=0;f<c.length;f++){let d=c[f];if(r+=d,!l){if(l=d>="\uD800"&&d<="\uDBFF",l)continue}else l=!1;if(d===Ho||d===Wd){Ld.lastIndex=f+1;let g=Ld.exec(c)?.groups;if(g?.code!==void 0){let b=Number.parseFloat(g.code);i=b===D$?void 0:b}else if(g?.uri!==void 0)s=g.uri.length===0?void 0:g.uri}if(c[f+1]===`
4
+ `){if(s)r+=Gd("");let h=i?Cd(i):void 0;if(i&&h)r+=_d(h)}else if(d===`
5
+ `){if(i&&Cd(i))r+=_d(i);if(s)r+=Gd(s)}}return r},rk=/\r?\n/;function Tn(e,t,n){return String(e).normalize().split(rk).map((r)=>nk(r,t,n)).join(`
6
+ `)}var pt=To(Ju(),1);function ti(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?ti(s,t<0?-1:1,n):s}function xo(e,t,n,r){let i=r.split(`
7
+ `),s=0,o=e;for(let u of i){if(o<=u.length)break;o-=u.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let u=0;u<s;u++)a+=i[u].length+1;return a+o}var uk=["up","down","left","right","space","enter","cancel"],ck=["January","February","March","April","May","June","July","August","September","October","November","December"],at={actions:new Set(uk),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...ck],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function zd(e,t){if(typeof e=="string")return at.aliases.get(e)===t;for(let n of e)if(n!==void 0&&zd(n,t))return!0;return!1}function lk(e,t){if(e===t)return;let n=e.split(`
8
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 ZP=globalThis.process.platform.startsWith("win"),Bu=Symbol("clack:cancel");function ht(e){return e===Bu}function xo(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Co=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,qu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ns(e,t,n,r=n,i=n,s){let o=Co(e??Kd);return Hn(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 hR=globalThis.process.platform.startsWith("win"),zu=Symbol("clack:cancel");function ht(e){return e===zu}function Ao(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var _o=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Yu=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ns(e,t,n,r=n,i=n,s){let o=_o(e??qd);return Tn(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 Jd(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 Rt{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=nk,output:r=Kd,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(Bu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=rk.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),xo(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),xo(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),xo(this.input,!1),e(Bu)})})}_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=Jd(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")}Bd([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
- `),xo(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Hn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
- `).length-1;this.output.write(pt.cursor.move(-999,e*-1))}render(){let e=Hn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(pt.cursor.hide);else{let t=ok(this._prevFrame,e),n=qu(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(pt.cursor.move(0,s-i)),this.output.write(pt.erase.lines(1));let o=e.split(`
11
+ `)}function Vd(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class Ft{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=ok,output:r=qd,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(zu);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ak.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Ao(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),Ao(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(pt.cursor.show),this.output.off("resize",this.render),Ao(this.input,!1),e(zu)})})}_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=Vd(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}zd([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
12
+ `),Ao(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Tn(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
13
+ `).length-1;this.output.write(pt.cursor.move(-999,e*-1))}render(){let e=Tn(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(pt.cursor.hide);else{let t=lk(this._prevFrame,e),n=Yu(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(pt.cursor.move(0,s-i)),this.output.write(pt.erase.lines(1));let o=e.split(`
14
14
  `);this.output.write(o[s]),this._prevFrame=e,this.output.write(pt.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(pt.cursor.move(0,a))}this.output.write(pt.erase.down());let o=e.split(`
15
15
  `).slice(s);this.output.write(o.join(`
16
- `)),this._prevFrame=e;return}}this.output.write(pt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function ak(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 uk(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function ck(e,t){if(t)return e?t:t[0]}var lk=class extends Rt{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Lo(["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}${Lo("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??uk;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=ti(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=ck(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=ak(this.focusedValue,this.filteredOptions);this.#t=ti(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 zu extends Rt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(pt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var fk={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Ud(e){return[...e].map((t)=>fk[t])}function dk(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 Ku(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Ao(e){return{year:Ku(e.year),month:Ku(e.month),day:Ku(e.day)}}function Ju(e,t){return new Date(e||2001,t||1,0).getDate()}function qd(e){let{year:t,month:n,day:r}=Ao(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 jd(e){let t=qd(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function hk(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:Ju(t.year,t.month)}}class zd extends Rt{#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(jd(this.#e)??void 0)}constructor(e){let t=e.format?{segments:Ud(e.format),separator:e.separator??"/"}:dk(e.locale),n=e.separator??t.separator,r=e.format?Ud(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=hk(n.type,Ao(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:qd(this.#e);if(l){let{year:d,month:h}=l,g=Ju(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}=Ao(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}=Ao(this.#e);if(t&&n&&r){let i=Ju(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=jd(this.#e)??e.defaultValue??void 0}}var gk=class extends Rt{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}})}},mk=new Set(["up","down","left","right"]);class Yd extends Rt{#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(pt.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function fk(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function dk(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function hk(e,t){if(t)return e?t:t[0]}var gk=class extends Ft{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#n="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Co(["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}${Co("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??dk;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#r(i,s)),this.on("userInput",(i)=>this.#i(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#r(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,u=this.options,c=a!==void 0&&a!==""&&u.some((l)=>!l.disabled&&(this.#e?this.#e(a,l):!0));if(n.name==="tab"&&o&&c){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=ti(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=hk(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#i(t){if(t!==this.#n){this.#n=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=fk(this.focusedValue,this.filteredOptions);this.#t=ti(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 Qu extends Ft{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(pt.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var mk={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Bd(e){return[...e].map((t)=>mk[t])}function pk(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function qu(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Lo(e){return{year:qu(e.year),month:qu(e.month),day:qu(e.day)}}function Vu(e,t){return new Date(e||2001,t||1,0).getDate()}function Yd(e){let{year:t,month:n,day:r}=Lo(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 Jd(e){let t=Yd(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function bk(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:Vu(t.year,t.month)}}class Qd extends Ft{#t;#n;#e;#s;#a;#r={segmentIndex:0,positionInSegment:0};#i=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#r}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#n}get formattedValue(){return this.#f(this.#e)}#f(e){return this.#t.map((t)=>e[t.type]).join(this.#n)}#u(){this._setUserInput(this.#f(this.#e)),this._setValue(Jd(this.#e)??void 0)}constructor(e){let t=e.format?{segments:Bd(e.format),separator:e.separator??"/"}:pk(e.locale),n=e.separator??t.separator,r=e.format?Bd(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#n=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#u(),this.on("cursor",(a)=>this.#g(a)),this.on("key",(a,u)=>this.#m(a,u)),this.on("finalize",()=>this.#p(e))}#c(){let e=Math.max(0,Math.min(this.#r.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#r.positionInSegment=Math.max(0,Math.min(this.#r.positionInSegment,t.len-1)),{segment:t,index:e}}#l(e){this.inlineError="",this.#o=null;let t=this.#c();t&&(this.#r.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#r.positionInSegment=0,this.#i=!0)}#d(e){let t=this.#c();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=bk(n.type,Lo(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:Yd(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}=Lo(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}=Lo(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=Jd(this.#e)??e.defaultValue??void 0}}var wk=class extends Ft{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},$k=new Set(["up","down","left","right"]);class Zd extends Ft{#t=!1;#n;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
17
17
  `?`${t}█
18
- ${r}`:`${t}${Lo("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=To(this._cursor,0,-1,t);return;case"down":this._cursor=To(this._cursor,0,1,t);return;case"left":this._cursor=To(this._cursor,-1,0,t);return;case"right":this._cursor=To(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#n)return this.focused==="submit"?!0:(this.#e(`
18
+ ${r}`:`${t}${Co("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=xo(this._cursor,0,-1,t);return;case"down":this._cursor=xo(this._cursor,0,1,t);return;case"left":this._cursor=xo(this._cursor,-1,0,t);return;case"right":this._cursor=xo(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&&mk.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 Yu extends Rt{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?ti(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=ti(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ti(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Qu extends Rt{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}${Lo("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 oO}from"node:util";import Ft from"node:process";var nh=Fo(ju(),1);function pk(){if(Ft.platform!=="win32")return Ft.env.TERM!=="linux";return Boolean(Ft.env.CI)||Boolean(Ft.env.WT_SESSION)||Boolean(Ft.env.TERMINUS_SUBLIME)||Ft.env.ConEmuTask==="{cmd::Cmder}"||Ft.env.TERM_PROGRAM==="Terminus-Sublime"||Ft.env.TERM_PROGRAM==="vscode"||Ft.env.TERM==="xterm-256color"||Ft.env.TERM==="alacritty"||Ft.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bk=pk();var Re=(e,t)=>bk?e:t,wk=Re("◆","*"),$k=Re("■","x"),kk=Re("▲","x"),Vu=Re("◇","o"),yk=Re("┌","T"),ke=Re("│","|"),xn=Re("└","—"),lO=Re("┐","T"),fO=Re("┘","—"),Qd=Re("●",">"),Vd=Re("○"," "),Ek=Re("◻","[•]"),Zd=Re("◼","[+]"),Xd=Re("◻","[ ]"),dO=Re("▪","•"),Dd=Re("─","-"),vk=Re("╮","+"),Mk=Re("├","+"),Sk=Re("╯","+"),Ik=Re("╰","+"),hO=Re("╭","+"),Nk=Re("●","•"),Pk=Re("◆","*"),Ok=Re("▲","!"),Rk=Re("■","x"),Zu=(e)=>{switch(e){case"initial":case"active":return I("cyan",wk);case"cancel":return I("red",$k);case"error":return I("yellow",kk);case"submit":return I("green",Vu)}},Fk=(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 Hk(e,t){let n=[`${t?`${I("cyan",ke)} `:""}${e.join(" • ")}`];return t&&n.push(I("cyan",xn)),n}var eh=(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}},th=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Co(r)-s,u=qu(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,b=Math.min(d+f,t.length),p=[],m=0;h&&m++,g&&m++;let $=d+(h?1:0),E=b-(g?1:0);for(let w=$;w<E;w++){let S=t[w],k=S?n(S,w===e):"",N=Hn(k,a,{hard:!0,trim:!1}).split(`
22
- `);p.push(N),m+=N.length}if(m>l){let w=0,S=0,k=m,N=e-$,O=l,T=()=>eh(p,k,0,N,O),x=()=>eh(p,k,N+1,p.length,O,!0);h?({lineCount:k,removals:w}=T(),k>O&&(g||(O-=1),{lineCount:k,removals:S}=x())):(g||(O-=1),{lineCount:k,removals:S}=x(),k>O&&(O-=1,{lineCount:k,removals:w}=T())),w>0&&(h=!0,p.splice(0,w)),S>0&&(g=!0,p.splice(p.length-S,S))}let M=[];h&&M.push(c);for(let w of p)for(let S of w)M.push(S);return g&&M.push(c),M};var An=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new zu({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=`${Zu(this.state)} `,s=r?`${I("gray",ke)} `:"",o=ns(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&&$k.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#n){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#n&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class Zu extends Ft{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?ti(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=ti(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ti(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class Xu extends Ft{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}█`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Co("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 ER}from"node:util";import Tt from"node:process";var sh=To(Ju(),1);function kk(){if(Tt.platform!=="win32")return Tt.env.TERM!=="linux";return Boolean(Tt.env.CI)||Boolean(Tt.env.WT_SESSION)||Boolean(Tt.env.TERMINUS_SUBLIME)||Tt.env.ConEmuTask==="{cmd::Cmder}"||Tt.env.TERM_PROGRAM==="Terminus-Sublime"||Tt.env.TERM_PROGRAM==="vscode"||Tt.env.TERM==="xterm-256color"||Tt.env.TERM==="alacritty"||Tt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var yk=kk();var Oe=(e,t)=>yk?e:t,Ek=Oe("◆","*"),vk=Oe("■","x"),Mk=Oe("▲","x"),Du=Oe("◇","o"),Sk=Oe("┌","T"),ke=Oe("│","|"),xn=Oe("└","—"),IR=Oe("┐","T"),NR=Oe("┘","—"),Xd=Oe("●",">"),Dd=Oe("○"," "),Ik=Oe("◻","[•]"),eh=Oe("◼","[+]"),th=Oe("◻","[ ]"),PR=Oe("▪","•"),nh=Oe("─","-"),Nk=Oe("╮","+"),Pk=Oe("├","+"),Rk=Oe("╯","+"),Ok=Oe("╰","+"),RR=Oe("╭","+"),Fk=Oe("●","•"),Tk=Oe("◆","*"),Hk=Oe("▲","!"),xk=Oe("■","x"),ec=(e)=>{switch(e){case"initial":case"active":return I("cyan",Ek);case"cancel":return I("red",vk);case"error":return I("yellow",Mk);case"submit":return I("green",Du)}},Ak=(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 Lk(e,t){let n=[`${t?`${I("cyan",ke)} `:""}${e.join(" • ")}`];return t&&n.push(I("cyan",xn)),n}var rh=(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}},ih=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=_o(r)-s,u=Yu(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,b=Math.min(d+f,t.length),p=[],m=0;h&&m++,g&&m++;let $=d+(h?1:0),E=b-(g?1:0);for(let w=$;w<E;w++){let S=t[w],k=S?n(S,w===e):"",N=Tn(k,a,{hard:!0,trim:!1}).split(`
22
+ `);p.push(N),m+=N.length}if(m>l){let w=0,S=0,k=m,N=e-$,R=l,H=()=>rh(p,k,0,N,R),x=()=>rh(p,k,N+1,p.length,R,!0);h?({lineCount:k,removals:w}=H(),k>R&&(g||(R-=1),{lineCount:k,removals:S}=x())):(g||(R-=1),{lineCount:k,removals:S}=x(),k>R&&(R-=1,{lineCount:k,removals:w}=H())),w>0&&(h=!0,p.splice(0,w)),S>0&&(g=!0,p.splice(p.length-S,S))}let M=[];h&&M.push(c);for(let w of p)for(let S of w)M.push(S);return g&&M.push(c),M};var An=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Qu({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=`${ec(this.state)} `,s=r?`${I("gray",ke)} `:"",o=ns(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",xn):"";return`${a}${c}${this.value?`${I("green",Qd)} ${t}`:`${I("dim",Vd)} ${I("dim",t)}`}${e.vertical?r?`
25
+ ${I("gray",ke)}`:""}`}default:{let c=r?`${I("cyan",ke)} `:"",l=r?I("cyan",xn):"";return`${a}${c}${this.value?`${I("green",Xd)} ${t}`:`${I("dim",Dd)} ${I("dim",t)}`}${e.vertical?r?`
26
26
  ${I("cyan",ke)} `:`
27
- `:` ${I("dim","/")} `}${this.value?`${I("dim",Vd)} ${I("dim",n)}`:`${I("green",Qd)} ${n}`}
27
+ `:` ${I("dim","/")} `}${this.value?`${I("dim",Dd)} ${I("dim",n)}`:`${I("green",Xd)} ${n}`}
28
28
  ${l}
29
- `}}}}).prompt()};var Tk=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Space:")} select`,`${I("dim","Enter:")} confirm`],rs=(e,t)=>e.split(`
29
+ `}}}}).prompt()};var Ck=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Space:")} select`,`${I("dim","Enter:")} confirm`],rs=(e,t)=>e.split(`
30
30
  `).map((n)=>t(n)).join(`
31
- `),rh=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${I("gray",Xd)} ${rs(o,(a)=>I(["strikethrough","gray"],a))}${i.hint?` ${I("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${I("cyan",Ek)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${I("green",Zd)} ${rs(o,(a)=>I("dim",a))}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${rs(o,(a)=>I(["strikethrough","dim"],a))}`:s==="active-selected"?`${I("green",Zd)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${rs(o,(a)=>I("dim",a))}`:`${I("dim",Xd)} ${rs(o,(a)=>I("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Yu({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=ns(e.output,e.message,i?`${Fk(this.state)} `:"",`${Zu(this.state)} `),o=`${i?`${I("gray",ke)}
31
+ `),oh=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${I("gray",th)} ${rs(o,(a)=>I(["strikethrough","gray"],a))}${i.hint?` ${I("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${I("cyan",Ik)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${I("green",eh)} ${rs(o,(a)=>I("dim",a))}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${rs(o,(a)=>I(["strikethrough","dim"],a))}`:s==="active-selected"?`${I("green",eh)} ${o}${i.hint?` ${I("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${rs(o,(a)=>I("dim",a))}`:`${I("dim",th)} ${rs(o,(a)=>I("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Zu({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=ns(e.output,e.message,i?`${Ak(this.state)} `:"",`${ec(this.state)} `),o=`${i?`${I("gray",ke)}
33
33
  `:""}${s}
34
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=ns(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=ns(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",xn)} `:""}${I("yellow",h)}`:` ${h}`).join(`
37
37
  `),f=o.split(`
38
38
  `).length,d=l.split(`
39
- `).length+1;return`${o}${c}${th({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}${ih({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?Hk(Tk,i):i?[I("cyan",xn)]:[],d=f.join(`
44
- `),h=f.length+1;return`${o}${c}${th({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?Lk(Ck,i):i?[I("cyan",xn)]:[],d=f.join(`
44
+ `),h=f.length+1;return`${o}${c}${ih({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
- `}}}}).prompt()};var Tn={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(`
47
+ `}}}}).prompt()};var Hn={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)=>{Tn.message(e,{...t,symbol:I("blue",Nk)})},success:(e,t)=>{Tn.message(e,{...t,symbol:I("green",Pk)})},step:(e,t)=>{Tn.message(e,{...t,symbol:I("green",Vu)})},warn:(e,t)=>{Tn.message(e,{...t,symbol:I("yellow",Ok)})},warning:(e,t)=>{Tn.warn(e,t)},error:(e,t)=>{Tn.message(e,{...t,symbol:I("red",Rk)})}},ni=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",xn)} `:"";n.write(`${r}${I("red",e)}
50
+ `)},info:(e,t)=>{Hn.message(e,{...t,symbol:I("blue",Fk)})},success:(e,t)=>{Hn.message(e,{...t,symbol:I("green",Tk)})},step:(e,t)=>{Hn.message(e,{...t,symbol:I("green",Du)})},warn:(e,t)=>{Hn.message(e,{...t,symbol:I("yellow",Hk)})},warning:(e,t)=>{Hn.warn(e,t)},error:(e,t)=>{Hn.message(e,{...t,symbol:I("red",xk)})}},ni=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",xn)} `:"";n.write(`${r}${I("red",e)}
51
51
 
52
- `)},_o=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",yk)} `:"";n.write(`${r}${e}
53
- `)},Xu=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",ke)}
52
+ `)},Go=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",Sk)} `:"";n.write(`${r}${e}
53
+ `)},tc=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??at.withGuide?`${I("gray",ke)}
54
54
  ${I("gray",xn)} `:"";n.write(`${r}${e}
55
55
 
56
- `)};var xk=(e)=>e,Ak=(e,t,n)=>{let r={hard:!0,trim:!1},i=Hn(e,t,r).split(`
57
- `),s=i.reduce((u,c)=>Math.max($e(c),u),0),o=i.map(n).reduce((u,c)=>Math.max($e(c),u),0),a=t-(o-s);return Hn(e,a,r)},vr=(e="",t="",n)=>{let r=n?.output??Ft.stdout,i=n?.withGuide??at.withGuide,s=n?.format??xk,o=["",...Ak(e,Co(r)-6,s).split(`
56
+ `)};var _k=(e)=>e,Gk=(e,t,n)=>{let r={hard:!0,trim:!1},i=Tn(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 Tn(e,a,r)},vr=(e="",t="",n)=>{let r=n?.output??Tt.stdout,i=n?.withGuide??at.withGuide,s=n?.format??_k,o=["",...Gk(e,_o(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?Mk:Ik;r.write(`${l}${I("green",Vu)} ${I("reset",t)} ${I("gray",Dd.repeat(Math.max(u-a-1,1))+vk)}
60
+ `:"",f=i?Pk:Ok;r.write(`${l}${I("green",Du)} ${I("reset",t)} ${I("gray",nh.repeat(Math.max(u-a-1,1))+Nk)}
61
61
  ${c}
62
- ${I("gray",f+Dd.repeat(u+2)+Sk)}
63
- `)};var gO={light:Re("─","-"),heavy:Re("━","="),block:Re("█","#")};var mO=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Enter:")} confirm`];var pO=`${I("gray",ke)} `;var Du=(e)=>new Qu({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
- `:""}${Zu(this.state)} `}${e.message}
62
+ ${I("gray",f+nh.repeat(u+2)+Rk)}
63
+ `)};var OR={light:Oe("─","-"),heavy:Oe("━","="),block:Oe("█","#")};var FR=[`${I("dim","↑/↓")} to navigate`,`${I("dim","Enter:")} confirm`];var TR=`${I("gray",ke)} `;var nc=(e)=>new Xu({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
+ `:""}${ec(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",xn):"";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",xn):"";return`${n}${o}${i}
70
70
  ${a}
71
- `}}}}).prompt();function ec(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function Xt(e){return`\x1B[38;2;${ec(e)}m`}function Go(e,t){return`\x1B[48;2;${ec(e)};38;2;${ec(t)}m`}function ih(e,t="\x1B[39m"){return`${e.map((n)=>`${Xt(n)}■`).join(" ")}${t}`}var ss="⧉";function Wo(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function Lk(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 sh(e,t){let n="",r=0,i=0;while(i<e.length){let s=Lk(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}=sh(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function bn(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}=sh(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 ap,readFileSync as ll}from"node:fs";import{join as up}from"node:path";var Ck=/^#[0-9a-f]{6}$/;function Ht(e){return Ck.test(e)}function ve(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=ve(e),i=ve(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function Ye(e){let[t,n,r]=ve(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function Ke(e,t){let n=Ye(e),r=Ye(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Uo(e,t){return Math.round(Ke(e,t)*100)/100}function _k(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Be(e){let[t,n,r]=ve(e).map(_k),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var Ln=7,oh=3,tc=0.15,ah=1.6,rc=[1,2,3,4,5,6,9,10,11,12,13,14],uh=[7,15],Cn=[1,2,3,4,5,6],$n={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},as=0.03,Ut=25,ii=15,si=0.08;function wn(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function nc(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=wn(e,i);return Ke(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${Uo(s,r)}:1, needs ${n}:1`]:[]})}function ch(e,t){return Math.min(...t.map((n)=>Ke(wn(e,n),e.background)))}var lh=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Ln,measure:({foreground:e,background:t})=>Ke(e,t),check:({foreground:e,background:t})=>Ke(e,t)<Ln?[`foreground ${e} on ${t} is ${Uo(e,t)}:1, needs ${Ln}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:oh,measure:(e)=>ch(e,rc),check:(e)=>nc(e,rc,oh)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:tc,measure:(e)=>Ye(wn(e,0)),check:(e)=>{let t=wn(e,0);return Ye(t)>tc?[`ANSI 0 ${t} has luminance ${Ye(t).toFixed(3)}, needs <= ${tc}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Ln,measure:(e)=>ch(e,uh),check:(e)=>nc(e,uh,Ln)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:ah,measure:(e)=>Ke(wn(e,8),e.background),check:(e)=>nc(e,[8],ah)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Ln,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Ke(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Ke(e,t)<Ln?[`foreground ${e} on selection ${t} is ${Uo(e,t)}:1, needs ${Ln}:1`]:[]}];function Dt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var _n=(e)=>e>8?e-8:e;function oi(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Cn.includes(_n(n))?[n,n>8?n-8:n+8]:[n]))}function os(e,t){let n=Be(wn(e,t));return n.c<as?void 0:n}function ri(e){let t=oi(e);return rc.flatMap((n)=>{let r=os(e,n),i=$n[_n(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Dt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function Mr(e){let t=new Set(e.signatureSlots);return Cn.flatMap((n)=>{let r=os(e,n),i=os(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Dt(r.h,i.h)}]})}function Sr(e){let t=oi(e);return[0,8].flatMap((n)=>Cn.flatMap((r)=>Cn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=os(e,s),u=os(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Dt(a.h,u.h)<ii&&Math.abs(a.l-u.l)<si?[[s,o]]:[]})))}var Gk=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...ri(e).map((t)=>t.over)),check:(e)=>ri(e).map(({slot:t,hue:n,over:r})=>{let i=$n[_n(t)];return`ANSI ${t} ${wn(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:Ut,measure:(e)=>Math.max(0,...Mr(e).map((t)=>t.gap)),check:(e)=>Mr(e).filter((t)=>t.gap>Ut).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${Ut}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>Sr(e).length,check:(e)=>Sr(e).map(([t,n])=>`ANSI ${t} ${wn(e,t)} and ANSI ${n} ${wn(e,n)} are within ${ii}° hue and ${si} lightness`)}],jo=[...lh,...Gk],ic=jo.map((e)=>e.rule),bt=jo.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Gn(e){return jo.map((t)=>Math.round(t.measure(e)*1000)/1000)}function fh(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function Ir(e){return fh(jo,e)}function dh(e){return fh(lh,e)}function hh(e){return e.flatMap(Ir)}import{chmodSync as Wk,copyFileSync as Uk,existsSync as ai,mkdirSync as jk,readFileSync as sc,realpathSync as Kk,renameSync as Bk,rmSync as gh,statSync as Jk,writeFileSync as qk}from"node:fs";import{dirname as zk}from"node:path";function mh(e){return`${e}.ttheme.bak`}var Yk=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function oc(e){let t=mh(e);if(ai(e)&&!ai(t)&&!Yk.test(sc(e,"utf8")))Uk(e,t)}function K(e,t){let n=ai(e)?Kk(e):e;jk(zk(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(qk(r,t),ai(n))Wk(r,Jk(n).mode&4095);Bk(r,n)}function en(e,t){if((ai(e)?sc(e,"utf8"):void 0)===t)return!1;return oc(e),K(e,t),!0}function ph(e,t){let n=mh(e),r=ai(n)?sc(n,"utf8"):void 0;if(t===""&&r===void 0)return gh(e,{force:!0}),"removed";if(K(e,t),r===void 0||r===t)return gh(n,{force:!0}),"restored";return"kept backup"}import{createHash as Sm}from"node:crypto";import{copyFileSync as SE,existsSync as Jc,mkdirSync as IE,readdirSync as NE,readFileSync as fa,renameSync as Im,rmSync as ki}from"node:fs";import{basename as Nm,isAbsolute as PE,join as D}from"node:path";var wg=Fo(vh(),1),Bo=Fo(mg(),1);import{deflateSync as bg}from"node:zlib";var fi=[137,80,78,71,13,10,26,10],$g=13,kg=3;function di(e){return e.length>=fi.length&&fi.every((t,n)=>e[n]===t)}function xt(e){let t=Bo.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Kn(e,t){if(di(e)){let n=Jn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return xt(e)}if(e[0]===255&&e[1]===216){let n=wg.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 yg(e,t){let{width:n,height:r,at:i}=t,s=Math.max(0,i.x),o=Math.max(0,i.y),a=Math.min(n,i.x+i.w),u=Math.min(r,i.y+i.h);if(a<=s||u<=o)return;let c={x:s,y:o,w:a-s,h:u-o};if(i.w===e.width&&i.h===e.height)return{part:e,box:c,dx:s-i.x,dy:o-i.y};let l={x:(s-i.x)*e.width/i.w,y:(o-i.y)*e.height/i.h,w:c.w*e.width/i.w,h:c.h*e.height/i.h};return{part:cs(e,l,c.w,c.h),box:c,dx:0,dy:0}}function Eg(e,t){let n=new Uint8Array(t.width*t.height*4),r=yg(e,t);if(r){let{part:i,box:s,dx:o,dy:a}=r;for(let u=0;u<s.h;u++){let c=((u+a)*i.width+o)*4;n.set(i.data.subarray(c,c+s.w*4),((s.y+u)*t.width+s.x)*4)}}return{width:t.width,height:t.height,data:n}}function Jo(e,t,n,r={width:e.width,height:e.height,at:{x:0,y:0,w:e.width,h:e.height}}){let i=ve(t),{width:s,height:o}=r,a=new Uint8Array(s*o*3);for(let h=0;h<s*3;h+=3)a.set(i,h);for(let h=1;h<o;h++)a.copyWithin(h*s*3,0,s*3);let u=yg(e,r);if(!u)return{width:s,height:o,data:a};let{part:c,box:l,dx:f,dy:d}=u;for(let h=0;h<l.h;h++)for(let g=0;g<l.w;g++){let b=((h+d)*c.width+g+f)*4,p=((l.y+h)*s+l.x+g)*3,m=c.data[b+3]/255*n;for(let $=0;$<3;$++)a[p+$]=Math.round(i[$]*(1-m)+c.data[b+$]*m)}return{width:s,height:o,data:a}}function Bn(e){let t=new Bo.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Bo.PNG.sync.write(t)}function pg(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function Jn(e){if(e.length<33||!di(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=pg(e,"IDAT");return{width:n,height:r,alpha:pg(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function vg(e,t=$g){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 kn(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)<$g)n++;return Math.round(n*100/(t.w*t.h))}function Mg(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=cs(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function h1(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 b=d;b<=Math.ceil(f+o-0.5);b++){let p=h1((b+0.5-f)/s),m=l*a+Math.min(e-1,Math.max(0,b))-h;c[m]=(c[m]??0)+p,g+=p}for(let b=l*a;b<(l+1)*a;b++)c[b]=(c[b]??0)/g}return{first:u,size:a,weights:c}}function Sg(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 b=c.get(f+h);if(!b)b=new Float32Array(a),s(f+h,b),c.set(f+h,b);for(let p=0;p<a;p++)u[d+p]=(u[d+p]??0)+(b[p]??0)*g}}return u}function cs(e,t,n,r){let i=Ec(e.width,t.x,t.w,n),s=e.data,o=Sg(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let f=0;f<n;f++){let d=l+(i.first[f]??0),h=f*i.size,g=0,b=0,p=0,m=0;for(let $=0;$<i.size;$++){let E=(d+$)*4,M=(i.weights[h+$]??0)*(s[E+3]??0);g+=(s[E]??0)*M,b+=(s[E+1]??0)*M,p+=(s[E+2]??0)*M,m+=M}c[f*4]=g,c[f*4+1]=b,c[f*4+2]=p,c[f*4+3]=m}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function Ig(e,t,n,r){let i=Ec(e.width,t.x,t.w,n),s=e.data,o=Sg(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let f=c+(i.first[l]??0),d=l*i.size,h=0;for(let g=0;g<i.size;g++)h+=(s[f+g]??0)*(i.weights[d+g]??0);u[l]=h}});return{width:n,height:r,data:o}}function ls(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,f)=>Math.exp(-((f-n)**2)/(2*t*t))),i=r.reduce((l,f)=>l+f,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=0;d<s;d++){let h=0;for(let g=-n;g<=n;g++)h+=(a[f+Math.min(s-1,Math.max(0,d+g))]??0)*(r[g+n]??0);u[f+d]=h/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=-n;d<=n;d++){let h=(r[d+n]??0)/i,g=Math.min(o-1,Math.max(0,l+d))*s;for(let b=0;b<s;b++)c[f+b]=(c[f+b]??0)+(u[g+b]??0)*h}}return{width:s,height:o,data:c}}function fs(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function ds(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var g1=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 m1(e){let t=4294967295;for(let n of e)t=(g1[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function jn(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE(m1(n.subarray(4,8+t.length)),8+t.length),n}function p1(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,f=s>0?e[u+c]??0:0,d=c>0&&s>0?e[u+c-1]??0:0,h=Math.abs(f-d),g=Math.abs(l-d),b=Math.abs(l+f-2*d);i[o+1+c]=(e[a+c]??0)-(h<=g&&h<=b?l:g<=b?f:d)&255}}return i}function Ng(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(fi),jn("IHDR",r),...n,jn("IDAT",bg(p1(e.data,e.width,e.height))),jn("IEND",new Uint8Array)])}function Pg(e){let[t,n,r]=ve(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return jn("PLTE",i)}function Og(e,t,n,r,i){let s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=n;let o=e*r,a=new Uint8Array(t*(o+1));for(let u=0;u<t;u++)a.set(i.subarray(u*o,(u+1)*o),u*(o+1)+1);return Buffer.concat([Buffer.from(fi),jn("IHDR",s),jn("IDAT",bg(a,{level:1})),jn("IEND",new Uint8Array)])}function qo(e){return Og(e.width,e.height,2,3,e.data)}function Rg(e){return Og(e.width,e.height,6,4,e.data)}function hs(e,t){return Ng(e,kg,[Pg(t),jn("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function vc(e){return Ng(e,0,[])}function Fg(e,t){if(!di(e)||e[25]!==kg)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(fi)],i=fi.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?Pg(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as hE,readFileSync as dm}from"node:fs";import{basename as gE,join as hm}from"node:path";/*!
71
+ `}}}}).prompt();function rc(e){let t=e.replace("#","");return[t.slice(0,2),t.slice(2,4),t.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function Xt(e){return`\x1B[38;2;${rc(e)}m`}function Wo(e,t){return`\x1B[48;2;${rc(e)};38;2;${rc(t)}m`}function ah(e,t="\x1B[39m"){return`${e.map((n)=>`${Xt(n)}■`).join(" ")}${t}`}var ss="⧉";function Uo(e,t){return t?`\x1B]8;;${t}\x1B\\${e}\x1B]8;;\x1B\\`:e}function Wk(e,t){if(e[t]!=="\x1B")return 0;if(e[t+1]==="]"){let r=e.indexOf("\x07",t+2),i=e.indexOf("\x1B\\",t+2),s=r!==-1&&(i===-1||r<i)?r+1:i!==-1?i+2:0;return s?s-t:0}if(e[t+1]!=="[")return 0;let n=t+2;while(n<e.length&&!/[@-~]/.test(e[n]))n++;return n<e.length?n-t+1:0}function uh(e,t){let n="",r=0,i=0;while(i<e.length){let s=Wk(e,i);if(s>0){n+=e.slice(i,i+s),i+=s;continue}let o=String.fromCodePoint(e.codePointAt(i)),a=$e(o);if(r+a>t)break;n+=o,r+=a,i+=o.length}return{head:n,used:r}}function rt(e,t,n=!0){if(t<=0)return"";let r=$e(e);if(r<=t)return n?e+" ".repeat(t-r):e;let{head:i,used:s}=uh(e,t-1);return`${i}${e.includes("\x1B")?"\x1B[0m":""}…${n?" ".repeat(t-1-s):""}`}function bn(e,t,n){let r=n-$e(t)-1;return r<=0?rt(e,n):`${rt(e,r)} ${t}`}function Qe(e,t){let n=[],r="";for(let i of e.split(/\s+/).filter(Boolean)){let s=r?`${r} ${i}`:i;if($e(s)<=t){r=s;continue}if(r)n.push(r);while($e(i)>t){let{head:o}=uh(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 lp,readFileSync as hl}from"node:fs";import{join as fp}from"node:path";var Uk=/^#[0-9a-f]{6}$/;function Ht(e){return Uk.test(e)}function ve(e){let t=Number.parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}function it(e,t,n){let r=ve(e),i=ve(t);return`#${r.map((s,o)=>Math.round(s+((i[o]??0)-s)*n).toString(16).padStart(2,"0")).join("")}`}function Ve(e){let[t,n,r]=ve(e).map((i)=>{let s=i/255;return s<=0.03928?s/12.92:((s+0.055)/1.055)**2.4});return 0.2126*t+0.7152*n+0.0722*r}function Ke(e,t){let n=Ve(e),r=Ve(t);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function jo(e,t){return Math.round(Ke(e,t)*100)/100}function jk(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function Be(e){let[t,n,r]=ve(e).map(jk),i=Math.cbrt(0.4122214708*t+0.5363325363*n+0.0514459929*r),s=Math.cbrt(0.2119034982*t+0.6806995451*n+0.1073969566*r),o=Math.cbrt(0.0883024619*t+0.2817188376*n+0.6299787005*r),a=1.9779984951*i-2.428592205*s+0.4505937099*o,u=0.0259040371*i+0.7827717662*s-0.808675766*o;return{l:0.2104542553*i+0.793617785*s-0.0040720468*o,c:Math.hypot(a,u),h:(Math.atan2(u,a)*180/Math.PI+360)%360}}var Ln=7,ch=3,ic=0.15,lh=1.6,oc=[1,2,3,4,5,6,9,10,11,12,13,14],fh=[7,15],Cn=[1,2,3,4,5,6],$n={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},as=0.03,jt=25,ii=15,si=0.08;function wn(e,t){let n=e.ansi[t];if(n===void 0)throw Error(`${e.name}: missing ANSI ${t}`);return n}function sc(e,t,n){let r=e.background;return t.flatMap((i)=>{let s=wn(e,i);return Ke(s,r)<n?[`ANSI ${i} ${s} on ${r} is ${jo(s,r)}:1, needs ${n}:1`]:[]})}function dh(e,t){return Math.min(...t.map((n)=>Ke(wn(e,n),e.background)))}var hh=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:Ln,measure:({foreground:e,background:t})=>Ke(e,t),check:({foreground:e,background:t})=>Ke(e,t)<Ln?[`foreground ${e} on ${t} is ${jo(e,t)}:1, needs ${Ln}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ch,measure:(e)=>dh(e,oc),check:(e)=>sc(e,oc,ch)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ic,measure:(e)=>Ve(wn(e,0)),check:(e)=>{let t=wn(e,0);return Ve(t)>ic?[`ANSI 0 ${t} has luminance ${Ve(t).toFixed(3)}, needs <= ${ic}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:Ln,measure:(e)=>dh(e,fh),check:(e)=>sc(e,fh,Ln)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:lh,measure:(e)=>Ke(wn(e,8),e.background),check:(e)=>sc(e,[8],lh)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:Ln,measure:({foreground:e,selectionBackground:t})=>t===void 0?Number.NaN:Ke(e,t),check:({foreground:e,selectionBackground:t})=>t!==void 0&&Ke(e,t)<Ln?[`foreground ${e} on selection ${t} is ${jo(e,t)}:1, needs ${Ln}:1`]:[]}];function Dt(e,t){let n=Math.abs(e-t)%360;return Math.min(n,360-n)}var _n=(e)=>e>8?e-8:e;function oi(e){let t=e.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(t.flatMap((n)=>Cn.includes(_n(n))?[n,n>8?n-8:n+8]:[n]))}function os(e,t){let n=Be(wn(e,t));return n.c<as?void 0:n}function ri(e){let t=oi(e);return oc.flatMap((n)=>{let r=os(e,n),i=$n[_n(n)];if(r===void 0||i===void 0||t.has(n))return[];let s=Dt(r.h,i.center)-i.width;return s>0?[{slot:n,hue:r.h,over:s}]:[]})}function Mr(e){let t=new Set(e.signatureSlots);return Cn.flatMap((n)=>{let r=os(e,n),i=os(e,n+8);if(r===void 0||i===void 0||t.has(`ansi${n}`)&&t.has(`ansi${n+8}`))return[];return[{normal:n,gap:Dt(r.h,i.h)}]})}function Sr(e){let t=oi(e);return[0,8].flatMap((n)=>Cn.flatMap((r)=>Cn.filter((i)=>i>r).flatMap((i)=>{let[s,o]=[n+r,n+i],a=os(e,s),u=os(e,o);if(a===void 0||u===void 0||t.has(s)&&t.has(o))return[];return Dt(a.h,u.h)<ii&&Math.abs(a.l-u.l)<si?[[s,o]]:[]})))}var Kk=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(e)=>Math.max(0,...ri(e).map((t)=>t.over)),check:(e)=>ri(e).map(({slot:t,hue:n,over:r})=>{let i=$n[_n(t)];return`ANSI ${t} ${wn(e,t)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:jt,measure:(e)=>Math.max(0,...Mr(e).map((t)=>t.gap)),check:(e)=>Mr(e).filter((t)=>t.gap>jt).map(({normal:t,gap:n})=>`ANSI ${t+8} is ${n.toFixed(0)}° from ANSI ${t}, needs <= ${jt}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(e)=>Sr(e).length,check:(e)=>Sr(e).map(([t,n])=>`ANSI ${t} ${wn(e,t)} and ANSI ${n} ${wn(e,n)} are within ${ii}° hue and ${si} lightness`)}],Ko=[...hh,...Kk],ac=Ko.map((e)=>e.rule),bt=Ko.map(({rule:e,label:t,unit:n,min:r,max:i})=>({rule:e,label:t,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Gn(e){return Ko.map((t)=>Math.round(t.measure(e)*1000)/1000)}function gh(e,t){return e.filter((n)=>!t.waive.includes(n.rule)).flatMap((n)=>n.check(t).map((r)=>({theme:t.name,rule:n.rule,detail:r})))}function Ir(e){return gh(Ko,e)}function mh(e){return gh(hh,e)}function ph(e){return e.flatMap(Ir)}import{chmodSync as Bk,copyFileSync as Jk,existsSync as ai,mkdirSync as qk,readFileSync as uc,realpathSync as zk,renameSync as Vk,rmSync as bh,statSync as Yk,writeFileSync as Qk}from"node:fs";import{dirname as Zk}from"node:path";function wh(e){return`${e}.ttheme.bak`}var Xk=/^(?:#|--) ttheme begin$|path = "ttheme-|^DefaultProfile=ttheme-/m;function cc(e){let t=wh(e);if(ai(e)&&!ai(t)&&!Xk.test(uc(e,"utf8")))Jk(e,t)}function K(e,t){let n=ai(e)?zk(e):e;qk(Zk(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(Qk(r,t),ai(n))Bk(r,Yk(n).mode&4095);Vk(r,n)}function en(e,t){if((ai(e)?uc(e,"utf8"):void 0)===t)return!1;return cc(e),K(e,t),!0}function $h(e,t){let n=wh(e),r=ai(n)?uc(n,"utf8"):void 0;if(t===""&&r===void 0)return bh(e,{force:!0}),"removed";if(K(e,t),r===void 0||r===t)return bh(n,{force:!0}),"restored";return"kept backup"}import{createHash as Pm}from"node:crypto";import{copyFileSync as RE,existsSync as Vc,mkdirSync as OE,readdirSync as FE,readFileSync as da,renameSync as Rm,rmSync as ki}from"node:fs";import{basename as Om,isAbsolute as TE,join as D}from"node:path";var yg=To(Ih(),1),Jo=To(wg(),1);import{deflateSync as kg}from"node:zlib";var fi=[137,80,78,71,13,10,26,10],Eg=13,vg=3;function di(e){return e.length>=fi.length&&fi.every((t,n)=>e[n]===t)}function At(e){let t=Jo.PNG.sync.read(Buffer.from(e));return{width:t.width,height:t.height,data:new Uint8Array(t.data)}}function Kn(e,t){if(di(e)){let n=Jn(e);if(n&&n.width*n.height>t)throw Error(`${n.width}×${n.height} is over ${t/1e6} megapixels`);return At(e)}if(e[0]===255&&e[1]===216){let n=yg.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 Mg(e,t){let{width:n,height:r,at:i}=t,s=Math.max(0,i.x),o=Math.max(0,i.y),a=Math.min(n,i.x+i.w),u=Math.min(r,i.y+i.h);if(a<=s||u<=o)return;let c={x:s,y:o,w:a-s,h:u-o};if(i.w===e.width&&i.h===e.height)return{part:e,box:c,dx:s-i.x,dy:o-i.y};let l={x:(s-i.x)*e.width/i.w,y:(o-i.y)*e.height/i.h,w:c.w*e.width/i.w,h:c.h*e.height/i.h};return{part:cs(e,l,c.w,c.h),box:c,dx:0,dy:0}}function Sg(e,t){let n=new Uint8Array(t.width*t.height*4),r=Mg(e,t);if(r){let{part:i,box:s,dx:o,dy:a}=r;for(let u=0;u<s.h;u++){let c=((u+a)*i.width+o)*4;n.set(i.data.subarray(c,c+s.w*4),((s.y+u)*t.width+s.x)*4)}}return{width:t.width,height:t.height,data:n}}function qo(e,t,n,r={width:e.width,height:e.height,at:{x:0,y:0,w:e.width,h:e.height}}){let i=ve(t),{width:s,height:o}=r,a=new Uint8Array(s*o*3);for(let h=0;h<s*3;h+=3)a.set(i,h);for(let h=1;h<o;h++)a.copyWithin(h*s*3,0,s*3);let u=Mg(e,r);if(!u)return{width:s,height:o,data:a};let{part:c,box:l,dx:f,dy:d}=u;for(let h=0;h<l.h;h++)for(let g=0;g<l.w;g++){let b=((h+d)*c.width+g+f)*4,p=((l.y+h)*s+l.x+g)*3,m=c.data[b+3]/255*n;for(let $=0;$<3;$++)a[p+$]=Math.round(i[$]*(1-m)+c.data[b+$]*m)}return{width:s,height:o,data:a}}function Bn(e){let t=new Jo.PNG({width:e.width,height:e.height});return t.data=Buffer.from(e.data),Jo.PNG.sync.write(t)}function $g(e,t){for(let n=0;n+t.length<=e.length;n++){let r=!0;for(let i=0;i<t.length&&r;i++)r=e[n+i]===t.charCodeAt(i);if(r)return n}return-1}function Jn(e){if(e.length<33||!di(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=$g(e,"IDAT");return{width:n,height:r,alpha:$g(i===-1?e:e.subarray(0,i),"tRNS")!==-1}}function Ig(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 kn(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 Ng(e,t,n){let r=Math.min(t/e.width,n/e.height),i=Math.max(1,Math.round(e.width*r)),s=Math.max(1,Math.round(e.height*r)),o=cs(e,{x:0,y:0,w:e.width,h:e.height},i,s),a=new Uint8Array(t*n*4),u=Math.floor((t-i)/2),c=Math.floor((n-s)/2);for(let l=0;l<s;l++)a.set(o.data.subarray(l*i*4,(l+1)*i*4),((c+l)*t+u)*4);return{width:t,height:n,data:a}}function b1(e){let t=Math.abs(e);if(t<1)return(7*t*t*t-12*t*t+5.333333333333333)/6;if(t<2)return(-2.3333333333333335*t*t*t+12*t*t-20*t+10.666666666666666)/6;return 0}function Sc(e,t,n,r){if(n===r&&Number.isInteger(t)&&t>=0&&t+r<=e)return{first:Int32Array.from({length:r},(l,f)=>t+f),size:1,weights:new Float32Array(r).fill(1)};let i=n/r,s=Math.max(1,i),o=2*s,a=Math.min(e,Math.ceil(2*o)+2),u=new Int32Array(r),c=new Float32Array(r*a);for(let l=0;l<r;l++){let f=t+(l+0.5)*i,d=Math.floor(f-o-0.5),h=Math.max(0,Math.min(e-a,d));u[l]=h;let g=0;for(let b=d;b<=Math.ceil(f+o-0.5);b++){let p=b1((b+0.5-f)/s),m=l*a+Math.min(e-1,Math.max(0,b))-h;c[m]=(c[m]??0)+p,g+=p}for(let b=l*a;b<(l+1)*a;b++)c[b]=(c[b]??0)/g}return{first:u,size:a,weights:c}}function Pg(e,t,n,r,i,s){let o=Sc(e,t.y,t.h,r),a=n*i,u=new Float32Array(a*r),c=new Map;for(let l=0;l<r;l++){let f=o.first[l]??0;for(let h of c.keys())if(h<f)c.delete(h);let d=l*a;for(let h=0;h<o.size;h++){let g=o.weights[l*o.size+h]??0;if(g===0)continue;let b=c.get(f+h);if(!b)b=new Float32Array(a),s(f+h,b),c.set(f+h,b);for(let p=0;p<a;p++)u[d+p]=(u[d+p]??0)+(b[p]??0)*g}}return u}function cs(e,t,n,r){let i=Sc(e.width,t.x,t.w,n),s=e.data,o=Pg(e.height,t,n,r,4,(u,c)=>{let l=u*e.width;for(let f=0;f<n;f++){let d=l+(i.first[f]??0),h=f*i.size,g=0,b=0,p=0,m=0;for(let $=0;$<i.size;$++){let E=(d+$)*4,M=(i.weights[h+$]??0)*(s[E+3]??0);g+=(s[E]??0)*M,b+=(s[E+1]??0)*M,p+=(s[E+2]??0)*M,m+=M}c[f*4]=g,c[f*4+1]=b,c[f*4+2]=p,c[f*4+3]=m}}),a=new Uint8Array(n*r*4);for(let u=0;u<n*r;u++){let c=o[u*4+3]??0;if(c<=0)continue;for(let l=0;l<3;l++)a[u*4+l]=Math.min(255,Math.max(0,Math.round((o[u*4+l]??0)/c)));a[u*4+3]=Math.min(255,Math.round(c))}return{width:n,height:r,data:a}}function Rg(e,t,n,r){let i=Sc(e.width,t.x,t.w,n),s=e.data,o=Pg(e.height,t,n,r,1,(a,u)=>{let c=a*e.width;for(let l=0;l<n;l++){let f=c+(i.first[l]??0),d=l*i.size,h=0;for(let g=0;g<i.size;g++)h+=(s[f+g]??0)*(i.weights[d+g]??0);u[l]=h}});return{width:n,height:r,data:o}}function ls(e,t){if(t<=0)return e;let n=Math.max(1,Math.ceil(t*3)),r=Array.from({length:2*n+1},(l,f)=>Math.exp(-((f-n)**2)/(2*t*t))),i=r.reduce((l,f)=>l+f,0),{width:s,height:o,data:a}=e,u=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=0;d<s;d++){let h=0;for(let g=-n;g<=n;g++)h+=(a[f+Math.min(s-1,Math.max(0,d+g))]??0)*(r[g+n]??0);u[f+d]=h/i}}let c=new Float32Array(s*o);for(let l=0;l<o;l++){let f=l*s;for(let d=-n;d<=n;d++){let h=(r[d+n]??0)/i,g=Math.min(o-1,Math.max(0,l+d))*s;for(let b=0;b<s;b++)c[f+b]=(c[f+b]??0)+(u[g+b]??0)*h}}return{width:s,height:o,data:c}}function fs(e){let t=new Uint8Array(e.data.length);for(let n=0;n<t.length;n++)t[n]=Math.min(255,Math.max(0,Math.round(e.data[n]??0)));return{width:e.width,height:e.height,data:t}}function ds(e){let t=new Uint8Array(e.width*e.height);for(let n=0;n<t.length;n++)t[n]=e.data[n*4+3]??0;return{width:e.width,height:e.height,data:t}}var w1=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function $1(e){let t=4294967295;for(let n of e)t=(w1[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function jn(e,t){let n=Buffer.alloc(12+t.length);return n.writeUInt32BE(t.length,0),n.write(e,4,"latin1"),n.set(t,8),n.writeUInt32BE($1(n.subarray(4,8+t.length)),8+t.length),n}function k1(e,t,n){let r=t+1,i=new Uint8Array(n*r);for(let s=0;s<n;s++){let o=s*r,a=s*t,u=a-t;i[o]=4;for(let c=0;c<t;c++){let l=c>0?e[a+c-1]??0:0,f=s>0?e[u+c]??0:0,d=c>0&&s>0?e[u+c-1]??0:0,h=Math.abs(f-d),g=Math.abs(l-d),b=Math.abs(l+f-2*d);i[o+1+c]=(e[a+c]??0)-(h<=g&&h<=b?l:g<=b?f:d)&255}}return i}function 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(fi),jn("IHDR",r),...n,jn("IDAT",kg(k1(e.data,e.width,e.height))),jn("IEND",new Uint8Array)])}function Fg(e){let[t,n,r]=ve(e),i=new Uint8Array(768);for(let s=0;s<256;s++)i.set([t,n,r],s*3);return jn("PLTE",i)}function Tg(e,t,n,r,i){let s=Buffer.alloc(13);s.writeUInt32BE(e,0),s.writeUInt32BE(t,4),s[8]=8,s[9]=n;let o=e*r,a=new Uint8Array(t*(o+1));for(let u=0;u<t;u++)a.set(i.subarray(u*o,(u+1)*o),u*(o+1)+1);return Buffer.concat([Buffer.from(fi),jn("IHDR",s),jn("IDAT",kg(a,{level:1})),jn("IEND",new Uint8Array)])}function zo(e){return Tg(e.width,e.height,2,3,e.data)}function Hg(e){return Tg(e.width,e.height,6,4,e.data)}function hs(e,t){return Og(e,vg,[Fg(t),jn("tRNS",Uint8Array.from({length:256},(n,r)=>r))])}function Ic(e){return Og(e,0,[])}function xg(e,t){if(!di(e)||e[25]!==vg)return;let n=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=[Buffer.from(fi)],i=fi.length;while(i+8<=n.length){let s=i+12+n.readUInt32BE(i);r.push(n.toString("latin1",i+4,i+8)==="PLTE"?Fg(t):n.subarray(i,s)),i=s}return Buffer.concat(r)}import{readdirSync as bE,readFileSync as mm}from"node:fs";import{basename as wE,join as pm}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 b1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function w1(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 y1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function E1(e,t,n){let r=e.split(/\r?\n/),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];if(!a)continue;if(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
98
98
  `,o===t)i+=" ".repeat(s+n+2),i+=`^
99
- `}return i}class B extends Error{line;column;codeblock;constructor(e,t){let[n,r]=b1(t.toml,t.ptr),i=w1(t.toml,n,r);super(`Invalid TOML document: ${e}
99
+ `}return i}class B extends Error{line;column;codeblock;constructor(e,t){let[n,r]=y1(t.toml,t.ptr),i=E1(t.toml,n,r);super(`Invalid TOML document: ${e}
100
100
 
101
101
  ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(e,{toml:t.s,ptr:n??t.p})}}/*!
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 B(
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 zo(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)B.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,f=n===120?2:n===117?4:8;for(let d=0;d<f;d++,e.p++){let h=e.s.charCodeAt(e.p),g=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;if(g<0)B.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)B.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
127
+ */function Vo(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,s=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);if(s){if((n=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(n===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let o="",a=e.p,u=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),s&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))u=u&&3;else if(n<32&&n!==9||n===127)B.x("control characters are not allowed in strings",e);else if((!u||u===3)&&n===r&&(!s||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(s){if(e.s.charCodeAt(e.p+3)===r)e.p++;if(e.s.charCodeAt(e.p+3)===r)e.p++}if(!u){let c=e.s.slice(a,e.p);o=o?o+c:c}return e.p+=s?3:1,o}else if(!u){if(!i&&n===92)o+=e.s.slice(a,a=e.p),u=1}else if(u===1)if(n===120||n===117||n===85){let c=e.p++-1,l=0,f=n===120?2:n===117?4:8;for(let d=0;d<f;d++,e.p++){let h=e.s.charCodeAt(e.p),g=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;if(g<0)B.x("invalid non-hex character in unicode escape",e);l=l<<4|g}if(l<0||l>1114111||l>=55296&&l<=57343)B.x("invalid unicode escape",e,c);o+=String.fromCodePoint(l),a=e.p--,u=0}else if(s&&(n===32||n===9))u=2;else{if(n===98)o+="\b";else if(n===116)o+="\t";else if(n===110)o+=`
128
128
  `;else if(n===102)o+="\f";else if(n===114)o+="\r";else if(n===101)o+="\x1B";else if(n===34)o+='"';else if(n===92)o+="\\";else B.x("unrecognised escape sequence",e);a=e.p+1,u=0}else if(n!==32&&n!==9){if(u===2)B.x("invalid escape: only line-ending whitespace may be escaped",e,a);u=!i&&n===92?1:0,a=e.p}B.x("unfinished string",e,t)}/*!
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 B(
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 $1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class qn extends Date{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match($1);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new qn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new qn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new qn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new qn(e);return t.#t=!1,t.#e=null,t}}/*!
154
+ */var v1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class qn extends Date{#t=!1;#n=!1;#e=null;constructor(e,t,n){let r=!0,i=!0,s="Z",o;if(typeof e==="string")if(t)e:{if(t<3){if(+e.slice(11,13)>23){e="";break e}if(t===2)s=null,e+="Z";else if((o=e.charCodeAt(e.length-1))!==90&&o!==122)s=e.slice(e.length-6);if(n)e=e.slice(0,10)+"T"+e.slice(11)}else if(t===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;r=t!==4,i=t!==3}else{let a=e.match(v1);if(a){if(!a[1])r=!1,e=`0000-01-01T${e}`;if(i=!!a[2],i&&e[10]===" "&&(e=e.replace(" ","T")),a[2]&&+a[2]>23)e="";else if(s=a[3]||null,!s&&i)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#t=r,this.#n=i,this.#e=s}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let t=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return t=this.#e[0]==="-"?t:-t,new Date(this.getTime()-t*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,t="Z"){let n=new qn(e);return n.#e=t,n}static wrapAsLocalDateTime(e){let t=new qn(e);return t.#e=null,t}static wrapAsLocalDate(e){let t=new qn(e);return t.#n=!1,t.#e=null,t}static wrapAsLocalTime(e){let t=new qn(e);return t.#t=!1,t.#e=null,t}}/*!
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 B(
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 wt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Sc(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function ms(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||B.x("document contains excessively nested structures. aborting.",e);let i=r===91?xg(e):Tg(e);return e.d++,i}if(r===34||r===39)return zo(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)B.x("invalid value",e,n);return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)B.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Yo(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 k1(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return y1(e,r,t);return Yo(e,e.p,r,0,t)}function Yo(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)B.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)B.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||Sc(s=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(s===120)return Mc(e,t,16,i);else if(s===98)return Mc(e,t,2,i);else if(s===111)return Mc(e,t,8,i)}if(s===46)o=2;else if(s===101||s===69)o=4;else B.x("illegal leading zero",e,t)}else if(!wt(s))B.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!Sc(s,i))){if(!o)o=1;if(s===95){if(!(o&1))B.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!wt(s))B.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))B.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):Hg(e,u,10,t)}function Mc(e,t,n,r){let i,s=1;while(++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Sc(i,r)))if(i===95){if(s&1)B.x("illegal underscore",e);s=3}else if(!wt(i,n))B.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)B.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return Hg(e,o,n,t)}function Hg(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;B.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function k1(e,t,n){let r=e.p++,i;if(!wt(t)||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++)))return Yo(e,e.p=r,t,0,n);if(e.p+=5,!wt(e.s.charCodeAt(e.p++)))B.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!wt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return gs(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)B.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(wt(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return gs(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return gs(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return gs(e,s,2,i,r)}function y1(e,t,n){let r=e.p;if(!wt(t)||!wt(e.s.charCodeAt(++e.p)))return Yo(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(wt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return gs(e,i,4,!1,r)}function gs(e,t,n,r,i,s){if(e.ld){let o=new qn(t,n,r);if(!o.isValid())B.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){B.x(o instanceof Error?o.message:""+o,e,i)}}/*!
180
+ */function wt(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Pc(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function ms(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||B.x("document contains excessively nested structures. aborting.",e);let i=r===91?Cg(e):Lg(e);return e.d++,i}if(r===34||r===39)return Vo(e);if(r===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)B.x("invalid value",e,n);return e.p++,!0}if(r===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)B.x("invalid value",e,n);return e.p++,!1}if(r===43||r===45)return Yo(e,e.p,e.s.charCodeAt(++e.p),44-r,t);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return M1(e,r,t);if(e.s.charCodeAt(e.p+2)===58)return S1(e,r,t);return Yo(e,e.p,r,0,t)}function Yo(e,t,n,r,i){let s=n,o=0,a=!1;if(s===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)B.x("invalid value",e,t);return e.p++,(r||1)/0}if(s===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)B.x("invalid value",e,t);return e.p++,NaN}if(s===48){if(++e.p>=e.s.length||Pc(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 B.x("illegal leading zero",e,t)}else if(!wt(s))B.x("invalid value",e,t);while(++e.p<e.s.length&&(s=e.s.charCodeAt(e.p),!Pc(s,i))){if(!o)o=1;if(s===95){if(!(o&1))B.x("illegal underscore",e);o+=11,a=!0}else if(o===1&&s===46)o=2;else if((o===1||o===3)&&(s===101||s===69))o=4;else if(o===4&&(s===43||s===45));else if(!wt(s))B.x("illegal character in numeric literal",e);else if(o>9)o-=11;else if(!(o&1))o++}if(!o){let c=(n-48)*(r||1);return e.bi===!0?BigInt(c):c}if(!(o&1))B.x("unfinished numeric value",e,t);let u=e.s.slice(t,e.p);if(a)u=u.replaceAll("_","");return o>1?parseFloat(u):Ag(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),!Pc(i,r)))if(i===95){if(s&1)B.x("illegal underscore",e);s=3}else if(!wt(i,n))B.x("illegal character in numeric literal",e);else if(s&1)s--;if(s&1)B.x("unfinished numeric value",e);let o=e.s.slice(t+2,e.p);if(s)o=o.replaceAll("_","");return Ag(e,o,n,t)}function Ag(e,t,n,r){if(e.bi!==!0)e:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break e;B.x("integer value cannot be represented losslessly",e,r)}return i}return n===10?BigInt(t):BigInt((n===2?"0b":n===8?"0o":"0x")+t)}function M1(e,t,n){let r=e.p++,i;if(!wt(t)||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++))||!wt(e.s.charCodeAt(e.p++)))return Yo(e,e.p=r,t,0,n);if(e.p+=5,!wt(e.s.charCodeAt(e.p++)))B.x("invalid date-time: date part is malformed",e,r);if(e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!wt(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116){let o=e.s.slice(r,e.p);return gs(e,o,3,!1,r)}if(e.s.charCodeAt(e.p+=3)!==58)B.x("invalid date-time: time part is malformed",e,r);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(wt(e.s.charCodeAt(++e.p)));if(t=e.s.charCodeAt(e.p)){if(t===90||t===122){let o=e.s.slice(r,++e.p);return gs(e,o,1,i,r,"[+00:00]")}if(t===43||t===45){let o=e.s.slice(r,e.p+=6);return gs(e,o,1,i,r,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let s=e.s.slice(r,e.p);return gs(e,s,2,i,r)}function S1(e,t,n){let r=e.p;if(!wt(t)||!wt(e.s.charCodeAt(++e.p)))return Yo(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(wt(e.s.charCodeAt(++e.p)));let i=e.s.slice(r,e.p);return gs(e,i,4,!1,r)}function gs(e,t,n,r,i,s){if(e.ld){let o=new qn(t,n,r);if(!o.isValid())B.x("invalid date",e,i);return o}try{if(s)t+=s;switch(n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(o){B.x(o instanceof Error?o.message:""+o,e,i)}}/*!
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 B(
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 E1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)B.x("control characters are not allowed in comments",e)}}function Kt(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;E1(e)}}/*!
206
+ */function I1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)B.x("control characters are not allowed in comments",e)}}function Bt(e,t,n){let r;while(e.p<e.s.length){while(e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(n||r!==35)break;I1(e)}}/*!
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 B(
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 Qo(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)B.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)B.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))B.x("illegal quoted key: multiline strings are not allowed",e);i.push(zo(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)B.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));B.x("incomplete key-value: cannot find end of key",e,n)}function Tg(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Kt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Qo(e);for(let f=0;f<c.length;f++){if(f)o=a?o[s]:o[s]=Object.create(null);if(s=c[f],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))B.x("trying to redefine an already defined value",e,u);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&B.x("document contains an unsafe property",e,u);break}if(!a&&d)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)B.x("trying to redefine an already defined value",e,u);Kt(e,!0,!0);let l=ms(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Kt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished table",e,t)}function xg(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Kt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(ms(e,93)),Kt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished array",e,t)}/*!
232
+ */function Qo(e,t=61){let n,r=0,i=[],s,o=e.s.charCodeAt(n=e.p);do if(o===t){if(!r)B.x("unexpected end of key",e);if(r===1)i.push(e.s.slice(s,e.p));return e.p++,i}else if(o===46){if(!r)B.x("illegal empty bare key",e);if(r===1)i.push(e.s.slice(s,e.p));r=0}else if(!r&&(o===34||o===39)){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))B.x("illegal quoted key: multiline strings are not allowed",e);i.push(Vo(e)),r=2,e.p--}else if(o===32||o===9){if(r===1)i.push(e.s.slice(s,e.p)),r=2}else if(r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122)B.x("illegal character in key",e);else if(!r)r=1,s=e.p;while(o=e.s.charCodeAt(++e.p));B.x("incomplete key-value: cannot find end of key",e,n)}function Lg(e){let t=e.p++,n=Object.create(null),r=new Set,i;while(e.p<e.s.length){if(Bt(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let s,o=n,a=!1,u=e.p,c=Qo(e);for(let f=0;f<c.length;f++){if(f)o=a?o[s]:o[s]=Object.create(null);if(s=c[f],(a=Object.hasOwn(o,s))&&(typeof o[s]!=="object"||r.has(o[s])))B.x("trying to redefine an already defined value",e,u);let d=s==="__proto__";if(e.uk&&(d||s==="constructor")){o=e.uk!==1&&B.x("document contains an unsafe property",e,u);break}if(!a&&d)Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})}if(a)B.x("trying to redefine an already defined value",e,u);Bt(e,!0,!0);let l=ms(e,125);if(o&&typeof(o[s]=l)==="object")r.add(l);if(Bt(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished table",e,t)}function Cg(e){let t=e.p++,n=[],r;while(e.p<e.s.length){if(Bt(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(ms(e,93)),Bt(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)B.x("expected comma or end of structure",e,e.p-1)}B.x("unfinished array",e,t)}/*!
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 B(
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 Ag(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 Lg(e,t,n){if(t===null||e.uk===2)B.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function 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++;Kt(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=Qo(n,93);if(c){if(e.charCodeAt(n.p)!==93)B.x("expected end of table array declaration",n);n.p++}let f=Ag(n,l,r,i,c?2:1);if(!f)Lg(n,f,s),o=!0;else u=f[2],a=f[1]}else{s=n.p;let c=Qo(n),l=Ag(n,c,a,u,0);if(!l&&!o)Lg(n,l,s);Kt(n,!0,!0);let f=ms(n,void 0);if(l&&!o)l[1][l[0]]=f}if(Kt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))B.x("each key-value declaration must be followed by an end-of-line",n);Kt(n)}return r}/*!
258
+ */function _g(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 Gg(e,t,n){if(t===null||e.uk===2)B.x(t===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,n)}function Rc(e,t={}){let n={s:e,p:0,d:t.maxDepth??1000,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour==="throw"?2:t.unsafeKeyBehaviour==="drop"?1:0},r=Object.create(null),i=Object.create(null),s,o=!1,a=r,u=i;if(e.charCodeAt(0)===65279)n.p++;Bt(n);while(n.p<e.length){if(e.charCodeAt(n.p)===91){let c=e.charCodeAt(++n.p)===91;s=n.p+=+c,o=!1;let l=Qo(n,93);if(c){if(e.charCodeAt(n.p)!==93)B.x("expected end of table array declaration",n);n.p++}let f=_g(n,l,r,i,c?2:1);if(!f)Gg(n,f,s),o=!0;else u=f[2],a=f[1]}else{s=n.p;let c=Qo(n),l=_g(n,c,a,u,0);if(!l&&!o)Gg(n,l,s);Bt(n,!0,!0);let f=ms(n,void 0);if(l&&!o)l[1][l[0]]=f}if(Bt(n,!0),n.p<e.length&&(s=e.charCodeAt(n.p))!==10&&(s!==13||e.charCodeAt(n.p+1)!==10))B.x("each key-value declaration must be followed by an end-of-line",n);Bt(n)}return r}/*!
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 B(
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 yR=!!"".isWellFormed;/*!
284
+ */var CO=!!"".isWellFormed;/*!
285
285
  * Copyright (c) Squirrel Chat et al., All rights reserved.
286
286
  * SPDX-License-Identifier: BSD-3-Clause
287
287
  *
@@ -307,92 +307,92 @@ ${i}`,t);this.line=n,this.column=r,this.codeblock=i}static x(e,t,n){throw new B(
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 v1,rmSync as M1,statSync as S1}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as I1}from"node:net";import{homedir as N1}from"node:os";import{join as bs}from"node:path";import{setTimeout as P1}from"node:timers/promises";var zn=100,$t=25000000,O1=536870912,hi=["safe","questionable","explicit"],Pr=["nudity","underwear"],Rc=["comic","monochrome","sketch","chibi"],Jg=["off","5","10","25","50","100"],qg=["off","720","1080","1440","1800","2560"],zg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},R1={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},F1=/^(?:rating|score|width|height|filetype|dimension):/,ps={safe:"s",questionable:"q",explicit:"e"},Yg=8191,H1=20000,T1=5000,Cg=3000,_g=8,x1=3000,Qg=60000,Gg=3,A1=3,L1="https://static.zerochan.net",Vg="https://s1.zerochan.net",Fc=`ttheme/${ot.version} (+${ot.homepage})`,C1=["orig","tile","thumb","cut"],Zg=new Map,_1=tE(process.env.TTHEME_FIND_HOSTS),G1=eE(process.env.TTHEME_FIND_CUTOUTS);I1(x1);var W1=["artist","character","copyright"];function Wg(e){try{return v1(e)}catch{return[]}}function gi(e){return e.startsWith("//")?`https:${e}`:e}function Qn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function ws(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function U1(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function Pc(e,t,n){let r=gi(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Qn(r)}}function yn(e){return String(e??"").split(/\s+/).filter(Boolean)}function Oc(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 Xg(e,t){let n=gi(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:yn(t.tags),named:t.named,...Oc(e.created_at)?{posted:Oc(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 j1(e){let t=U1(e);return ws(e).flatMap((n)=>{let r=gi(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>yn(i).filter((a)=>t.get(a)===o);return Xg(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Qn(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:s("artist"),character:s("character"),copyright:s("copyright")},solo:void 0,versions:[Pc(n.jpeg_url,n.jpeg_width,n.jpeg_height),Pc(n.sample_url,n.sample_width,n.sample_height)]})})}function K1(e){return ws(e).flatMap((t)=>{let n=gi(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return Xg(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Qn(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:yn(t.tag_string_artist),character:yn(t.tag_string_character),copyright:yn(t.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>Pc(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 Dg(e){return e.toLowerCase().replace(/\s+/g,"_")}function B1(e){return(Array.isArray(e)?e:[]).map((t)=>Dg(String(t)))}function J1(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function q1(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=B1(i.tags),a=gi(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Qn(a),preview:`${Vg}/${J1(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>zg.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,named:{artist:[],character:[],copyright:[]},solo:o.includes("solo"),family:0,smaller:[]}]})}var z1={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function Ug(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 Y1(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=z1[r],o=Dg(Ug(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=Oc(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:Ug(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function Q1(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function V1(e){return ws(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function Z1(e){return ws(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function X1(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function D1(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function eE(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 tE(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 Vo(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 Rr(e){return Vo(e,hi,["safe"])}function mi(e){return Vo(e,Pr,Pr,"none")}function Zo(e){return Vo(e,Rc,[],"none")}function $s(e){let t=X.map((n)=>n.name);return Vo(e,t,t)}function Hc(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function ks(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function Tc(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function xc(e){let t=_1.get(e.key),n=G1.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 em(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function tm(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function jg(e){let t=xc(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}`]:[],...tm(i)],cutouts:em(t.cutouts),ratings:Tc([ps.safe],[ps.questionable],[ps.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ps[i]}`;let s=hi.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${ps[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(zn),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:j1,count:X1,uploadedBy:(r)=>`user:${r}`}}function nE(e){let t=xc(e),n=Tc(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...tm(i),...s?["filetype:png"]:[]],cutouts:em(t.cutouts),ratings:n,rate:(r)=>r.length===hi.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(zn),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:K1,count:D1,uploadedBy:(r)=>`user:${r}`}}function Nc(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 rE(e){let t=xc(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:Tc(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${Nc(n)}?${new URLSearchParams({json:"",l:String(zn),p:String(r+1),...Kg(n)})}`,countUrl:(n)=>`${t.origin}/${Nc(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:q1,count:Q1,credits:Y1,counts:(n)=>Nc(n).split(",").length===1&&!("d"in Kg(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Vg,L1).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function iE(e){let t=Bg(`https://${e}`);return X.find((n)=>Bg(n.origin)===t)}function Ac(e){return e.split(/\s+/).filter((t)=>t&&!F1.test(t)).length}function Xo(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=iE(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=[nE({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),jg({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),jg({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),rE({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],At=X.find((e)=>e.key==="danbooru"),Vn=134217728;function Lt(e,t){let n=X.indexOf(e);return(n===-1?X.length:n)*Vn+t}function Bg(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function pi(e,t,n=t){return t.mirror&&n===t?{site:At,url:t.mirror.file}:{site:e,url:n.file}}function Do(e,t){return t.mirror?{site:At,url:t.mirror.preview}:{site:e,url:t.preview}}function ea(e,t=Pr){return e.tags.filter((n)=>t.some((r)=>zg[r].has(n)))}function nm(e,t){return e.tags.filter((n)=>t.some((r)=>R1[r].has(n)))}function ta(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function rm(e,t){return e.rate(["safe"])===""?void 0:hi.find((n)=>e.ratings[n].has(t.rating))}function nn(e){return[e,...e.smaller].find((t)=>t.width*t.height<=$t)}function im(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 bi(){return bs(process.env.XDG_CACHE_HOME??bs(N1(),".cache"),"ttheme")}function rn(e){return bs(bi(),e.key)}function sm(e=O1,t=bi()){let n=[],r=0;for(let i of Wg(t))for(let s of C1){let o=bs(t,i,s);for(let a of Wg(o)){let u=bs(o,a);try{let{size:c,mtimeMs:l}=S1(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{M1(i.path,{force:!0}),r-=i.size}catch{}}}function sE(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)?Qg:Math.max(0,n-t)}function Yn(e){return Zg.get(e.key)??0}function oE(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function aE(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function uE(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Or(e,t,n,r={},i=H1){let s=t;for(let o=1,a=0;;o++){let u=Yn(e)-Date.now();if(u>0)await P1(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":Fc,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(o<Gg&&!n.aborted&&oE(f))continue;throw f}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<A1){await c.body?.cancel(),s=uE(s,l),a++,o--;continue}if(c.status===429&&o<Gg){await c.body?.cancel();let f=sE(c.headers.get("retry-after"),Date.now());if(f>Qg)throw Error(`${e.name} asks to wait ${Math.ceil(f/1000)}s`);Zg.set(e.key,Math.max(Yn(e),Date.now()+f));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(aE(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function na(e,t,n){try{return await(await Or(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function om(e,t,n,r){return e.parse(await na(e,e.postsUrl(t,n),r))}async function Lc(e,t,n){return e.count(await na(e,e.countUrl(t),n))}async function ys(e,t,n){let[r]=e.parse(await na(e,e.postUrl(t),n));return r}async function ra(e,t,n){return e.credits?.(await na(e,e.pageUrl(t),n))}var cE=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,lE=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function Es(e){let t=cE.exec(e)?.[1]??lE.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function ia(e,t){return e.credits!==void 0&&t.named.artist.length===0}function vs(e,t){for(let n of W1){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 fE(e){let t=new URLSearchParams({limit:String(2*zn),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${At.origin}/posts.json?${t}`}function dE(e){return new Map(ws(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:yn(t.tag_string),named:{artist:yn(t.tag_string_artist),character:yn(t.tag_string_character),copyright:yn(t.tag_string_copyright)},source:String(t.source??""),file:gi(String(t.file_url??""))}]]:[]}))}function sa(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],vs(n,r),n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=Qn(r.file)}}}async function oa(e,t){let n=new Map;if(Yn(At)>Date.now())return n;for(let r=0;r<e.length;r+=zn){let i=await(await Or(At,fE(e.slice(r,r+zn)),t,{},T1)).text();for(let[s,o]of dE(i))n.set(s,o)}return n}async function aa(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Or(e,r,n,{Range:`bytes=0-${Yg}`}),s=Jn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Qn(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 am(e,t){if(Yn(At)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(_g)}),s=`${At.origin}/autocomplete.json?${i}`;return V1(await(await Or(At,s,t,{},Cg)).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(_g)});return Z1(await(await Or(n,`${n.origin}/tag.json?${r}`,t,{},Cg)).text())}async function um(e,t,n){let r=await Or(e,t,n,{Range:`bytes=0-${Yg}`});return Jn(new Uint8Array(await r.arrayBuffer()))}async function ua(e,t,n,r){let i=await Or(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:f,value:d}=await o.read();if(f)break;a.push(d),u+=d.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let f of a)c.set(f,l),l+=f.length;return c}var kt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Ms="Original",mE=1e6,sn="_groups.toml",cm=3,lm=8,Cc="[a-z0-9]+(?:-[a-z0-9]+)*",pE=new RegExp(`^(?:(${Cc})@(${Cc})/)?(${Cc})$`),gm=["background","foreground","cursor","selection"];function ge(e,t){throw Error(`${e}: ${t}`)}function Fr(e,t,n){if(typeof n!=="string"||!Ht(n))ge(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Is(e,t,n){if(typeof n!=="string"||n.length===0)ge(e,`${t} must be a non-empty string`);return n}function En(e){return e.replace("@","--").replace("/","--")}function _(e){return`ttheme-${En(e)}`}function Me(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function $i(e){return e.slice(e.indexOf("/")+1)}function on(e){let t=pE.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function Ns(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function Ss(e,t,n){let r=Is(e,t,n),i=Ns(r);if(i)ge(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function fm(e,t,n){let r=Is(e,t,n),i=on(r);if(i)ge(e,`${t} "${r}" ${i}`);return r}function wi(e){return e&&typeof e==="object"?e:{}}function bE(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)ge(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Fr(e,`ghostty.icon_screen[${s}]`,i))}function wE(e,t,n){let r=wi(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Fr(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:bE(e,r.icon_screen,n)}}function $E(e){return new Map([...gm.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function kE(e,t,n){if(!Array.isArray(t)||t.length!==cm)ge(e,`meta.signature must name exactly ${cm} palette slots`);let r=$E(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Is(e,u,a),l=r.get(c);if(l===void 0)ge(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${gm.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)ge(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function yE(e,t,n){if(t===void 0)return;if(!n)ge(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))ge(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=X.find((u)=>u.key===i);if(!o)ge(e,`meta.booru_sites.${i} is not a find site — use ${X.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))ge(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))ge(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function EE(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>lm)ge(e,`[[picture]] holds 1 to ${lm} pictures`);return t.map((n,r)=>{let i=wi(n),s=`picture[${r}]`,o=X.find((l)=>l.key===i.site);if(!o)ge(e,`${s}.site must be one of ${X.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ge(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))ge(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!kt.includes(u))ge(e,`${s}.position must be one of ${kt.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))ge(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function mm(e,t){try{return Ic(t)}catch(n){ge(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
- `)[0]}`)}}function vE(e){let n=mm(sn,dm(hm(e,sn),"utf8")).group;if(!Array.isArray(n)||n.length===0)ge(sn,"needs at least one [[group]] table");return n.map((r)=>{let i=wi(r);return{name:Ss(sn,"group.name",i.name),native:i.native===void 0?void 0:Ss(sn,"group.native",i.native),lead:Is(sn,"group.lead",i.lead)}})}function ME(e,t){if(!Array.isArray(t)||t.length===0)ge(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=Ss(e,`meta.native_names[${r}]`,n);if(i.includes("|"))ge(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function _c(e,t,n){let r=mm(e,t),i=wi(r.meta),s=wi(r.colors),o=wi(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)ge(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=fm(e,"meta.name",i.name);if(u!==n.name)ge(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let T of["order","role"])if(c&&i[T]!==void 0)ge(e,`meta.${T} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")ge(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:fm(e,"meta.base",i.base);if(f!==void 0&&!c)ge(e,"meta.base is for market palettes");let d=f===void 0?void 0:n.bases?.get(f),h=c&&i.group===void 0?d?.group??Ms:Ss(e,"meta.group",i.group),g=n.groups.get(h);if(!g&&!(c&&(h===Ms||n.open)))ge(e,`meta.group "${h}" has no [[group]] table in ${sn}`);let b=Fr(e,"colors.background",s.background),p=Fr(e,"colors.foreground",s.foreground),m=Fr(e,"colors.cursor",s.cursor),$=Fr(e,"colors.selection_background",s.selection_background),E=a.map((T,x)=>Fr(e,`colors.ansi[${x}]`,T)),M=kE(e,i.signature,{background:b,foreground:p,cursor:m,selection:$,ansi:E}),w=i.booru===void 0?void 0:Is(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))ge(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let S=yE(e,i.booru_sites,w),k=i.native_names===void 0?void 0:ME(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")ge(e,"contrast.waive needs a contrast.reason explaining why");let O=EE(e,r.picture);return{name:u,...f?{base:f}:{},group:h,native:g?.native,...k?{nativeNames:k}:{},lead:!c&&g?.lead===u,order:c?d?.order??mE:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?f??"original":Ss(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...S?{booruSites:S}:{},background:b,foreground:p,cursor:m,selectionBackground:$,ansi:E,signature:M.colors,signatureSlots:M.names,ghostty:wE(e,r.ghostty,{background:b,cursor:m,selectionBackground:$}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...O?{pictures:O}:{}}}function pm(e){let t=vE(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)ge(sn,"group.name must be unique");let r=hE(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>_c(s,dm(hm(e,s),"utf8"),{name:gE(s,".toml"),groups:n})).sort((s,o)=>s.order-o.order);if(new Set(r.map((s)=>s.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)ge(sn,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))ge(sn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function bm(e){return e.filter((t)=>t.role===void 0)}function Hr(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>Me(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(Me(r.name)!==void 0)-Number(Me(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||t((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var ca={width:2560,height:1550},OE=2560,RE=0.1,Pm=0.99,FE=2,vn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},HE=Ye(rt("#19161e","#9b86c8",0.2)),TE="shelf",da="originals",xE="images.json",Wc=1;function AE(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 wm(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=wm((s)=>dh({name:e.name,background:rt(e.background,t,s),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),i=wm((s)=>Ye(rt(e.background,t,s))<=HE);return{cap:r,matched:i,opacity:Math.floor(Math.min(r,i)*100)/100}}function $m(e,t){let n=AE(e,t),{cap:r,matched:i,opacity:s}=Om(e,n),o=ve(e.background),a=Math.hypot(...ve(n).map((u,c)=>(u-(o[c]??0))*s));return{slot:t,color:n,cap:r,matched:i,opacity:s,reach:a}}function ha(e,t){return Om(e,t).opacity}function yi(e,t){let n=$m(e,"cursor");if(n.opacity>=RE)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>$m(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function LE(e){return vg(e)??{x:0,y:0,w:e.width,h:e.height}}function qc(e,t){if(e<=0||t<=0)return ca;let n=Math.min(1,ca.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function Rm(e,t,n,r){if(r<vn.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(vn.tall*n,vn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>vn.widest*t)s=vn.widest*t,i=s*e.h/e.w;let o=vn.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-vn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function Fm(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function CE(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(Fm(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*Pm)return Math.min(FE,Math.max(1,255/Math.max(1,o)));return 1}var Gc=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 _E(e,t,n){return`#${[e,t,n].map((r)=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function GE(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*(Gc[c]??0)+0.7152*(Gc[l]??0)+0.0722*(Gc[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*Pm){let u=Math.max(1,n[a]??1);return _E((r[a*3]??0)/u,(r[a*3+1]??0)/u,(r[a*3+2]??0)/u)}return"#ffffff"}function WE(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,Fm(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function Hm(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 la(e,t,n,r){let i=new Float32Array(n*r),s=Hm(t,n,r);if(s){let o=Ig(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 zc(e,t,n,r){let i=new Uint8Array(n*r*4),s=Hm(t,n,r);if(s){let o=s.x1-s.x0,a=cs(e,s.box,o,s.y1-s.y0);for(let u=s.y0;u<s.y1;u++)i.set(a.data.subarray((u-s.y0)*o*4,(u-s.y0+1)*o*4),(u*n+s.x0)*4)}return{width:n,height:r,data:i}}function Uc(e,t){if(t<=0)return e;let{width:n,height:r}=e,i=[0,1,2,3].map(()=>({width:n,height:r,data:new Float32Array(n*r)}));for(let a=0;a<n*r;a++){let u=e.data[a*4+3]??0;for(let c=0;c<3;c++)i[c].data[a]=(e.data[a*4+c]??0)*u/255;i[3].data[a]=u}let s=i.map((a)=>ls(a,t).data),o=new Uint8Array(n*r*4);for(let a=0;a<n*r;a++){let u=s[3]?.[a]??0;if(u<=0)continue;for(let c=0;c<3;c++)o[a*4+c]=Math.min(255,Math.max(0,Math.round((s[c]?.[a]??0)*255/u)));o[a*4+3]=Math.min(255,Math.round(u))}return{width:n,height:r,data:o}}function Yc(e){let t=LE(e);return{box:t,clear:kn(e,t),ink:WE(e,CE(e,t)),image:e,peak:GE(e,t)}}function Tm(e,t,n,r,i){let s=Yc(e),{box:o,clear:a,ink:u}=s,c=Rm(o,t,n,a),l=Math.min(1,OE/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:Uc(cs(e,o,f.w,f.h),d),fill:Uc(zc(e,c,t,n),r),focus:c.focus,peak:s.peak};let h=la(u,{crop:o,at:f,focus:c.focus},f.w,f.h),g=la(u,c,t,n);return{coloring:i,figure:fs(ls(h,d)),fill:fs(ls(g,r)),focus:c.focus}}function UE(e,t,n,r){let i=ve(t),s=ve(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function jE(e,t,n){let r=ve(t),i=new Uint8Array(e.width*e.height*4);for(let s=0;s<e.width*e.height;s++){let o=(e.data[s*4+3]??0)/255*n;for(let a=0;a<3;a++)i[s*4+a]=Math.round((r[a]??0)+((e.data[s*4+a]??0)-(r[a]??0))*o);i[s*4+3]=255}return{width:e.width,height:e.height,data:i}}function xm(e,t,n,r,i,s,o,a="tone"){let{box:u,clear:c,ink:l}=e,f=Rm(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:Um(u.w,u.h,r,i,h,o?.at??5,!1,h>100?Math.round(f.focus*100):-1),focus:f.focus},b=a==="original"?ha(t,e.peak):n.opacity,p=o?.opacity??b;return{image:a==="original"?jE(Uc(zc(e.image,g,r,i),s),t.background,p):UE(fs(ls(la(l,g,r,i),s)),t.background,n.color,p),fill:d,opacity:b}}function Se(e){return D(e,"ttheme","backgrounds")}function jc(e){return D(e,xE)}function Xn(e){try{return fa(e,"utf8")}catch{return}}function Zn(e){try{return NE(e)}catch{return[]}}function ct(e){let t=Xn(jc(e));if(t===void 0)return KE(e);let n=JSON.parse(t);if(n.version!==Wc)throw Error(`${jc(e)} is version ${n.version} — this ttheme reads version ${Wc}`);return n}function Dn(e){return e.coloring??"tone"}function Qc(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,...e.selection?{selection:e.selection}:{},ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}function Ps(e){return{hue:{color:e.backdrop.color,opacity:e.backdrop.opacity},colors:Qc(e)}}function Os(e){return e.tone===void 0&&Dn(e)==="tone"}function km(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function Am(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${km(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?km(i):"-"}`,...i.from?[i.from]:[]].join(" ")),...t.pictures.filter((i)=>Dn(i)==="original").map((i)=>`# colors ${i.key} original`),`background-image = ${D(e,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
312
- `)}function Lm(e){let t=Se(e);for(let[n,r]of Object.entries(ct(t).palettes)){let i=D(t,`${En(n)}.conf`),s=Am(t,r);if(Xn(i)!==s)K(i,s)}}function Ei(e,t,n){K(jc(e),`${JSON.stringify(t,null,2)}
313
- `);for(let r of n){let i=t.palettes[r],s=D(e,`${En(r)}.conf`);if(i)K(s,Am(e,i));else ki(s,{force:!0})}}function Cm(e,t){return Zn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function Vc(e,t){for(let n of Cm(e,t))ki(D(e,n),{force:!0})}function _m(e,t){Vc(e,t.stem);for(let n of[t.original,t.cut])if(n)ki(D(e,n),{force:!0})}function ym(e,t,n,r){let i=Nm(/^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(da,c)}:{}}}function Em(e,t){if(Jc(e))Im(e,t)}function KE(e){let t={version:Wc,palettes:{}};if(!Jc(e))return t;let n=Zn(D(e,da)),r=Zn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=D(e,TE);for(let s of new Set([...r,...Zn(i)])){let o=[],a=ym(s,Xn(D(e,`${s}.conf`)),n);if(a)Em(D(e,`${s}.tune.conf`),D(e,`${a.stem}.tune.conf`)),Em(D(e,`${s}.off.conf`),D(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Zn(D(i,s))){let c=D(i,s,u),l=ym(s,Xn(D(c,".conf")),n,u);if(!l)continue;for(let f of Zn(c)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${s}${f}`;if(f!==".conf")Im(D(c,f),D(e,d))}ki(c,{recursive:!0}),o.push(l)}if(Zn(D(i,s)).length===0)ki(D(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(Zn(i).length===0)ki(i,{recursive:!0,force:!0});return Ei(e,t,Object.keys(t.palettes)),t}function vm(e,t,n){return t.startsWith("~/")?D(n,t.slice(2)):PE(t)?t:D(e,t)}function Rs(e,t,n){let r=new Map,i=(a,u)=>{let c=Xn(a);if(c===void 0)return!1;for(let l of c.split(`
314
- `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(f?.[1]==="config-file"&&u<4)i(vm(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,`${En(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:vm(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 ga(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t];if(!s)throw Error(`${t} has no image`);let o=s.pictures.findIndex((c)=>c.key===(n??s.active));if(o===-1)throw Error(`${t} has no picture ${n}`);let[a]=s.pictures.splice(o,1);_m(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 Ei(r,i,[t]),{key:a.key,left:s.pictures.length}}function Gm(e,t,n,r){let i=n.coloring==="original"?Bn(n.figure):hs(n.figure,r),s=n.coloring==="original"?Bn(n.fill):hs(n.fill,r),o=`${En(e)}.${Sm("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:ha(e,n.peak),peak:n.peak}:{coloring:"tone",opacity:t.opacity,tone:t.color}}function Kc(e,t){return D(da,`${En(e)}-${t}`)}function Zc(e,t){return t.map(([n,r])=>{let i=D(e,n);return K(i,r),i})}function ma(e,t,n,r,i,s,o,a="tone"){let u=Se(e),c=t.name,l=ft(i),f=ct(u),d=f.palettes[c]??{active:l,pictures:[]},h=qc(s.width,s.height),g=Tm(r,h.width,h.height,o,a),b=Gm(c,l,g,n.color),p=Kc(c,l),m={key:l,stem:b.stem,fill:b.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:`${p}.${i.ext}`,...i.cut?{cut:`${p}.cut.png`}:{}},$=d.pictures.find((M)=>M.key===l);if($)_m(u,$);IE(D(u,da),{recursive:!0});let E=Zc(u,[...b.files,[m.original,i.bytes],...m.cut?[[m.cut,vc(ds(r))]]:[]]);return d.pictures=$?d.pictures.map((M)=>M===$?m:M):[...d.pictures,m],d.active=l,f.palettes[c]=d,Ei(u,f,[c]),[...E,D(u,`${En(c)}.conf`)]}function vi(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t],o=s?s.pictures.findIndex((a)=>a.key===n):-1;if(!s||o===-1)throw Error(`${t} has no picture ${n}`);if(s.active!==n)s.active=n,Ei(r,i,[t]);return{at:o+1,of:s.pictures.length}}function Ct(e,t){let n=ct(Se(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var Bc="top-right";function Um(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),f=n*t>=r*e!==!o,d=f?u(i*n/100):u(i*r*e/(100*t)),h=f?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-d)/2),b=u(l*(r-h)/2);if(a>=0){if(d>n)g=u((n-d)/2);if(h>r)b=Math.max(r-h,Math.min(0,u(r/2)-u(a*h/100)))}return{x:g,y:b,w:d,h}}function Xc(e,t){let n=Xn(D(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=Nm(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!==Bc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Fs(e,t,n,r,i){let s=n.size??"fill",o=n.position??Bc,a=n.opacity??t.opacity;if(s==="fill"&&o===Bc&&a===t.opacity)return;let u=kt.indexOf(o)+1,c=D(e,`${t.stem}.png`),l=D(e,t.fill),f=!0,d=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!d)l=c,f=!1;else if(typeof s==="number"){if(Os(t))throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=xt(new Uint8Array(fa(c))),{width:b,height:p}=d?ca:g,m=d?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,$=Um(g.width,g.height,b,p,s,u,!1,m);l=D(e,`${t.stem}@${s}-${o}${d?`-${b}x${p}`:""}.png`);let M={crop:{x:0,y:0,w:g.width,h:g.height},at:$,focus:m};K(l,t.tone?hs(fs(la(ds(g),M,b,p)),t.tone):Bn(zc(g,M,b,p))),f=d}let h=D(e,`${t.stem}.tune.conf`);return K(h,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
- `)),h}function jm(e){let t=new Map;for(let[n,r]of Object.entries(ct(Se(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function BE(e){try{let t=Jn(new Uint8Array(fa(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function pa(e,t,n,r,i,s,o,a,u,c=Dn(n)){let l=Se(e),f=n.window??BE(D(l,n.fill))??ca,d=Tm(r,f.width,f.height,s,c),h=Gm(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:`${Kc(t,n.key)}.cut.png`}:{}};if(d.coloring==="original")delete g.tone;else delete g.peak;if(u)K(D(l,`${Kc(t,n.key)}.cut.png`),vc(ds(r)));if(h.stem===n.stem)return g;Zc(l,h.files);let b=Xc(l,n);Fs(l,g,Dn(n)===c?b:{...b,opacity:void 0},o,a);let p=D(l,`${n.stem}.off.conf`);if(Jc(p))SE(p,D(l,`${g.stem}.off.conf`));return g}function Dc(e,t){let n=Se(e),r=ct(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((f)=>f.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;Ei(n,r,[...i]);for(let o of s)Vc(n,o)}function Km(e,t,n){return e.replace(/^background-image-opacity = (\S+)$/m,(r,i)=>Number(i)===t?`background-image-opacity = ${n}`:r)}function Bm(e,t,n){let r=D(e,`${t.stem}.tune.conf`),i=Xn(r);if(i!==void 0)K(r,Km(i,t.opacity,n));return{...t,opacity:n}}function JE(e,t,n,r){if(n.tone===r.color)return Bm(e,n,r.opacity);let i=Cm(e,n.stem).filter((a)=>a.endsWith(".png")).map((a)=>{let u=new Uint8Array(fa(D(e,a)));return[a,Fg(u,r.color)??hs(ds(xt(u)),r.color)]}),s=(a)=>i.find(([u])=>u===a)?.[1]??new Uint8Array,o=`${En(t)}.${Sm("sha1").update(n.key).update(s(`${n.stem}.png`)).update(s(n.fill)).digest("hex").slice(0,8)}`;Zc(e,i.map(([a,u])=>[o+a.slice(n.stem.length),u]));for(let a of["tune","off"]){let u=Xn(D(e,`${n.stem}.${a}.conf`));if(u!==void 0)K(D(e,`${o}.${a}.conf`),Km(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 Mm(e,t){if(Dn(e)==="original")return e.peak!==void 0&&ha(t.colors,e.peak)!==e.opacity;return e.tone!==void 0&&(e.tone!==t.hue.color||e.opacity!==t.hue.opacity)}function Jm(e,t){let n=Se(e),r=ct(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o);if(!u||!a.pictures.some((c)=>Mm(c,u)))continue;a.pictures=a.pictures.map((c)=>{if(!Mm(c,u))return c;let l=Dn(c)==="original"?Bm(n,c,ha(u.colors,c.peak)):JE(n,o,c,u.hue);if(l.stem!==c.stem)s.push(c.stem);return l}),i.push(o)}if(i.length>0){Ei(n,r,i);for(let o of s)Vc(n,o)}return i}function Bt(e){let{slot:t,color:n,opacity:r}=yi({name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi,waived:e.waive},e.signatureSlots);return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},...e.lead?{lead:!0}:{},order:e.order,ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},...e.role==="default"?{default:!0}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,signature:e.signature,signatureSlots:e.signatureSlots,ansi:e.ansi,gate:Gn(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function Mn(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},lead:e.lead===!0,order:e.order,...e.default?{role:"default"}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selectionBackground:e.selection,ansi:e.ansi,signature:e.signature,signatureSlots:e.signatureSlots,ghostty:{iconGhost:e.cursor,iconScreen:[e.cursor,e.selection,e.background]},waive:e.waived??[],...e.pictures?{pictures:e.pictures}:{}}}var qE=6,zE=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function ba(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...zE]){let o=t(s);if(i.length===qE||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function Xe(e){return e.filter((t)=>t.default!==!0)}function Hs(){return{version:ot.version,gate:bt,placement:vn,palettes:[]}}function YE(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Hs(),palettes:e.map(Bt)}}var el={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(YE(e),null,2)}
316
- `}]}};import{existsSync as tv,readdirSync as Zm,readFileSync as nv}from"node:fs";import{basename as Xm,join as Ts}from"node:path";import{existsSync as QE,readFileSync as qm}from"node:fs";import{homedir as zm}from"node:os";import{isAbsolute as Ym,join as Tr,resolve as VE}from"node:path";var ee="official",an="ttheme-market.json",Mi="ttheme-market",ZE=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,XE=/^[\w.-]{1,100}$/,DE=/^\w[\w.+/-]{0,199}$/;function tr(e){return Tr(e,"ttheme","installed.json")}function it(e){return e??[ee]}function Si(e){try{let{markets:t}=JSON.parse(qm(tr(e),"utf8"));return it(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[ee]}}function xe(e){return Ym(e)}function yt(e){return e!==ee&&!xe(e)}function er(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(0,t):e}function tl(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(t+1):void 0}function Ii(e,t){return er(e)===er(t)}function nr(e,t){return!xe(e)&&(t?.[e]??e===ee)}function ev(e){return!DE.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function rr(e,t=process.cwd()){if(e===ee)return ee;if(e==="~"||e.startsWith("~/"))return Tr(zm(),e.slice(1));if(e.startsWith(".")||Ym(e))return VE(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!ZE.test(s)||!o||!XE.test(o)||a.length>0||i.length>0||r!==void 0&&ev(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 Qm(e){let t=tl(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${er(e)}/${t}/${an}`}function Vm(e){return e.slice(0,e.indexOf("/"))}function nl(e){return Tr(e,"ttheme","markets")}function Jt(e,t){return Tr(nl(e),`${er(t).replace("/","--")}.json`)}function wa(e){return Tr(e,"ttheme","market")}function rl(e,t){return Tr(wa(e),t)}function il(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return on(`${e}@${t}/x`)}function Et({owner:e,name:t}){return`${e}@${t}`}function un(e){let t=Tr(e,an);if(!QE(t))throw Error(`${e} has no ${an} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(qm(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=il(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function ye(e){if(e===ee)return"the ttheme catalog";if(!xe(e))return`github.com/${e}`;let t=zm();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var Sn="tt1:",Dm=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function xr(e,t=!0){return Si(e).filter(xe).flatMap((n)=>{try{let r=un(n);return[{dir:n,...r,id:Et(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
- `);return[]}})}function $a(e){return Ts(e,"palettes")}function ir(e){let t=$a(e);if(!tv(t))return[];let n=[],r=[];for(let i of Zm(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of Zm(Ts(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:Ts(t,i.name,s),slug:Xm(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Ts(t,i.name),slug:Xm(i.name,".toml")})}return[...n,...r]}function xs(e,t){let n=t.get(e.slug);if(n)return`${e.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=e.catalog===void 0?void 0:Ns(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function sl(e,t){let n=Me(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=xr(e,!1).find((s)=>s.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=$i(t);return ir(r.dir).find((s)=>s.slug===i)?.path??Ts($a(r.dir),`${i}.toml`)}function rv(e,t){let n=new Map;for(let i of t)if(i.group!==Ms&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!Me(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function vt(e,t,n){let r=$i(e),{native:i,...s}=_c(`${r}.toml`,t,rv(r,n)),o=Me(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function sr(e,t,n,r=!0){let i=new Map;return ir(e).flatMap((s)=>{try{let o=xs(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Bt(vt(`${t}/${s.slug}`,nv(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 ka(e,t,n=!0){return xr(e,n).flatMap(({dir:r,id:i})=>sr(r,i,t,n))}function ol(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 ep(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 tp(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
310
+ */import{readdirSync as N1,rmSync as P1,statSync as R1}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as O1}from"node:net";import{homedir as F1}from"node:os";import{join as bs}from"node:path";import{setTimeout as T1}from"node:timers/promises";var zn=100,$t=25000000,H1=536870912,hi=["safe","questionable","explicit"],Pr=["nudity","underwear"],Hc=["comic","monochrome","sketch","chibi"],Vg=["off","5","10","25","50","100"],Yg=["off","720","1080","1440","1800","2560"],Qg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},x1={comic:new Set(["comic","4koma"]),monochrome:new Set(["monochrome","greyscale"]),sketch:new Set(["sketch","lineart","line_art"]),chibi:new Set(["chibi"])},A1=/^(?:rating|score|width|height|filetype|dimension):/,ps={safe:"s",questionable:"q",explicit:"e"},Zg=8191,L1=20000,C1=5000,Wg=3000,Ug=8,_1=3000,Xg=60000,jg=3,G1=3,W1="https://static.zerochan.net",Dg="https://s1.zerochan.net",xc=`ttheme/${et.version} (+${et.homepage})`,U1=["orig","tile","thumb","cut"],em=new Map,j1=sE(process.env.TTHEME_FIND_HOSTS),K1=iE(process.env.TTHEME_FIND_CUTOUTS);O1(_1);var B1=["artist","character","copyright"];function Kg(e){try{return N1(e)}catch{return[]}}function gi(e){return e.startsWith("//")?`https:${e}`:e}function Yn(e){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(e)?.[1]??"").toLowerCase()}function ws(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function J1(e){let t=e.trim(),r=(t?JSON.parse(t):{}).tags??{};return new Map(Object.entries(r).map(([i,s])=>[i,String(s)]))}function Fc(e,t,n){let r=gi(String(e??""));return{file:r,width:Number(t)||0,height:Number(n)||0,ext:Yn(r)}}function yn(e){return String(e??"").split(/\s+/).filter(Boolean)}function Tc(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 tm(e,t){let n=gi(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:yn(t.tags),named:t.named,...Tc(e.created_at)?{posted:Tc(e.created_at)}:{},solo:t.solo,family:Number(e.parent_id)||(e.has_children===!0?Number(e.id):0),smaller:t.versions.filter((s)=>s.file&&s.width>0&&s.height>0&&s.width*s.height<r*i)}]}function q1(e){let t=J1(e);return ws(e).flatMap((n)=>{let r=gi(String(n.file_url??"")),i=String(n.tags??""),s=(o)=>yn(i).filter((a)=>t.get(a)===o);return tm(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Yn(r)).toLowerCase(),owner:n.author,md5:n.md5,tags:i,named:{artist:s("artist"),character:s("character"),copyright:s("copyright")},solo:void 0,versions:[Fc(n.jpeg_url,n.jpeg_width,n.jpeg_height),Fc(n.sample_url,n.sample_width,n.sample_height)]})})}function z1(e){return ws(e).flatMap((t)=>{let n=gi(String(t.file_url??"")),r=String(t.tag_string??""),i=t.media_asset??{};return tm(t,{preview:i.variants?.find((s)=>s.type==="360x360")?.url??t.preview_file_url,file:n,ext:String(t.file_ext||Yn(n)).toLowerCase(),owner:"",md5:t.md5,tags:r,named:{artist:yn(t.tag_string_artist),character:yn(t.tag_string_character),copyright:yn(t.tag_string_copyright)},solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((s)=>Fc(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 nm(e){return e.toLowerCase().replace(/\s+/g,"_")}function V1(e){return(Array.isArray(e)?e:[]).map((t)=>nm(String(t)))}function Y1(e){return String(e??"").replace(/[^0-9a-z]+/gi,".").replace(/^\.+|\.+$/g,"")||"zerochan"}function Q1(e){let t=e.trim(),n=t?JSON.parse(t):{};return(Array.isArray(n.items)?n.items:n.id?[n]:[]).flatMap((i)=>{let s=Number(i.id);if(!s)return[];let o=V1(i.tags),a=gi(String(i.full??""));return[{id:s,width:Number(i.width)||0,height:Number(i.height)||0,file:a,ext:Yn(a),preview:`${Dg}/${Y1(i.tag??i.primary)}.600.${s}.jpg`,owner:"",score:0,rating:o.some((u)=>Qg.nudity.has(u))?"q":"g",md5:String(i.md5??i.hash??""),source:String(i.source??""),tags:o,named:{artist:[],character:[],copyright:[]},solo:o.includes("solo"),family:0,smaller:[]}]})}var Z1={mangaka:"artist",studio:"artist",character:"character",series:"copyright",game:"copyright"};function Bg(e){return e.replace(/&(?:#(\d+)|amp|quot|apos|lt|gt);/g,(t,n)=>n?String.fromCharCode(Number(n)):{"&amp;":"&","&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">"}[t]??t)}function X1(e){let t={artist:[],character:[],copyright:[]};for(let[,r,i]of e.matchAll(/<li class="([a-z]+)[^"]*"[^>]*\bdata-tag="([^"]*)"/g)){let s=Z1[r],o=nm(Bg(i));if(s&&!t[s].includes(o))t[s].push(o)}let n=Tc(/"datePublished":\s*"([^"]+)"/.exec(e)?.[1]);return{named:t,source:"",owner:Bg(/\buploader = \{\s*name: '([^']*)'/.exec(e)?.[1]??""),...n?{posted:n}:{}}}function D1(e){return Number(/Zerochan has ([\d,]+) /.exec(e)?.[1]?.replace(/,/g,"")??0)}function eE(e){return ws(e).flatMap((t)=>{let n=String(t.value??"");return n?[{value:n,count:Number(t.post_count)||0}]:[]})}function tE(e){return ws(e).flatMap((t)=>{let n=String(t.name??"");return n?[{value:n,count:Number(t.count)||0}]:[]})}function nE(e){return Number(/count="(\d+)"/.exec(e)?.[1]??0)}function rE(e){let n=(e.trim()?JSON.parse(e):{}).counts?.posts;return n===null?Number.NaN:Number(n)||0}function iE(e){let t=new Map;for(let n of(e??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)t.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return t}function sE(e){let t=new Map;for(let n of(e??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let s=new URL(n.slice(r+1));if(i&&s.protocol==="https:")t.set(i,s.origin)}catch{}}return t}function Zo(e,t,n,r){let i=(e??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let s=t.filter((o)=>i.includes(o));return s.length>0?s:[...n]}function Or(e){return Zo(e,hi,["safe"])}function mi(e){return Zo(e,Pr,Pr,"none")}function Xo(e){return Zo(e,Hc,[],"none")}function $s(e){let t=X.map((n)=>n.name);return Zo(e,t,t)}function Ac(e,t,n){return{score:Number(e)||0,size:Number(t)||0,png:n==="on"}}function ks(e){return[...new Set((e??"").toLowerCase().split(/[\s,]+/).map((t)=>t.replace(/^-+/,"")).filter(Boolean))]}function Lc(e,t,n){return{safe:new Set(e),questionable:new Set(t),explicit:new Set(n)}}function Cc(e){let t=j1.get(e.key),n=K1.get(e.key);return{...e,origin:t??e.origin,moved:t!==void 0&&t!==e.origin,cutouts:n??e.cutouts,vouched:e.vouched&&n===void 0}}function rm(e){return e.length<2?e.join(""):e.map((t)=>`~${t}`).join(" ")}function im(e){return e>0?[`width:>=${e}`,`height:>=${e}`]:[]}function Jg(e){let t=Cc(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}`]:[],...im(i)],cutouts:rm(t.cutouts),ratings:Lc([ps.safe],[ps.questionable],[ps.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${ps[i]}`;let s=hi.filter((a)=>!r.includes(a)),[o]=s;return s.length===1&&o?`-rating:${ps[o]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${t.origin}/post.json?${n({limit:String(zn),page:String(i+1),tags:r})}`,countUrl:(r)=>`${t.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${t.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${t.origin}/post/show/${r}`,parse:q1,count:nE,uploadedBy:(r)=>`user:${r}`}}function oE(e){let t=Cc(e),n=Lc(["g"],["s","q"],["e"]);return{...t,scored:!0,narrow:({score:r,size:i,png:s})=>[...r>0?[`score:>=${r}`]:[],...im(i),...s?["filetype:png"]:[]],cutouts:rm(t.cutouts),ratings:n,rate:(r)=>r.length===hi.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${t.origin}/posts.json?${new URLSearchParams({limit:String(zn),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:z1,count:rE,uploadedBy:(r)=>`user:${r}`}}function Oc(e){return e.split(/\s+/).filter((t)=>t&&!/^(?:order|dimension):/.test(t)).map((t)=>t.split("_").map(encodeURIComponent).join("+")).join(",")}function qg(e){let t=e.split(/\s+/),n=t.find((r)=>r.startsWith("dimension:"))?.slice(10);return{s:t.includes("order:fav")?"fav":"id",...n?{d:n}:{}}}function aE(e){let t=Cc(e);return{...t,scored:!1,narrow:({size:n})=>n>=1800?["dimension:huge"]:n>0?["dimension:large"]:[],cutouts:t.cutouts[0]??"",ratings:Lc(["g"],["q"],["e"]),rate:()=>"",best:"order:fav",tagBudget:3,missing:404,postsUrl:(n,r)=>`${t.origin}/${Oc(n)}?${new URLSearchParams({json:"",l:String(zn),p:String(r+1),...qg(n)})}`,countUrl:(n)=>`${t.origin}/${Oc(n)}?${new URLSearchParams({xml:"",l:"1"})}`,postUrl:(n)=>`${t.origin}/${n}?json=`,pageUrl:(n)=>`${t.origin}/${n}`,parse:Q1,count:D1,credits:X1,counts:(n)=>Oc(n).split(",").length===1&&!("d"in qg(n)),guesses:(n)=>(n.tags.includes("transparent_background")?["png","jpg"]:["jpg","png"]).map((r)=>n.preview.replace(Dg,W1).replace(/\.600\.(\d+)\.jpg$/,`.full.$1.${r}`))}}function uE(e){let t=zg(`https://${e}`);return X.find((n)=>zg(n.origin)===t)}function _c(e){return e.split(/\s+/).filter((t)=>t&&!A1.test(t)).length}function Do(e,t){let n=e.trim();if(/^\d+$/.test(n))return{site:t,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let a=X.find((u)=>u.key===r[1]||u.name===r[1]);return a&&{site:a,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let s=uE(i.host),o=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return s&&o>0?{site:s,id:o}:void 0}var X=[oE({key:"danbooru",name:"danbooru",origin:"https://shima.donmai.us",cutouts:["transparent_background"],vouched:!1,ansi:2}),Jg({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,ansi:6}),Jg({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,ansi:5}),aE({key:"zerochan",name:"zerochan",origin:"https://www.zerochan.net",cutouts:["transparent_background"],vouched:!1,ansi:3})],Lt=X.find((e)=>e.key==="danbooru"),Qn=134217728;function Ct(e,t){let n=X.indexOf(e);return(n===-1?X.length:n)*Qn+t}function zg(e){let t;try{t=new URL(e).hostname}catch{return""}return t.split(".").slice(-2).join(".")}function pi(e,t,n=t){return t.mirror&&n===t?{site:Lt,url:t.mirror.file}:{site:e,url:n.file}}function ea(e,t){return t.mirror?{site:Lt,url:t.mirror.preview}:{site:e,url:t.preview}}function ta(e,t=Pr){return e.tags.filter((n)=>t.some((r)=>Qg[r].has(n)))}function sm(e,t){return e.tags.filter((n)=>t.some((r)=>x1[r].has(n)))}function na(e,t,n=["safe"]){return n.some((r)=>e.ratings[r].has(t.rating))}function om(e,t){return e.rate(["safe"])===""?void 0:hi.find((n)=>e.ratings[n].has(t.rating))}function nn(e){return[e,...e.smaller].find((t)=>t.width*t.height<=$t)}function am(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 bi(){return bs(process.env.XDG_CACHE_HOME??bs(F1(),".cache"),"ttheme")}function rn(e){return bs(bi(),e.key)}function um(e=H1,t=bi()){let n=[],r=0;for(let i of Kg(t))for(let s of U1){let o=bs(t,i,s);for(let a of Kg(o)){let u=bs(o,a);try{let{size:c,mtimeMs:l}=R1(u);n.push({path:u,size:c,at:l}),r+=c}catch{}}}n.sort((i,s)=>i.at-s.at);for(let i of n){if(r<=e)return;try{P1(i.path,{force:!0}),r-=i.size}catch{}}}function cE(e,t){if(e!==null&&/^\s*\d+\s*$/.test(e))return Number(e)*1000;let n=e===null?Number.NaN:Date.parse(e);return Number.isNaN(n)?Xg:Math.max(0,n-t)}function Vn(e){return em.get(e.key)??0}function lE(e){for(let t=e;t instanceof Error;t=t.cause)if(t.code==="ECONNRESET")return!0;return!1}function fE(e){return(e.headers.get("server")??"").startsWith("cloudflare")&&e.headers.get("cf-mitigated")==="challenge"}function dE(e,t){let n=new URL(t,e);if(!n.search)n.search=new URL(e).search;return n.href}async function Rr(e,t,n,r={},i=L1){let s=t;for(let o=1,a=0;;o++){let u=Vn(e)-Date.now();if(u>0)await T1(u,void 0,{signal:n});let c;try{c=await fetch(s,{headers:{"User-Agent":xc,Referer:`${e.origin}/`,...r},redirect:"manual",signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(f){if(o<jg&&!n.aborted&&lE(f))continue;throw f}let l=c.headers.get("location");if(l&&c.status>=300&&c.status<400&&a<G1){await c.body?.cancel(),s=dE(s,l),a++,o--;continue}if(c.status===429&&o<jg){await c.body?.cancel();let f=cE(c.headers.get("retry-after"),Date.now());if(f>Xg)throw Error(`${e.name} asks to wait ${Math.ceil(f/1000)}s`);em.set(e.key,Math.max(Vn(e),Date.now()+f));continue}if(!c.ok)throw await c.body?.cancel(),Object.assign(Error(fE(c)?`${e.name} is behind a Cloudflare challenge`:`${e.name} answered ${c.status}`),{status:c.status});return c}}async function ra(e,t,n){try{return await(await Rr(e,t,n)).text()}catch(r){if(e.missing!==void 0&&r.status===e.missing)return"";throw r}}async function cm(e,t,n,r){return e.parse(await ra(e,e.postsUrl(t,n),r))}async function Gc(e,t,n){return e.count(await ra(e,e.countUrl(t),n))}async function ys(e,t,n){let[r]=e.parse(await ra(e,e.postUrl(t),n));return r}async function ia(e,t,n){return e.credits?.(await ra(e,e.pageUrl(t),n))}var hE=/^https?:\/\/(?:i\.pximg\.net|i\d*\.pixiv\.net|img\d*\.pixiv\.net)\/\S*\/(\d+)(?:_p\d+)?(?:_\w+)?\.\w+(?:[?#]\S*)?$/i,gE=/^https?:\/\/(?:www\.)?pixiv\.net\/member_illust\.php\?\S*\billust_id=(\d+)/i;function Es(e){let t=hE.exec(e)?.[1]??gE.exec(e)?.[1];return t?`https://www.pixiv.net/artworks/${t}`:e}function sa(e,t){return e.credits!==void 0&&t.named.artist.length===0}function vs(e,t){for(let n of B1){let r=t.named?.[n]??[];if(e.named[n].length===0&&r.length>0)e.named[n]=r}if(e.source||=t.source??"",e.owner||=t.owner??"",!e.posted&&t.posted)e.posted=t.posted}function mE(e){let t=new URLSearchParams({limit:String(2*zn),only:"md5,tag_string,tag_string_artist,tag_string_character,tag_string_copyright,source,file_url",tags:`md5:${e.join(",")}`});return`${Lt.origin}/posts.json?${t}`}function pE(e){return new Map(ws(e).flatMap((t)=>{let n=String(t.md5??"");return n?[[n,{tags:yn(t.tag_string),named:{artist:yn(t.tag_string_artist),character:yn(t.tag_string_character),copyright:yn(t.tag_string_copyright)},source:String(t.source??""),file:gi(String(t.file_url??""))}]]:[]}))}function oa(e,t){for(let n of e){let r=t.get(n.md5);if(!r)continue;if(n.tags=[...new Set([...n.tags,...r.tags])],vs(n,r),n.solo=r.tags.includes("solo"),r.file.includes("/original/")){if(n.mirror={file:r.file,preview:r.file.replace("/original/","/360x360/").replace(/\.[a-z0-9]+$/i,".jpg")},!n.file)n.file=r.file,n.ext=Yn(r.file)}}}async function aa(e,t){let n=new Map;if(Vn(Lt)>Date.now())return n;for(let r=0;r<e.length;r+=zn){let i=await(await Rr(Lt,mE(e.slice(r,r+zn)),t,{},C1)).text();for(let[s,o]of pE(i))n.set(s,o)}return n}async function ua(e,t,n){if(t.file||!e.guesses)return;for(let r of e.guesses(t))try{let i=await Rr(e,r,n,{Range:`bytes=0-${Zg}`}),s=Jn(new Uint8Array(await i.arrayBuffer()));return t.file=r,t.ext=Yn(r),s}catch(i){if(n.aborted||i.status!==404)throw i}throw Error(`${e.name} keeps no png or jpg of ${t.id}`)}async function lm(e,t){if(Vn(Lt)<=Date.now())try{let i=new URLSearchParams({"search[query]":e,"search[type]":"tag_query",limit:String(Ug)}),s=`${Lt.origin}/autocomplete.json?${i}`;return eE(await(await Rr(Lt,s,t,{},Wg)).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(Ug)});return tE(await(await Rr(n,`${n.origin}/tag.json?${r}`,t,{},Wg)).text())}async function fm(e,t,n){let r=await Rr(e,t,n,{Range:`bytes=0-${Zg}`});return Jn(new Uint8Array(await r.arrayBuffer()))}async function ca(e,t,n,r){let i=await Rr(e,t,n,{},0),s=Number(i.headers.get("content-length"))||0,o=i.body?.getReader();if(!o)return new Uint8Array(await i.arrayBuffer());let a=[],u=0;for(;;){let{done:f,value:d}=await o.read();if(f)break;a.push(d),u+=d.length,r?.(u,s)}let c=new Uint8Array(u),l=0;for(let f of a)c.set(f,l),l+=f.length;return c}var kt=["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"],Ms="Original",$E=1e6,sn="_groups.toml",dm=3,hm=8,Wc="[a-z0-9]+(?:-[a-z0-9]+)*",kE=new RegExp(`^(?:(${Wc})@(${Wc})/)?(${Wc})$`),bm=["background","foreground","cursor","selection"];function ge(e,t){throw Error(`${e}: ${t}`)}function Fr(e,t,n){if(typeof n!=="string"||!Ht(n))ge(e,`${t} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Is(e,t,n){if(typeof n!=="string"||n.length===0)ge(e,`${t} must be a non-empty string`);return n}function En(e){return e.replace("@","--").replace("/","--")}function _(e){return`ttheme-${En(e)}`}function Me(e){let t=e.indexOf("/");return t<0?void 0:e.slice(0,t)}function $i(e){return e.slice(e.indexOf("/")+1)}function on(e){let t=kE.exec(e);if(!t)return"takes lowercase letters, digits and single hyphens, as <palette> or <owner>@<market>/<palette>";if((t[1]?.length??0)>39)return"has an owner longer than a GitHub handle can be";return(t[2]?.length??0)>40||(t[3]?.length??0)>40?"is longer than 40 characters":void 0}function Ns(e){if(/[\p{Cc}"$`\\]/u.test(e))return"holds a control character, a quote, $, ` or \\";return e.length>80?"is longer than 80 characters":void 0}function Ss(e,t,n){let r=Is(e,t,n),i=Ns(r);if(i)ge(e,`${t} ${JSON.stringify(r)} ${i}`);return r}function gm(e,t,n){let r=Is(e,t,n),i=on(r);if(i)ge(e,`${t} "${r}" ${i}`);return r}function wi(e){return e&&typeof e==="object"?e:{}}function yE(e,t,n){if(t===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(t)?t:[t];if(r.length===0)ge(e,"ghostty.icon_screen must not be empty");return r.map((i,s)=>Fr(e,`ghostty.icon_screen[${s}]`,i))}function EE(e,t,n){let r=wi(t);return{iconGhost:r.icon_ghost===void 0?n.cursor:Fr(e,"ghostty.icon_ghost",r.icon_ghost),iconScreen:yE(e,r.icon_screen,n)}}function vE(e){return new Map([...bm.map((t)=>[t,e[t]]),...e.ansi.map((t,n)=>[`ansi${n}`,t])])}function ME(e,t,n){if(!Array.isArray(t)||t.length!==dm)ge(e,`meta.signature must name exactly ${dm} palette slots`);let r=vE(n),i=[],s=[];for(let[o,a]of t.entries()){let u=`meta.signature[${o}]`,c=Is(e,u,a),l=r.get(c);if(l===void 0)ge(e,`${u} ${JSON.stringify(a)} is not a palette slot — use ${bm.join(", ")} or ansi0-ansi15`);i.push(c),s.push(l)}if(new Set(s).size!==s.length)ge(e,"meta.signature slots must resolve to three different colors");return{names:i,colors:s}}function SE(e,t,n){if(t===void 0)return;if(!n)ge(e,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!t||typeof t!=="object"||Array.isArray(t))ge(e,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,s]of Object.entries(t)){let o=X.find((u)=>u.key===i);if(!o)ge(e,`meta.booru_sites.${i} is not a find site — use ${X.map((u)=>u.key).join(", ")}`);let a=typeof s==="string"?[s]:Array.isArray(s)?s:void 0;if(!a||a.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))ge(e,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(s)}`);if(a.length>1&&Number.isFinite(o.tagBudget))ge(e,`meta.booru_sites.${i} takes one tag — ${o.name} searches ${o.tagBudget} tags at a time`);r[i]=a}return r}function IE(e,t){if(t===void 0)return;if(!Array.isArray(t)||t.length===0||t.length>hm)ge(e,`[[picture]] holds 1 to ${hm} pictures`);return t.map((n,r)=>{let i=wi(n),s=`picture[${r}]`,o=X.find((l)=>l.key===i.site);if(!o)ge(e,`${s}.site must be one of ${X.map((l)=>l.key).join(", ")}`);if(typeof i.id!=="number"||!Number.isSafeInteger(i.id)||i.id<=0)ge(e,`${s}.id must be the post's number on ${o.name}`);let{size:a,position:u,opacity:c}=i;if(a!==void 0&&a!=="fill"&&!(Number.isInteger(a)&&Number(a)>=20&&Number(a)<=999))ge(e,`${s}.size must be "fill" or a percentage from 20 to 999`);if(u!==void 0&&!kt.includes(u))ge(e,`${s}.position must be one of ${kt.join(", ")}`);if(c!==void 0&&!(typeof c==="number"&&c>=0&&c<=1))ge(e,`${s}.opacity must be a number from 0 to 1`);return{site:o.key,id:i.id,...a!==void 0?{size:a}:{},...u!==void 0?{position:u}:{},...c!==void 0?{opacity:c}:{}}})}function wm(e,t){try{return Rc(t)}catch(n){ge(e,`is not valid TOML — ${(n instanceof Error?n.message:String(n)).split(`
311
+ `)[0]}`)}}function NE(e){let n=wm(sn,mm(pm(e,sn),"utf8")).group;if(!Array.isArray(n)||n.length===0)ge(sn,"needs at least one [[group]] table");return n.map((r)=>{let i=wi(r);return{name:Ss(sn,"group.name",i.name),native:i.native===void 0?void 0:Ss(sn,"group.native",i.native),lead:Is(sn,"group.lead",i.lead)}})}function PE(e,t){if(!Array.isArray(t)||t.length===0)ge(e,'meta.native_names must be a list of names, like ["後藤ひとり"]');return t.map((n,r)=>{let i=Ss(e,`meta.native_names[${r}]`,n);if(i.includes("|"))ge(e,`meta.native_names[${r}] ${JSON.stringify(i)} contains |`);return i})}function Uc(e,t,n){let r=wm(e,t),i=wi(r.meta),s=wi(r.colors),o=wi(r.contrast),a=s.ansi;if(!Array.isArray(a)||a.length!==16)ge(e,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(a)?a.length:typeof a}`);let u=gm(e,"meta.name",i.name);if(u!==n.name)ge(e,`meta.name "${u}" does not match its file — it lives at ${n.name}`);let c=n.open===!0;for(let H of["order","role"])if(c&&i[H]!==void 0)ge(e,`meta.${H} is for the official palettes — a market palette follows its base`);let l=i.role;if(l!==void 0&&l!=="default")ge(e,`meta.role must be "default", got ${JSON.stringify(l)}`);let f=i.base===void 0?void 0:gm(e,"meta.base",i.base);if(f!==void 0&&!c)ge(e,"meta.base is for market palettes");let d=f===void 0?void 0:n.bases?.get(f),h=c&&i.group===void 0?d?.group??Ms:Ss(e,"meta.group",i.group),g=n.groups.get(h);if(!g&&!(c&&(h===Ms||n.open)))ge(e,`meta.group "${h}" has no [[group]] table in ${sn}`);let b=Fr(e,"colors.background",s.background),p=Fr(e,"colors.foreground",s.foreground),m=Fr(e,"colors.cursor",s.cursor),$=Fr(e,"colors.selection_background",s.selection_background),E=a.map((H,x)=>Fr(e,`colors.ansi[${x}]`,H)),M=ME(e,i.signature,{background:b,foreground:p,cursor:m,selection:$,ansi:E}),w=i.booru===void 0?void 0:Is(e,"meta.booru",i.booru);if(w!==void 0&&/[\s\p{Cc}]/u.test(w))ge(e,`meta.booru must be a single booru tag, got ${JSON.stringify(w)}`);let S=SE(e,i.booru_sites,w),k=i.native_names===void 0?void 0:PE(e,i.native_names),N=Array.isArray(o.waive)?o.waive.map(String):[];if(N.length>0&&typeof o.reason!=="string")ge(e,"contrast.waive needs a contrast.reason explaining why");let R=IE(e,r.picture);return{name:u,...f?{base:f}:{},group:h,native:g?.native,...k?{nativeNames:k}:{},lead:!c&&g?.lead===u,order:c?d?.order??$E:Number(i.order),role:l,ansiSource:c&&i.ansi_source===void 0?f??"original":Ss(e,"meta.ansi_source",i.ansi_source),...w?{booru:w}:{},...S?{booruSites:S}:{},background:b,foreground:p,cursor:m,selectionBackground:$,ansi:E,signature:M.colors,signatureSlots:M.names,ghostty:EE(e,r.ghostty,{background:b,cursor:m,selectionBackground:$}),waive:N,waiveReason:typeof o.reason==="string"?o.reason:void 0,...R?{pictures:R}:{}}}function $m(e){let t=NE(e),n=new Map(t.map((s)=>[s.name,s]));if(n.size!==t.length)ge(sn,"group.name must be unique");let r=bE(e).filter((s)=>s.endsWith(".toml")&&!s.startsWith("_")).map((s)=>Uc(s,mm(pm(e,s),"utf8"),{name:wE(s,".toml"),groups:n})).sort((s,o)=>s.order-o.order);if(new Set(r.map((s)=>s.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let s of t){let o=r.filter((a)=>a.group===s.name);if(o.length===0)ge(sn,`group "${s.name}" has no themes`);if(!o.some((a)=>a.name===s.lead))ge(sn,`group "${s.name}" lead "${s.lead}" is not one of its themes`)}return r}function km(e){return e.filter((t)=>t.role===void 0)}function Tr(e){let t=(r,i)=>r<i?-1:r>i?1:0,n=(r)=>Me(r.name)?r.name:r.base??r.name;return[...e].sort((r,i)=>Number(Me(r.name)!==void 0)-Number(Me(i.name)!==void 0)||t(r.group.toLowerCase(),i.group.toLowerCase())||Number(r.catalog===void 0)-Number(i.catalog===void 0)||t((r.catalog??"").toLowerCase(),(i.catalog??"").toLowerCase())||t(n(r),n(i))||Number(r.base!==void 0)-Number(i.base!==void 0)||t(r.name,i.name))}var la={width:2560,height:1550},HE=2560,xE=0.1,Fm=0.99,AE=2,vn={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},LE=Ve(it("#19161e","#9b86c8",0.2)),CE="shelf",ha="originals",_E="images.json",Kc=1;function GE(e,t){if(t==="background"||t==="foreground"||t==="cursor")return e[t];if(t==="selection"&&e.selection)return e.selection;let n=/^ansi(\d|1[0-5])$/.exec(t),r=n?e.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${e.name} has no slot ${t}`);return r}function ym(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 Tm(e,t){let r=ym((s)=>mh({name:e.name,background:it(e.background,t,s),foreground:e.foreground,ansi:e.ansi,waive:e.waived??[]}).length===0),i=ym((s)=>Ve(it(e.background,t,s))<=LE);return{cap:r,matched:i,opacity:Math.floor(Math.min(r,i)*100)/100}}function Em(e,t){let n=GE(e,t),{cap:r,matched:i,opacity:s}=Tm(e,n),o=ve(e.background),a=Math.hypot(...ve(n).map((u,c)=>(u-(o[c]??0))*s));return{slot:t,color:n,cap:r,matched:i,opacity:s,reach:a}}function ga(e,t){return Tm(e,t).opacity}function yi(e,t){let n=Em(e,"cursor");if(n.opacity>=xE)return n;return t.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Em(e,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function WE(e){return Ig(e)??{x:0,y:0,w:e.width,h:e.height}}function Yc(e,t){if(e<=0||t<=0)return la;let n=Math.min(1,la.width/Math.max(e,t));return{width:Math.round(e*n),height:Math.round(t*n)}}function Hm(e,t,n,r){if(r<vn.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(vn.tall*n,vn.reach*t*e.h/e.w),s=i*e.w/e.h;if(s>vn.widest*t)s=vn.widest*t,i=s*e.h/e.w;let o=vn.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-vn.margin)-s,y:o,w:s,h:i*a},focus:Math.min(1,(n/2-o)/i)}}function xm(e,t){return 0.299*(e[t]??0)+0.587*(e[t+1]??0)+0.114*(e[t+2]??0)}function UE(e,t){let n=new Uint32Array(256),r=Math.max(1,Math.floor(t.w*t.h/400000)),i=0;for(let o=0;o<t.w*t.h;o+=r){let a=((t.y+Math.floor(o/t.w))*e.width+t.x+o%t.w)*4;if((e.data[a+3]??0)>=128){let u=Math.round(xm(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*Fm)return Math.min(AE,Math.max(1,255/Math.max(1,o)));return 1}var jc=Float64Array.from({length:256},(e,t)=>{let n=t/255;return n<=0.04045?n/12.92:((n+0.055)/1.055)**2.4});function jE(e,t,n){return`#${[e,t,n].map((r)=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function KE(e,t){let n=new Uint32Array(256),r=new Float64Array(768),i=Math.max(1,Math.floor(t.w*t.h/400000)),s=0;for(let a=0;a<t.w*t.h;a+=i){let u=((t.y+Math.floor(a/t.w))*e.width+t.x+a%t.w)*4;if((e.data[u+3]??0)>=128){let c=e.data[u]??0,l=e.data[u+1]??0,f=e.data[u+2]??0,d=Math.round(255*Math.sqrt(0.2126*(jc[c]??0)+0.7152*(jc[l]??0)+0.0722*(jc[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*Fm){let u=Math.max(1,n[a]??1);return jE((r[a*3]??0)/u,(r[a*3+1]??0)/u,(r[a*3+2]??0)/u)}return"#ffffff"}function BE(e,t){let n=new Uint8Array(e.width*e.height);for(let r=0;r<n.length;r++){let i=r*4;n[r]=Math.round(Math.min(255,xm(e.data,i)*t)*(e.data[i+3]??0)/255)}return{width:e.width,height:e.height,data:n}}function Am(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 fa(e,t,n,r){let i=new Float32Array(n*r),s=Am(t,n,r);if(s){let o=Rg(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 Qc(e,t,n,r){let i=new Uint8Array(n*r*4),s=Am(t,n,r);if(s){let o=s.x1-s.x0,a=cs(e,s.box,o,s.y1-s.y0);for(let u=s.y0;u<s.y1;u++)i.set(a.data.subarray((u-s.y0)*o*4,(u-s.y0+1)*o*4),(u*n+s.x0)*4)}return{width:n,height:r,data:i}}function Bc(e,t){if(t<=0)return e;let{width:n,height:r}=e,i=[0,1,2,3].map(()=>({width:n,height:r,data:new Float32Array(n*r)}));for(let a=0;a<n*r;a++){let u=e.data[a*4+3]??0;for(let c=0;c<3;c++)i[c].data[a]=(e.data[a*4+c]??0)*u/255;i[3].data[a]=u}let s=i.map((a)=>ls(a,t).data),o=new Uint8Array(n*r*4);for(let a=0;a<n*r;a++){let u=s[3]?.[a]??0;if(u<=0)continue;for(let c=0;c<3;c++)o[a*4+c]=Math.min(255,Math.max(0,Math.round((s[c]?.[a]??0)*255/u)));o[a*4+3]=Math.min(255,Math.round(u))}return{width:n,height:r,data:o}}function Zc(e){let t=WE(e);return{box:t,clear:kn(e,t),ink:BE(e,UE(e,t)),image:e,peak:KE(e,t)}}function Lm(e,t,n,r,i){let s=Zc(e),{box:o,clear:a,ink:u}=s,c=Hm(o,t,n,a),l=Math.min(1,HE/Math.max(o.w,o.h)),f={x:0,y:0,w:Math.round(o.w*l),h:Math.round(o.h*l)},d=r*f.w*c.crop.w/(o.w*c.at.w);if(i==="original")return{coloring:i,figure:Bc(cs(e,o,f.w,f.h),d),fill:Bc(Qc(e,c,t,n),r),focus:c.focus,peak:s.peak};let h=fa(u,{crop:o,at:f,focus:c.focus},f.w,f.h),g=fa(u,c,t,n);return{coloring:i,figure:fs(ls(h,d)),fill:fs(ls(g,r)),focus:c.focus}}function JE(e,t,n,r){let i=ve(t),s=ve(n),o=new Uint8Array(e.width*e.height*4);for(let a=0;a<e.data.length;a++){let u=(e.data[a]??0)/255*r;for(let c=0;c<3;c++)o[a*4+c]=Math.round((i[c]??0)+((s[c]??0)-(i[c]??0))*u);o[a*4+3]=255}return{width:e.width,height:e.height,data:o}}function qE(e,t,n){let r=ve(t),i=new Uint8Array(e.width*e.height*4);for(let s=0;s<e.width*e.height;s++){let o=(e.data[s*4+3]??0)/255*n;for(let a=0;a<3;a++)i[s*4+a]=Math.round((r[a]??0)+((e.data[s*4+a]??0)-(r[a]??0))*o);i[s*4+3]=255}return{width:e.width,height:e.height,data:i}}function Cm(e,t,n,r,i,s,o,a="tone"){let{box:u,clear:c,ink:l}=e,f=Hm(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:Bm(u.w,u.h,r,i,h,o?.at??5,!1,h>100?Math.round(f.focus*100):-1),focus:f.focus},b=a==="original"?ga(t,e.peak):n.opacity,p=o?.opacity??b;return{image:a==="original"?qE(Bc(Qc(e.image,g,r,i),s),t.background,p):JE(fs(ls(fa(l,g,r,i),s)),t.background,n.color,p),fill:d,opacity:b}}function Se(e){return D(e,"ttheme","backgrounds")}function Jc(e){return D(e,_E)}function Xn(e){try{return da(e,"utf8")}catch{return}}function Zn(e){try{return FE(e)}catch{return[]}}function ct(e){let t=Xn(Jc(e));if(t===void 0)return zE(e);let n=JSON.parse(t);if(n.version!==Kc)throw Error(`${Jc(e)} is version ${n.version} — this ttheme reads version ${Kc}`);return n}function Dn(e){return e.coloring??"tone"}function Xc(e){return{name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,...e.selection?{selection:e.selection}:{},ansi:e.ansi,...e.waived?{waived:e.waived}:{}}}function Ps(e){return{hue:{color:e.backdrop.color,opacity:e.backdrop.opacity},colors:Xc(e)}}function Rs(e){return e.tone===void 0&&Dn(e)==="tone"}function vm(e){return(e.artist??[]).map((t)=>t.replace(/[\s,]+/g,"_")).join(",")}function _m(e,t){let n=t.pictures.findIndex((i)=>i.key===t.active),r=t.pictures[n];return[...r.artist?.length?[`# by ${vm(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?vm(i):"-"}`,...i.from?[i.from]:[]].join(" ")),...t.pictures.filter((i)=>Dn(i)==="original").map((i)=>`# colors ${i.key} original`),`background-image = ${D(e,r.fill)}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${r.opacity}`,`config-file = ?${r.stem}.tune.conf`,`config-file = ?${r.stem}.off.conf`,""].join(`
312
+ `)}function Gm(e){let t=Se(e);for(let[n,r]of Object.entries(ct(t).palettes)){let i=D(t,`${En(n)}.conf`),s=_m(t,r);if(Xn(i)!==s)K(i,s)}}function Ei(e,t,n){K(Jc(e),`${JSON.stringify(t,null,2)}
313
+ `);for(let r of n){let i=t.palettes[r],s=D(e,`${En(r)}.conf`);if(i)K(s,_m(e,i));else ki(s,{force:!0})}}function Wm(e,t){return Zn(e).filter((n)=>n.startsWith(`${t}.`)||n.startsWith(`${t}@`))}function Dc(e,t){for(let n of Wm(e,t))ki(D(e,n),{force:!0})}function Um(e,t){Dc(e,t.stem);for(let n of[t.original,t.cut])if(n)ki(D(e,n),{force:!0})}function Mm(e,t,n,r){let i=Om(/^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(ha,c)}:{}}}function Sm(e,t){if(Vc(e))Rm(e,t)}function zE(e){let t={version:Kc,palettes:{}};if(!Vc(e))return t;let n=Zn(D(e,ha)),r=Zn(e).filter((s)=>s.endsWith(".conf")&&s!=="shown.conf"&&!/\.(tune|off)\.conf$/.test(s)).map((s)=>s.slice(0,-5)),i=D(e,CE);for(let s of new Set([...r,...Zn(i)])){let o=[],a=Mm(s,Xn(D(e,`${s}.conf`)),n);if(a)Sm(D(e,`${s}.tune.conf`),D(e,`${a.stem}.tune.conf`)),Sm(D(e,`${s}.off.conf`),D(e,`${a.stem}.off.conf`)),o.push(a);for(let u of Zn(D(i,s))){let c=D(i,s,u),l=Mm(s,Xn(D(c,".conf")),n,u);if(!l)continue;for(let f of Zn(c)){let d=f===".tune.conf"||f===".off.conf"?`${l.stem}${f}`:`${s}${f}`;if(f!==".conf")Rm(D(c,f),D(e,d))}ki(c,{recursive:!0}),o.push(l)}if(Zn(D(i,s)).length===0)ki(D(i,s),{recursive:!0,force:!0});if(o.length>0)o.sort((u,c)=>u.key<c.key?-1:u.key>c.key?1:0),t.palettes[s]={active:(a??o[0]).key,pictures:o}}if(Zn(i).length===0)ki(i,{recursive:!0,force:!0});return Ei(e,t,Object.keys(t.palettes)),t}function Im(e,t,n){return t.startsWith("~/")?D(n,t.slice(2)):TE(t)?t:D(e,t)}function Os(e,t,n){let r=new Map,i=(a,u)=>{let c=Xn(a);if(c===void 0)return!1;for(let l of c.split(`
314
+ `)){let f=/^([a-z-]+)\s*=\s*(.*?)\s*$/.exec(l);if(f?.[1]==="config-file"&&u<4)i(Im(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,`${En(t)}.conf`),0))return;let s=r.get("background-image")??"";if(s==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:Im(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 ma(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t];if(!s)throw Error(`${t} has no image`);let o=s.pictures.findIndex((c)=>c.key===(n??s.active));if(o===-1)throw Error(`${t} has no picture ${n}`);let[a]=s.pictures.splice(o,1);Um(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 Ei(r,i,[t]),{key:a.key,left:s.pictures.length}}function jm(e,t,n,r){let i=n.coloring==="original"?Bn(n.figure):hs(n.figure,r),s=n.coloring==="original"?Bn(n.fill):hs(n.fill,r),o=`${En(e)}.${Pm("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 Km(e,t,n){return n.coloring==="original"?{coloring:"original",opacity:ga(e,n.peak),peak:n.peak}:{coloring:"tone",opacity:t.opacity,tone:t.color}}function qc(e,t){return D(ha,`${En(e)}-${t}`)}function el(e,t){return t.map(([n,r])=>{let i=D(e,n);return K(i,r),i})}function pa(e,t,n,r,i,s,o,a="tone"){let u=Se(e),c=t.name,l=ft(i),f=ct(u),d=f.palettes[c]??{active:l,pictures:[]},h=Yc(s.width,s.height),g=Lm(r,h.width,h.height,o,a),b=jm(c,l,g,n.color),p=qc(c,l),m={key:l,stem:b.stem,fill:b.fill,...Km(t,n,g),blur:o,window:h,...i.from?{from:i.from}:{},...i.artist?.length?{artist:i.artist}:{},...i.source?{source:i.source}:{},original:`${p}.${i.ext}`,...i.cut?{cut:`${p}.cut.png`}:{}},$=d.pictures.find((M)=>M.key===l);if($)Um(u,$);OE(D(u,ha),{recursive:!0});let E=el(u,[...b.files,[m.original,i.bytes],...m.cut?[[m.cut,Ic(ds(r))]]:[]]);return d.pictures=$?d.pictures.map((M)=>M===$?m:M):[...d.pictures,m],d.active=l,f.palettes[c]=d,Ei(u,f,[c]),[...E,D(u,`${En(c)}.conf`)]}function vi(e,t,n){let r=Se(e),i=ct(r),s=i.palettes[t],o=s?s.pictures.findIndex((a)=>a.key===n):-1;if(!s||o===-1)throw Error(`${t} has no picture ${n}`);if(s.active!==n)s.active=n,Ei(r,i,[t]);return{at:o+1,of:s.pictures.length}}function _t(e,t){let n=ct(Se(e)).palettes[t];if(!n)return[];return[...n.pictures.filter((i)=>i.key===n.active),...n.pictures.filter((i)=>i.key!==n.active)]}var zc="top-right";function Bm(e,t,n,r,i,s,o,a=-1){let u=Math.trunc,c=(s-1)%3,l=u((s-1)/3),f=n*t>=r*e!==!o,d=f?u(i*n/100):u(i*r*e/(100*t)),h=f?u(i*n*t/(100*e)):u(i*r/100),g=u(c*(n-d)/2),b=u(l*(r-h)/2);if(a>=0){if(d>n)g=u((n-d)/2);if(h>r)b=Math.max(r-h,Math.min(0,u(r/2)-u(a*h/100)))}return{x:g,y:b,w:d,h}}function tl(e,t){let n=Xn(D(e,`${t.stem}.tune.conf`));if(n===void 0)return{};let r=(c)=>new RegExp(`^${c}\\s*=\\s*(.*?)\\s*$`,"m").exec(n)?.[1]??"",i=Om(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!==zc?{position:a}:{},...Number.isFinite(u)&&u!==t.opacity?{opacity:u}:{}}}function Fs(e,t,n,r,i){let s=n.size??"fill",o=n.position??zc,a=n.opacity??t.opacity;if(s==="fill"&&o===zc&&a===t.opacity)return;let u=kt.indexOf(o)+1,c=D(e,`${t.stem}.png`),l=D(e,t.fill),f=!0,d=typeof s==="number"&&(s>100||!r&&o!=="center");if(s===100&&!d)l=c,f=!1;else if(typeof s==="number"){if(Rs(t))throw Error(`${t.stem} was drawn before pictures kept their tone — init draws it again`);let g=At(new Uint8Array(da(c))),{width:b,height:p}=d?la:g,m=d?Number(/@fill-(\d+)\.png$/.exec(t.fill)?.[1]??50):-1,$=Bm(g.width,g.height,b,p,s,u,!1,m);l=D(e,`${t.stem}@${s}-${o}${d?`-${b}x${p}`:""}.png`);let M={crop:{x:0,y:0,w:g.width,h:g.height},at:$,focus:m};K(l,t.tone?hs(fs(fa(ds(g),M,b,p)),t.tone):Bn(Qc(g,M,b,p))),f=d}let h=D(e,`${t.stem}.tune.conf`);return K(h,[`background-image = ${l.startsWith(`${i}/`)?`~${l.slice(i.length)}`:l}`,`background-image-fit = ${f?"cover":"contain"}`,`background-image-position = ${o}`,`background-image-opacity = ${a}`,""].join(`
315
+ `)),h}function Jm(e){let t=new Map;for(let[n,r]of Object.entries(ct(Se(e)).palettes)){let[,i,s]=/^([a-z.]+)_(\d+)$/.exec(r.active)??[];if(i&&s)t.set(n,{site:i,id:Number(s)})}return t}function VE(e){try{let t=Jn(new Uint8Array(da(e)));return t?{width:t.width,height:t.height}:void 0}catch{return}}function ba(e,t,n,r,i,s,o,a,u,c=Dn(n)){let l=Se(e),f=n.window??VE(D(l,n.fill))??la,d=Lm(r,f.width,f.height,s,c),h=jm(t,n.key,d,i.hue.color),g={...n,stem:h.stem,fill:h.fill,...Km(i.colors,i.hue,d),blur:s,window:f,...u?{cut:`${qc(t,n.key)}.cut.png`}:{}};if(d.coloring==="original")delete g.tone;else delete g.peak;if(u)K(D(l,`${qc(t,n.key)}.cut.png`),Ic(ds(r)));if(h.stem===n.stem)return g;el(l,h.files);let b=tl(l,n);Fs(l,g,Dn(n)===c?b:{...b,opacity:void 0},o,a);let p=D(l,`${n.stem}.off.conf`);if(Vc(p))RE(p,D(l,`${g.stem}.off.conf`));return g}function nl(e,t){let n=Se(e),r=ct(n),i=new Set,s=[];for(let{name:o,picture:a}of t){let u=r.palettes[o],c=u?.pictures.findIndex((f)=>f.key===a.key)??-1,l=u?.pictures[c];if(!u||!l)continue;if(u.pictures[c]=a,i.add(o),l.stem!==a.stem)s.push(l.stem)}if(i.size===0)return;Ei(n,r,[...i]);for(let o of s)Dc(n,o)}function qm(e,t,n){return e.replace(/^background-image-opacity = (\S+)$/m,(r,i)=>Number(i)===t?`background-image-opacity = ${n}`:r)}function zm(e,t,n){let r=D(e,`${t.stem}.tune.conf`),i=Xn(r);if(i!==void 0)K(r,qm(i,t.opacity,n));return{...t,opacity:n}}function YE(e,t,n,r){if(n.tone===r.color)return zm(e,n,r.opacity);let i=Wm(e,n.stem).filter((a)=>a.endsWith(".png")).map((a)=>{let u=new Uint8Array(da(D(e,a)));return[a,xg(u,r.color)??hs(ds(At(u)),r.color)]}),s=(a)=>i.find(([u])=>u===a)?.[1]??new Uint8Array,o=`${En(t)}.${Pm("sha1").update(n.key).update(s(`${n.stem}.png`)).update(s(n.fill)).digest("hex").slice(0,8)}`;el(e,i.map(([a,u])=>[o+a.slice(n.stem.length),u]));for(let a of["tune","off"]){let u=Xn(D(e,`${n.stem}.${a}.conf`));if(u!==void 0)K(D(e,`${o}.${a}.conf`),qm(u.split(n.stem).join(o),n.opacity,r.opacity))}return{...n,stem:o,fill:o+n.fill.slice(n.stem.length),opacity:r.opacity,tone:r.color}}function Nm(e,t){if(Dn(e)==="original")return e.peak!==void 0&&ga(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=Se(e),r=ct(n),i=[],s=[];for(let[o,a]of Object.entries(r.palettes)){let u=t.get(o);if(!u||!a.pictures.some((c)=>Nm(c,u)))continue;a.pictures=a.pictures.map((c)=>{if(!Nm(c,u))return c;let l=Dn(c)==="original"?zm(n,c,ga(u.colors,c.peak)):YE(n,o,c,u.hue);if(l.stem!==c.stem)s.push(c.stem);return l}),i.push(o)}if(i.length>0){Ei(n,r,i);for(let o of s)Dc(n,o)}return i}function Jt(e){let{slot:t,color:n,opacity:r}=yi({name:e.name,background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi,waived:e.waive},e.signatureSlots);return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},...e.lead?{lead:!0}:{},order:e.order,ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},...e.role==="default"?{default:!0}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,signature:e.signature,signatureSlots:e.signatureSlots,ansi:e.ansi,gate:Gn(e),...e.waive.length>0?{waived:e.waive}:{},backdrop:{slot:t,color:n,opacity:r},...e.pictures?{pictures:e.pictures}:{}}}function Mn(e){return{name:e.name,...e.base?{base:e.base}:{},group:e.group,...e.native?{native:e.native}:{},...e.nativeNames?{nativeNames:e.nativeNames}:{},lead:e.lead===!0,order:e.order,...e.default?{role:"default"}:{},ansiSource:e.ansiSource,...e.booru?{booru:e.booru}:{},...e.booruSites?{booruSites:e.booruSites}:{},background:e.background,foreground:e.foreground,cursor:e.cursor,selectionBackground:e.selection,ansi:e.ansi,signature:e.signature,signatureSlots:e.signatureSlots,ghostty:{iconGhost:e.cursor,iconScreen:[e.cursor,e.selection,e.background]},waive:e.waived??[],...e.pictures?{pictures:e.pictures}:{}}}var QE=6,ZE=["ansi1","ansi2","ansi4","ansi3","ansi5","ansi6"];function wa(e){let t=(s)=>s.startsWith("ansi")?e.ansi[Number(s.slice(4))]:s==="foreground"?e.foreground:s==="cursor"?e.cursor:s==="selection"?e.selection:void 0,n=(s)=>s.startsWith("ansi")?`ansi${Number(s.slice(4))%8}`:s,r=new Set,i=[];for(let s of["foreground",...e.signatureSlots,...ZE]){let o=t(s);if(i.length===QE||!o||r.has(n(s))||i.includes(o))continue;r.add(n(s)),i.push(o)}return i}function Xe(e){return e.filter((t)=>t.default!==!0)}function Ts(){return{version:et.version,gate:bt,placement:vn,palettes:[]}}function XE(e){let[t]=e;if(!t)throw Error("manifest needs at least one theme");return{...Ts(),palettes:e.map(Jt)}}var rl={id:"meta",emitShared(e){return[{path:"manifest.json",content:`${JSON.stringify(XE(e),null,2)}
316
+ `}]}};import{existsSync as sv,readdirSync as ep,readFileSync as ov}from"node:fs";import{basename as tp,join as Hs}from"node:path";import{existsSync as DE,readFileSync as Ym}from"node:fs";import{homedir as Qm}from"node:os";import{isAbsolute as Zm,join as Hr,resolve as ev}from"node:path";var ee="official",an="ttheme-market.json",Mi="ttheme-market",tv=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,nv=/^[\w.-]{1,100}$/,rv=/^\w[\w.+/-]{0,199}$/;function tr(e){return Hr(e,"ttheme","installed.json")}function st(e){return e??[ee]}function Si(e){try{let{markets:t}=JSON.parse(Ym(tr(e),"utf8"));return st(Array.isArray(t)?t.filter((n)=>typeof n==="string"):void 0)}catch{return[ee]}}function xe(e){return Zm(e)}function yt(e){return e!==ee&&!xe(e)}function er(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(0,t):e}function il(e){let t=e.indexOf("#");return yt(e)&&t>=0?e.slice(t+1):void 0}function Ii(e,t){return er(e)===er(t)}function nr(e,t){return!xe(e)&&(t?.[e]??e===ee)}function iv(e){return!rv.test(e)||e.includes("..")||e.includes("//")||/(?:[./]|\.lock)$/.test(e)}function rr(e,t=process.cwd()){if(e===ee)return ee;if(e==="~"||e.startsWith("~/"))return Hr(Qm(),e.slice(1));if(e.startsWith(".")||Zm(e))return ev(t,e);let[n="",r,...i]=e.split("#"),[s,o,...a]=n.replace(/^https:\/\/github\.com\//,"").replace(/\.git$/,"").split("/");if(!s||!tv.test(s)||!o||!nv.test(o)||a.length>0||i.length>0||r!==void 0&&iv(r))throw Error(`${e} is not a market — give a repository (alice/ttheme-dust, #v1 pins a tag or branch) or a path (./my-market)`);return`${s.toLowerCase()}/${o}${r===void 0?"":`#${r}`}`}function Xm(e){let t=il(e)?.split("/").map(encodeURIComponent).join("/")??"HEAD";return`https://raw.githubusercontent.com/${er(e)}/${t}/${an}`}function Dm(e){return e.slice(0,e.indexOf("/"))}function sl(e){return Hr(e,"ttheme","markets")}function qt(e,t){return Hr(sl(e),`${er(t).replace("/","--")}.json`)}function $a(e){return Hr(e,"ttheme","market")}function ol(e,t){return Hr($a(e),t)}function al(e,t){if(typeof e!=="string"||typeof t!=="string")return'needs an "owner" (the GitHub handle) and a "name"';return on(`${e}@${t}/x`)}function Et({owner:e,name:t}){return`${e}@${t}`}function un(e){let t=Hr(e,an);if(!DE(t))throw Error(`${e} has no ${an} — \`ttheme market init ${e}\` makes one`);let n;try{n=JSON.parse(Ym(t,"utf8"))}catch{throw Error(`${t} is not valid JSON`)}let r=al(n.owner,n.name);if(r)throw Error(`${t} ${r}`);return{owner:n.owner,name:n.name}}function ye(e){if(e===ee)return"the ttheme catalog";if(!xe(e))return`github.com/${e}`;let t=Qm();return e===t||e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}var Sn="tt1:",np=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)];function xr(e,t=!0){return Si(e).filter(xe).flatMap((n)=>{try{let r=un(n);return[{dir:n,...r,id:Et(r)}]}catch(r){if(t)process.stderr.write(`ttheme: skipping the market at ${n} — ${r.message}
317
+ `);return[]}})}function ka(e){return Hs(e,"palettes")}function ir(e){let t=ka(e);if(!sv(t))return[];let n=[],r=[];for(let i of ep(t,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){if(i.name.startsWith("."))continue;if(i.isDirectory()){for(let s of ep(Hs(t,i.name)).sort())if(s.endsWith(".toml"))n.push({path:Hs(t,i.name,s),slug:tp(s,".toml"),catalog:i.name})}else if(i.name.endsWith(".toml"))r.push({path:Hs(t,i.name),slug:tp(i.name,".toml")})}return[...n,...r]}function xs(e,t){let n=t.get(e.slug);if(n)return`${e.slug} is also ${n.catalog?`in ${n.catalog}`:"outside a catalog"} — a palette name is used once in a market`;let r=e.catalog===void 0?void 0:Ns(e.catalog);return r?`the catalog folder ${JSON.stringify(e.catalog)} ${r}`:void 0}function ul(e,t){let n=Me(t);if(!n)throw Error(`${t} is an official palette — yours are named <you>@<market>/<palette>`);let r=xr(e,!1).find((s)=>s.id===n);if(!r)throw Error(`${n} is not a local market — \`ttheme market add <dir>\` adds the folder that holds it`);let i=$i(t);return ir(r.dir).find((s)=>s.slug===i)?.path??Hs(ka(r.dir),`${i}.toml`)}function av(e,t){let n=new Map;for(let i of t)if(i.group!==Ms&&!n.has(i.group)){let s=t.find((o)=>o.group===i.group&&o.lead)?.name??"";n.set(i.group,{name:i.group,...i.native?{native:i.native}:{},lead:s})}let r=new Map(t.filter((i)=>!i.default&&!Me(i.name)).map((i)=>[i.name,{group:i.group,order:i.order}]));return{name:e,groups:n,bases:r,open:!0}}function vt(e,t,n){let r=$i(e),{native:i,...s}=Uc(`${r}.toml`,t,av(r,n)),o=Me(e);return{...s,name:e,...o?{group:o,lead:!1}:{}}}function sr(e,t,n,r=!0){let i=new Map;return ir(e).flatMap((s)=>{try{let o=xs(s,i);if(o)throw Error(o);i.set(s.slug,s);let a=Jt(vt(`${t}/${s.slug}`,ov(s.path,"utf8"),n));return[s.catalog?{...a,catalog:s.catalog}:a]}catch(o){if(r)process.stderr.write(`ttheme: skipping ${s.path} — ${o.message}
318
+ `);return[]}})}function ya(e,t,n=!0){return xr(e,n).flatMap(({dir:r,id:i})=>sr(r,i,t,n))}function cl(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 rp(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 ip(e,t){return t.length===0?e:`${e.replace(/\n*$/,`
319
319
  `)}${t.map((n)=>`
320
- ${ep(n).join(`
320
+ ${rp(n).join(`
321
321
  `)}
322
- `).join("")}`}function al(e){let t=["[meta]",`name = ${qe($i(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("",...ep(n));return`${t.join(`
322
+ `).join("")}`}function ll(e){let t=["[meta]",`name = ${qe($i(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("",...rp(n));return`${t.join(`
323
323
  `)}
324
- `}class np{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 rp{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 ip(e){let t=new np;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(Dm.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<<ic.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(X.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:kt.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${Sn}${t.done()}`}function sp(e){if(!e.startsWith(Sn))throw Error(`a share code starts with ${Sn}`);let t=e.slice(Sn.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 rp(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(($)=>Dm[$]??`slot${$}`),l=n.str(),f=n.str(),d=n.str(),h=n.str(),g=n.u16(),b=n.str(),p=ic.filter(($,E)=>g&1<<E),m=Array.from({length:n.u8()},()=>{let $=X[n.u8()]?.key??"unknown",E=n.u32(),M=n.u16(),w=n.u8(),S=n.u16();return{site:$,id:E,...M===1?{size:"fill"}:M>1?{size:M}:{},...w>0?{position:kt[w-1]??"unknown"}:{},...S>0?{opacity:(S-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Ht))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...f?{group:f}:{},...d?{ansiSource:d}:{},...h?{booru:h}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...p.length>0?{waive:p,reason:b}:{},...m.length>0?{pictures:m}:{}}}function ul(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function cl(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 op(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(qe).join(", ")}]`)}function As(e){let t=Gn(Mn(e)),n=new Set(e.waived??[]),r=Math.max(...bt.map((i)=>i.label.length));return bt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var cp="https://kecan0406.github.io/ttheme/manifest.json",iv=20000;function qt(e){return up(e,"ttheme","catalog.json")}function ya(e,t){K(qt(e),`${JSON.stringify(t,null,2)}
325
- `)}function We(e,t=!0){let n=Si(e),r=qt(e),i=Hs();if(n.includes(ee)){if(!ap(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=cn(ll(r,"utf8"))}let s=n.filter(yt).flatMap((o)=>sv(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function or(e,t){return fl(ll(Jt(e,t),"utf8"))}function Ni(e,t){return Et({owner:Vm(e),name:t.name})}function sv(e,t,n){let r=Jt(e,t);if(!ap(r))return[];try{let i=or(e,t);return Ea(i,Ni(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
- `);return[]}}function fl(e){let t=cn(e),n=il(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>Me(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function Ea(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function cn(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=lp(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function lp(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=on(e.name)??(e.base===void 0?void 0:on(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Ht(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.catalog??"-",e.ansiSource]){let r=typeof n==="string"?Ns(n):"has a field that is not text";if(r)return r}return}function fp(e){return up(e,"ttheme","kept.json")}function va(e,t){K(fp(e),`${JSON.stringify({palettes:t},null,2)}
327
- `)}function In(e){try{let{palettes:t}=JSON.parse(ll(fp(e),"utf8"));return Array.isArray(t)?t.filter((n)=>lp(n)===void 0):[]}catch{return[]}}function je(e,t,n=!0){let r=[...t.palettes,...ka(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...In(e).filter((s)=>!i.has(s.name))]}}function ln(e){return je(e,We(e))}class Ma extends Error{}class Sa extends Error{}async function Ls(e,t,n=iv,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 Ma(`nothing at ${e}`);if(i.status===403||i.status===429)throw new Sa(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function Cs(e){let t=new Set(e.waived??[]),n=e.gate??Gn(Mn(e));return bt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function Ar(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${dl(e,[t])}`);return n}function dl(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 dp(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 hp(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 gp(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as HM}from"node:child_process";import{existsSync as of,mkdirSync as qb,readdirSync as TM,readFileSync as uf,rmSync as zb}from"node:fs";import{basename as xM,join as jr,relative as AM}from"node:path";import{existsSync as Vl,readFileSync as Nb,rmSync as Zl}from"node:fs";import{homedir as dn}from"node:os";import{join as Ja}from"node:path";var ov=["black","red","green","yellow","blue","magenta","cyan","white"];function mp(e,t){return[e,...ov.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
- `)}var hl={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...ar(e),"","[colors.primary]",`background = '${e.background}'`,`foreground = '${e.foreground}'`,"","[colors.cursor]",`cursor = '${e.cursor}'`,`text = '${e.background}'`,"","[colors.selection]",`background = '${e.selectionBackground}'`,`text = '${e.foreground}'`,"",mp("[colors.normal]",e.ansi.slice(0,8)),mp("[colors.bright]",e.ansi.slice(8,16))].join(`
329
- `);return[{path:`alacritty/themes/${_(e.name)}.toml`,content:t}]}};var gl={id:"ghostty",emit(e){let t=[...ar(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"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/${_(e.name)}`,content:t}]}};function ur(e){let[t,n,r]=ve(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function bp(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,ur(t)])),"Background Color":ur(e.background),"Bold Color":ur(e.foreground),"Cursor Color":ur(e.cursor),"Cursor Text Color":ur(e.background),"Foreground Color":ur(e.foreground),"Selected Text Color":ur(e.foreground),"Selection Color":ur(e.selectionBackground)}}function pp(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function wp(e,t,n,r,i=!1){let s=(u,c)=>({Name:`ttheme · ${c}`,Guid:_(c),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...pp(t.get(u.name)),...bp(u)}),o={Name:"ttheme · default",Guid:_("default"),"Dynamic Profile Parent GUID":r,...pp(void 0)},a=[...n?[s(n,"default")]:i&&r?[o]:[],...e.map((u)=>s(u,u.name))];return`${JSON.stringify({Profiles:a},null,2)}
331
- `}function av(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 ml={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(bp(e)).map(([n,r])=>av(n,r)),"</dict>","</plist>",""].join(`
333
- `);return[{path:`iterm2/${_(e.name)}.itermcolors`,content:t}]}};var pl={id:"kitty",emit(e){let t=[...ar(e),`background ${e.background}`,`foreground ${e.foreground}`,`cursor ${e.cursor}`,`cursor_text_color ${e.background}`,`selection_background ${e.selectionBackground}`,`selection_foreground ${e.foreground}`,...e.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
334
- `);return[{path:`kitty/themes/${_(e.name)}.conf`,content:t}]}};function $p(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 Nn(e,t){return[`[${e}]`,`Color=${ve(t).join(",")}`,""]}function uv(e){let t=(n)=>rt(n,e.background,0.5);return[...ar(e),"",...Nn("Background",e.background),...Nn("BackgroundFaint",e.background),...Nn("BackgroundIntense",e.background),...e.ansi.slice(0,8).flatMap((n,r)=>[...Nn(`Color${r}`,n),...Nn(`Color${r}Faint`,t(n)),...Nn(`Color${r}Intense`,e.ansi[r+8])]),...Nn("Foreground",e.foreground),...Nn("ForegroundFaint",t(e.foreground)),...Nn("ForegroundIntense",e.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${e.name}`,"Opacity=1","Wallpaper=",""].join(`
336
- `)}var bl={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(e){return[{path:`konsole/${_(e.name)}.colorscheme`,content:uv(e)}]}};var kp=44,_t=[{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 Ia(e){let t=_t.length;return _t[(e%t+t)%t]}function yp(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 cv,writeSync as lv}from"node:fs";import{ReadStream as fv}from"node:tty";var Pi=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function gt(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function wl(e,t){return`\x1B]${Pi[e]};${t}\x1B\\`}function $l(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":wl(r,n)).join("")}function dv(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function hv(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 gv(e){return`#${e.slice(e.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function Ep(e,t=[...e.keys()],n=!1){return t.map((r)=>{let i=e.get(r);return i?`\x1B]${r};${n?gv(i):i}\x1B\\`:dv(r)}).join("")}function vp(e,t){return`\x1B]50;ColorScheme=${e};UseCustomCursorColor=true;customCursorColor=${t}\x07`}function mv(e=Pi){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function pv(e){return e.includes("\x1B[0n")}async function Mp(e=Pi){let t,n;try{t=cv("/dev/tty","r+"),n=new fv(t),n.setRawMode(!0)}catch{return new Map}try{lv(t,mv(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),pv(r))clearTimeout(s),i()})}),hv(r)}finally{n.setRawMode(!1),n.destroy()}}function zt(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 Yt={ghostty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},warp:{links:!1,pictures:!0,bands:!0,files:!1,moves:!1,layers:!1,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0}};function Sp(e){return Yt[zt(e)].links}function Ip(e){return Yt[zt(e)].pictures&&!e.TMUX}function Np(e){return Yt[zt(e)].bands}function Pp(e){return Yt[zt(e)].files}function Op(e){return Yt[zt(e)].layers}function Rp(e){return Yt[zt(e)].moves}var Oi="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function cr(e,t){let n=zt(e),r=Yt[n];if(!t||gt(e)||e.TMUX||!r.paints)return;let i=r.repaint??Pi.map((o,a)=>a),s=Pi.filter((o,a)=>i.includes(a));return{slots:i,paint:(o)=>$l(o,i),wear:(o,a)=>!r.schemes?$l(o):a.includes(n)?vp(_(o.name),o.cursor):void 0,saved:()=>Mp(s),restore:(o)=>Ep(o,s,r.hex===!0)}}var Mt=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var bv=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"}],Gs=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",shell:!0},{name:"next",args:[],about:"Advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"Make a palette the one new tabs open with",section:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{name:"pin",args:["[directory]"],about:"Pick a palette for this directory, everything below it or its repository — cd in repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:["[directory]"],about:"Drop a pin — this directory's, every one below it, or the one above that paints it",section:"tab",shell:!0},{name:"pins",args:[],about:"Map every pinned directory as a tree in its palette's colors, and the pin that covers this one",section:"tab",shell:!0},{name:"config",args:[],about:"Edit settings in $EDITOR — they apply in new tabs",section:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{name:"list",args:["[query]"],about:"Show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"Print the matches as JSON: name, group, catalog, installed"}}},{name:"add",args:["<palette...>"],about:"Install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, from blank in the palette editor — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"Open the editor on this palette's colors instead of blank"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in the palette editor — the contrast gate advises, never refuses",section:"own"},{name:"check",args:["<palette>"],about:"Measure a palette against the contrast gate and suggest colors that pass",section:"own",flags:{fix:{type:"boolean",about:"Write the suggested colors into your palette"}}},{name:"share",args:["<palette>"],about:"Print a share code — ttheme add <code> installs it anywhere, pictures included",section:"own"},{name:"init",args:[],about:"Install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Accept every default without prompting"}}},{name:"uninstall",args:[],about:"Take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Remove without asking"}}},{name:"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:Mt,about:"Rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"Pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>","[picture]"],about:"Show one of a palette's saved backgrounds, remove one, draw one in its palette's tone or its own colors, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"flatten",args:["<source>","<out>","<background>","<opacity>","[canvas]","[place]"],about:"Lay a picture on a background color at an opacity, placed on a canvas when given one, for Warp, which fades the window instead — preview calls this",section:"setup",hidden:!0},{name:"bake",args:["<source>","<out>","<canvas>","<place>"],about:"Place a picture on a transparent canvas the way sips bakes preview's tuning — preview in Warp calls this",section:"setup",hidden:!0},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function _s(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function kl(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var wv=[["npx @kecan0406/ttheme init -y","Wire the terminals found here, no prompts"],["ttheme add homura madoka","Install two palettes"],["ttheme use homura","Paint this tab with one"],["ttheme list --json madoka","The madoka series as JSON"],["ttheme market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function Ws(e,t=!1){let n=Gs.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=bv.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",...kl(o.map((u)=>[_s(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
337
- `)}let s=Math.max(...n.map((o)=>_s(o).length));return["Usage: ttheme <command>","",ot.description,...r.flatMap(({section:o,title:a})=>["",a,...kl(n.filter((u)=>u.section===o).map((u)=>[_s(u),u.about]),s)]),"","Examples",...kl(wv),"",...i].join(`
338
- `)}import{readFileSync as Fp}from"node:fs";import{join as Hp}from"node:path";var yl="# ttheme begin",El="# ttheme end",Ri=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function lr(e,t){let n=`${yl}
324
+ `}class sp{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 op{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 ap(e){let t=new sp;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(np.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<<ac.indexOf(i),0)),t.str(e.waive&&e.waive.length>0?e.reason:"");let n=e.pictures??[];t.u8(n.length);for(let r of n)t.u8(X.findIndex((i)=>i.key===r.site)),t.u32(r.id),t.u16(r.size===void 0?0:r.size==="fill"?1:r.size),t.u8(r.position===void 0?0:kt.indexOf(r.position)+1),t.u16(r.opacity===void 0?0:Math.round(r.opacity*1000)+1);return`${Sn}${t.done()}`}function up(e){if(!e.startsWith(Sn))throw Error(`a share code starts with ${Sn}`);let t=e.slice(Sn.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 op(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(($)=>np[$]??`slot${$}`),l=n.str(),f=n.str(),d=n.str(),h=n.str(),g=n.u16(),b=n.str(),p=ac.filter(($,E)=>g&1<<E),m=Array.from({length:n.u8()},()=>{let $=X[n.u8()]?.key??"unknown",E=n.u32(),M=n.u16(),w=n.u8(),S=n.u16();return{site:$,id:E,...M===1?{size:"fill"}:M>1?{size:M}:{},...w>0?{position:kt[w-1]??"unknown"}:{},...S>0?{opacity:(S-1)/1000}:{}}});if(n.end(),![i,s,o,a,...u].every(Ht))throw Error("the share code holds a color that is not one");return{name:r,...l?{base:l}:{},...f?{group:f}:{},...d?{ansiSource:d}:{},...h?{booru:h}:{},signature:c,background:i,foreground:s,cursor:o,selection:a,ansi:u,...p.length>0?{waive:p,reason:b}:{},...m.length>0?{pictures:m}:{}}}function fl(e){return{background:e.background,foreground:e.foreground,cursor:e.cursor,selection:e.selectionBackground,ansi:e.ansi}}function dl(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 cp(e,t){return e.replace(/^(signature\s*=\s*)\[[^\]]*\]/m,(n,r)=>`${r}[${t.map(qe).join(", ")}]`)}function As(e){let t=Gn(Mn(e)),n=new Set(e.waived??[]),r=Math.max(...bt.map((i)=>i.label.length));return bt.map((i,s)=>{let o=t[s],a=n.has(i.rule)||Number.isNaN(o)||(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),u=i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:"",c=Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2);return` ${a?"✓":"✗"} ${i.label.padEnd(r)} ${c.padStart(6)} ${u}${n.has(i.rule)?" waived":""}`})}var dp="https://kecan0406.github.io/ttheme/manifest.json",uv=20000;function zt(e){return fp(e,"ttheme","catalog.json")}function Ea(e,t){K(zt(e),`${JSON.stringify(t,null,2)}
325
+ `)}function We(e,t=!0){let n=Si(e),r=zt(e),i=Ts();if(n.includes(ee)){if(!lp(r))throw Error(`no catalog at ${r} — run \`ttheme init\` first`);i=cn(hl(r,"utf8"))}let s=n.filter(yt).flatMap((o)=>cv(e,o,t));return{...i,palettes:[...i.palettes,...s]}}function or(e,t){return gl(hl(qt(e,t),"utf8"))}function Ni(e,t){return Et({owner:Dm(e),name:t.name})}function cv(e,t,n){let r=qt(e,t);if(!lp(r))return[];try{let i=or(e,t);return va(i,Ni(t,i))}catch(i){if(n)process.stderr.write(`ttheme: skipping ${r} — ${i.message}
326
+ `);return[]}}function gl(e){let t=cn(e),n=al(t.owner,t.name);if(n)throw Error(`market index ${n}`);let r=t.palettes.find((i)=>Me(i.name)!==void 0);if(r)throw Error(`market index names ${r.name} with its market — its entries are bare palette names`);return t}function va(e,t){return e.palettes.map(({lead:n,default:r,native:i,...s})=>({...s,name:`${t}/${s.name}`,group:t}))}function cn(e){let t;try{t=JSON.parse(e)}catch{throw Error("catalog is not valid JSON")}let n=t;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes){let i=hp(r);if(i)throw Error(`catalog entry ${JSON.stringify(r?.name)} ${i}`)}return n}function hp(e){if(typeof e?.name!=="string"||!Array.isArray(e.ansi)||e.ansi.length!==16)return"is missing name or its 16 ANSI colors";let t=on(e.name)??(e.base===void 0?void 0:on(e.base));if(t)return t;if(![e.background,e.foreground,e.cursor,e.selection,...e.ansi].every((n)=>typeof n==="string"&&Ht(n)))return'holds a color that is not "#rrggbb"';for(let n of[e.group,e.native??"-",e.catalog??"-",e.ansiSource]){let r=typeof n==="string"?Ns(n):"has a field that is not text";if(r)return r}return}function gp(e){return fp(e,"ttheme","kept.json")}function Ma(e,t){K(gp(e),`${JSON.stringify({palettes:t},null,2)}
327
+ `)}function In(e){try{let{palettes:t}=JSON.parse(hl(gp(e),"utf8"));return Array.isArray(t)?t.filter((n)=>hp(n)===void 0):[]}catch{return[]}}function je(e,t,n=!0){let r=[...t.palettes,...ya(e,t.palettes,n)],i=new Set(r.map((s)=>s.name));return{...t,palettes:[...r,...In(e).filter((s)=>!i.has(s.name))]}}function ln(e){return je(e,We(e))}class Sa extends Error{}class Ia extends Error{}async function Ls(e,t,n=uv,r){let i;try{let s=AbortSignal.timeout(n);i=await fetch(e,{signal:r?AbortSignal.any([s,r]):s})}catch(s){throw Error(`cannot reach ${e} — ${s instanceof Error?s.message:String(s)}`)}if(i.status===404)throw new Sa(`nothing at ${e}`);if(i.status===403||i.status===429)throw new Ia(`${new URL(e).host} is turning requests away for now (${i.status}) — try again in a minute`);if(!i.ok)throw Error(`${e} answered ${i.status}`);return t(await i.text())}function Cs(e){let t=new Set(e.waived??[]),n=e.gate??Gn(Mn(e));return bt.flatMap((r,i)=>{let s=n[i];if(t.has(r.rule)||typeof s!=="number"||Number.isNaN(s))return[];if(r.min!==void 0&&s<r.min)return[`${r.label} ${s} < ${r.min}`];if(r.max!==void 0&&s>r.max)return[`${r.label} ${s} > ${r.max}`];return[]})}function Ar(e,t){let n=e.find((r)=>r.name===t);if(!n)throw Error(`no palette named ${t} in the catalog — ${ml(e,[t])}`);return n}function ml(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 mp(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 pp(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 bp(e,t){return e.booruSites?.[t]??(e.booru?[e.booru]:[])}import{execFileSync as LM}from"node:child_process";import{existsSync as uf,mkdirSync as Vb,readdirSync as CM,readFileSync as lf,rmSync as Yb}from"node:fs";import{basename as _M,join as jr,relative as GM}from"node:path";import{existsSync as Xl,readFileSync as Rb,rmSync as Dl}from"node:fs";import{homedir as dn}from"node:os";import{join as za}from"node:path";var lv=["black","red","green","yellow","blue","magenta","cyan","white"];function wp(e,t){return[e,...lv.map((n,r)=>`${n} = '${t[r]}'`),""].join(`
328
+ `)}var pl={id:"alacritty",limits:"no runtime color API (OSC only)",emit(e){let t=[...ar(e),"","[colors.primary]",`background = '${e.background}'`,`foreground = '${e.foreground}'`,"","[colors.cursor]",`cursor = '${e.cursor}'`,`text = '${e.background}'`,"","[colors.selection]",`background = '${e.selectionBackground}'`,`text = '${e.foreground}'`,"",wp("[colors.normal]",e.ansi.slice(0,8)),wp("[colors.bright]",e.ansi.slice(8,16))].join(`
329
+ `);return[{path:`alacritty/themes/${_(e.name)}.toml`,content:t}]}};var bl={id:"ghostty",emit(e){let t=[...ar(e),`background = ${e.background}`,`foreground = ${e.foreground}`,`cursor-color = ${e.cursor}`,`selection-background = ${e.selectionBackground}`,`selection-foreground = ${e.foreground}`,...e.ansi.map((n,r)=>`palette = ${r}=${n}`),"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/${_(e.name)}`,content:t}]}};function ur(e){let[t,n,r]=ve(e);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":t/255}}function kp(e){return{...Object.fromEntries(e.ansi.map((t,n)=>[`Ansi ${n} Color`,ur(t)])),"Background Color":ur(e.background),"Bold Color":ur(e.foreground),"Cursor Color":ur(e.cursor),"Cursor Text Color":ur(e.background),"Foreground Color":ur(e.foreground),"Selected Text Color":ur(e.foreground),"Selection Color":ur(e.selectionBackground)}}function $p(e){return e?{"Background Image Location":e.image,"Background Image Mode":e.cover?2:3,Blend:e.opacity}:{"Background Image Location":""}}function yp(e,t,n,r,i=!1){let s=(u,c)=>({Name:`ttheme · ${c}`,Guid:_(c),...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...$p(t.get(u.name)),...kp(u)}),o={Name:"ttheme · default",Guid:_("default"),"Dynamic Profile Parent GUID":r,...$p(void 0)},a=[...n?[s(n,"default")]:i&&r?[o]:[],...e.map((u)=>s(u,u.name))];return`${JSON.stringify({Profiles:a},null,2)}
331
+ `}function fv(e,t){return[` <key>${e}</key>`,"\t<dict>",...Object.entries(t).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
332
+ `)}var wl={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(kp(e)).map(([n,r])=>fv(n,r)),"</dict>","</plist>",""].join(`
333
+ `);return[{path:`iterm2/${_(e.name)}.itermcolors`,content:t}]}};var $l={id:"kitty",emit(e){let t=[...ar(e),`background ${e.background}`,`foreground ${e.foreground}`,`cursor ${e.cursor}`,`cursor_text_color ${e.background}`,`selection_background ${e.selectionBackground}`,`selection_foreground ${e.foreground}`,...e.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
334
+ `);return[{path:`kitty/themes/${_(e.name)}.conf`,content:t}]}};function Ep(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 Nn(e,t){return[`[${e}]`,`Color=${ve(t).join(",")}`,""]}function dv(e){let t=(n)=>it(n,e.background,0.5);return[...ar(e),"",...Nn("Background",e.background),...Nn("BackgroundFaint",e.background),...Nn("BackgroundIntense",e.background),...e.ansi.slice(0,8).flatMap((n,r)=>[...Nn(`Color${r}`,n),...Nn(`Color${r}Faint`,t(n)),...Nn(`Color${r}Intense`,e.ansi[r+8])]),...Nn("Foreground",e.foreground),...Nn("ForegroundFaint",t(e.foreground)),...Nn("ForegroundIntense",e.foreground),"[General]","Blur=false","ColorRandomization=false",`Description=ttheme · ${e.name}`,"Opacity=1","Wallpaper=",""].join(`
336
+ `)}var kl={id:"konsole",limits:"draws no OSC 4, so a tab repaints by switching color scheme",emit(e){return[{path:`konsole/${_(e.name)}.colorscheme`,content:dv(e)}]}};var vp=44,Gt=[{name:"Shell",lines:["«B4»~/code/demo«d» on «5»main«2» +2«3» ~1","«2»❯ «»git status -sb","«w»## «2»main«»...«1»origin/main«3» [ahead 1]","«1» M«» src/main.rs","«1»??«» notes.md","","«w»«2»❯ «»ls","«w»«B4»docs«» «B4»src«» «B4»tests«» Cargo.toml README.md","«w»","«2»❯ «»cargo test","«2» ✓«» parses config","«n»«1» ✗«» renders frame","«w»«1» ✗«» renders frame«d» expected «2»3«d», received «1»2","","«2»❯ «»echo «s»selected text«» «c» "]},{name:"Code",lines:["«d» 12 │ «5»import«» { readFile } «5»from «2»'node:fs/promises'","«d» 13 │","«d» 14 │ «8»// Read a palette and check its sixteen colors","«d» 15 │ «5»export async function «4»load«»(path: «6»string«») {","«d» 16 │ «5»const«» text = «5»await «4»readFile«»(path, «2»'utf8'«»)","«b» 17 «d»│ «5»const«» colors = «s»parse(text)«».colors ?? {}","«d» 18 │ «5»if«» (colors.ansi.length !== «3»16«») {","«d» 19 │ «5»throw new «6»Error«»(«2»'needs 16 colors'«»)","«d» 20 │ }","«d» 21 │ «5»return«» { ...colors, ratio: «c»4«3».5«» }","«d» 22 │ }"]},{name:"Diff",lines:["«2»❯ «»git diff --stat","«» src/theme.ts | 3 «2»++«1»-","«2»❯ «»git diff","«b»diff --git a/src/theme.ts b/src/theme.ts","«6»@@ -16,3 +16,4 @@«» export async function load(","«» const text = await readFile(path, 'utf8')","«1»- const colors = parse(text).colors","«2»+ const colors = parse(text).colors ?? {}","«2»+ const ratio = contrast(colors)","«2»❯ «»git log --oneline --graph -4","«3»* 3f2a1c9 («B6»HEAD -> «B2»main«3»)«» Check contrast on load","«3»* 9b04e7d«» Merge branch ansi","«1»|«5»\\","«1»| «5»* «3»51cd0aa«» Add sixteen ANSI colors","«1»|«5»/","«3»* 07be2f1 («B1»origin/main«3», «B3»tag: v1.0«3»)«» Read palette files"]},{name:"Logs",lines:["«2»❯ «»npm run dev","«B2» VITE v6.2.0«d» ready in «b»412«d» ms","«2» ➜ «b»Local«»: «6»http://localhost:5173/","«d»10:42:07 «2»INFO «» GET /api/palettes «2»200«d» 12 ms","«d»10:42:08 «2»INFO «» GET /api/themes/kita «2»200«d» 8 ms","«d»10:42:09 «3»WARN «» slow query: palettes «3»812 ms","«d»10:42:10 «4»DEBUG«» cache hit themes/kita","«d»10:42:11 «B1»ERROR«» POST /api/share «1»500«d» 41 ms","«1» Error«»: read ECONNRESET","«d» at «»TCP.onStreamRead «d»(«6»node:net:216:20«d»)","«d» at «»share «d»(«6»src/share.ts:48:11«d»)","«d»10:42:12 «2»INFO «» retry 1/3 in 200 ms"]},{name:"Monitor",lines:["«6» 1 «b»[«2»|||||||||||||«1»||«» 42.1%«b»]«6» Tasks: «b»128«», 412 thr; «B2»3«» running","«6» 2 «b»[«2»||||||«4»||«» 21.4%«b»]«6» Load average: «b»1.42 «»1.18 0.97","«6» 3 «b»[«2»||||||||||||||«1»|||||«» 71.0%«b»]«6» Uptime: «b»3 days, 04:12:55","«6» 4 «b»[«2»||«» 7.9%«b»]","«6» Mem«b»[«2»||||||||«4»||«3»||«» 6.21G/16.0G«b»]","«6» Swp«b»[«1»|«» 0.10G/2.00G«b»]","","«K2» PID USER CPU% MEM% TIME+ Command ","«s» 4127 kec 38.2 2.1 3:12.44 node dev.js ","«» 2210 kec 12.0 4.8 1:02.10 «b»ghostty","«» 3301 kec 4.4 1.2 0:05.61 «b»zsh","«» 812 «1»root«» 3.1 0.3 0:44.02 «d»kernel_task","«» 167 «1»root«» 0.9 0.1 0:12.80 «d»WindowServer"]}];function Na(e){let t=Gt.length;return Gt[(e%t+t)%t]}function Mp(e,t){let n=e.split("«"),r=n[0]?[[n[0],""]]:[];for(let i of n.slice(1)){let s=i.indexOf("»"),o=i.slice(0,s),a=i.slice(s+1);if(o==="w"||o==="n"){if(o==="w"!==t>=44)return}if(a)r.push([a,o==="w"||o==="n"?"":o])}return r}import{openSync as hv,writeSync as gv}from"node:fs";import{ReadStream as mv}from"node:tty";var Pi=["11","10","12","17",...Array.from({length:16},(e,t)=>`4;${t}`)];function gt(e=process.env){return Boolean(e.NO_COLOR)||e.TERM==="dumb"}function yl(e,t){return`\x1B]${Pi[e]};${t}\x1B\\`}function El(e,t){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi].map((n,r)=>t&&!t.includes(r)?"":yl(r,n)).join("")}function pv(e){return`\x1B]${e.startsWith("4;")?`104;${e.slice(2)}`:`1${e}`}\x1B\\`}function bv(e){let t=new Map;for(let n of e.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,s]=r??[];if(i&&s)t.set(i,s)}return t}function wv(e){return`#${e.slice(e.indexOf(":")+1).split("/").slice(0,3).map((n)=>n.slice(0,2).padStart(2,"0")).join("")}`}function Sp(e,t=[...e.keys()],n=!1){return t.map((r)=>{let i=e.get(r);return i?`\x1B]${r};${n?wv(i):i}\x1B\\`:pv(r)}).join("")}function Ip(e,t){return`\x1B]50;ColorScheme=${e};UseCustomCursorColor=true;customCursorColor=${t}\x07`}function $v(e=Pi){return`${e.map((t)=>`\x1B]${t};?\x1B\\`).join("")}\x1B[5n`}function kv(e){return e.includes("\x1B[0n")}async function Np(e=Pi){let t,n;try{t=hv("/dev/tty","r+"),n=new mv(t),n.setRawMode(!0)}catch{return new Map}try{gv(t,$v(e));let r="";return await new Promise((i)=>{let s=setTimeout(i,120);n.on("data",(o)=>{if(r+=o.toString(),kv(r))clearTimeout(s),i()})}),bv(r)}finally{n.setRawMode(!1),n.destroy()}}function Mt(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 Vt={ghostty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},kitty:{links:!0,pictures:!0,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},iterm2:{links:!0,pictures:!0,bands:!0,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1]},wezterm:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},alacritty:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"windows-terminal":{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},konsole:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0,repaint:[0,1],hex:!0,schemes:!0},foot:{links:!0,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},"terminal-app":{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0},warp:{links:!1,pictures:!0,bands:!0,files:!1,moves:!1,layers:!1,paints:!1},unknown:{links:!1,pictures:!1,bands:!1,files:!0,moves:!0,layers:!0,paints:!0}};function Pp(e){return Vt[Mt(e)].links}function Rp(e){return Vt[Mt(e)].pictures&&!e.TMUX}function Op(e){return Vt[Mt(e)].bands}function Fp(e){return Vt[Mt(e)].files}function Tp(e){return Vt[Mt(e)].layers}function Hp(e){return Vt[Mt(e)].moves}var Ri="\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H";function cr(e,t){let n=Mt(e),r=Vt[n];if(!t||gt(e)||e.TMUX||!r.paints)return;let i=r.repaint??Pi.map((o,a)=>a),s=Pi.filter((o,a)=>i.includes(a));return{slots:i,paint:(o)=>El(o,i),wear:(o,a)=>!r.schemes?El(o):a.includes(n)?Ip(_(o.name),o.cursor):void 0,saved:()=>Np(s),restore:(o)=>Sp(o,s,r.hex===!0)}}var St=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp","konsole"];var yv=[{section:"tab",title:"This tab"},{section:"startup",title:"New tabs"},{section:"catalog",title:"Palettes"},{section:"own",title:"Your own"},{section:"setup",title:"Setup"},{section:"support",title:"Support"}],Gs=[{name:"preview",args:[],about:"Browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",start:"Try every palette live — enter keeps the one you land on",shell:!0},{name:"use",args:["<palette>"],about:"Paint this tab — a unique prefix works: ttheme use ho",section:"tab",start:"Paint this tab with one — ttheme use homura",shell:!0},{name:"next",args:[],about:"Advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"Make a palette the one new tabs open with",section:"startup"},{name:"on",args:[],about:"Wear the default palette in new tabs again",section:"startup"},{name:"off",args:[],about:"Take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"startup"},{name:"pin",args:["[directory]"],about:"Pick a palette for this directory, everything below it or its repository — cd in repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:["[directory]"],about:"Drop a pin — this directory's, every one below it, or the one above that paints it",section:"tab",shell:!0},{name:"pins",args:[],about:"Map every pinned directory as a tree in its palette's colors, and the pin that covers this one",section:"tab",shell:!0},{name:"config",args:[],about:"Edit settings in $EDITOR — they apply in new tabs",section:"startup",shell:!0},{name:"browse",args:[],about:"Pick palettes and markets in a live picker — tab moves between Catalog, Installed, Markets and Errors",section:"catalog",start:"Install or drop palettes, add markets — every change applies at once on enter"},{name:"list",args:["[query]"],about:"Show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"Print the matches as JSON: name, group, catalog, installed"}}},{name:"add",args:["<palette...>"],about:"Install palettes from the catalog, or from a share code: ttheme add tt1:…",section:"catalog",flags:{market:{type:"string",value:"<source>",about:"Add this market first — a repository, a folder or official — and take bare palette names from it"}}},{name:"remove",args:["<palette...>"],about:"Uninstall palettes",section:"catalog"},{name:"update",args:[],about:"Refresh every market you added now — those with auto-update refresh on their own once a day",section:"catalog"},{name:"market",args:["[action]","[source]"],about:"The markets you added — add, remove and search them; init makes one of your own",actions:[["(none)","List the markets you added: palettes, auto-update and the last update"],["add <source>","Add one: a repository (alice/ttheme-pastel, #v1 pins a tag or branch), a folder, or official — asks whether it updates on its own"],["remove <market>","Drop one by its name (alice@pastel) — the palettes you installed from it keep working"],["search [query]","Repositories on GitHub with the ttheme-market topic"],["init [name]","Make a market of your own, <you>@<name>, in ~/.config/ttheme/market/<name> (or give a folder)"]],section:"catalog"},{name:"new",args:["<name>"],about:"Make a palette of your own, <you>@<market>/<name>, from blank in the palette editor — installed at once",section:"own",flags:{from:{type:"string",value:"<palette>",about:"Open the editor on this palette's colors instead of blank"},in:{type:"string",value:"<market>",about:"The local market to put it in, when you have more than one"}}},{name:"edit",args:["<palette>"],about:"Change one of your palettes in the palette editor — the contrast gate advises, never refuses",section:"own"},{name:"check",args:["<palette>"],about:"Measure a palette against the contrast gate and suggest colors that pass",section:"own",flags:{fix:{type:"boolean",about:"Write the suggested colors into your palette"}}},{name:"share",args:["<palette>"],about:"Print a share code — ttheme add <code> installs it anywhere, pictures included",section:"own"},{name:"init",args:[],about:"Install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Accept every default without prompting"}}},{name:"uninstall",args:[],about:"Take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"Remove without asking"}}},{name:"info",args:[],about:"Print what a bug report needs — version, OS, shell, terminal and the settings you changed",section:"support"},{name:"build",args:[],about:"Emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:St,about:"Rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"Pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>","[picture]"],about:"Show one of a palette's saved backgrounds, remove one, draw one in its palette's tone or its own colors, or pass on tuning — preview calls this",section:"setup",hidden:!0},{name:"flatten",args:["<source>","<out>","<background>","<opacity>","[canvas]","[place]"],about:"Lay a picture on a background color at an opacity, placed on a canvas when given one, for Warp, which fades the window instead — preview calls this",section:"setup",hidden:!0},{name:"bake",args:["<source>","<out>","<canvas>","<place>"],about:"Place a picture on a transparent canvas the way sips bakes preview's tuning — preview in Warp calls this",section:"setup",hidden:!0},{name:"redraw",args:[],about:"Draw the background pictures again after TTHEME_BG_BLUR changed — ttheme config and preview call this",section:"setup",hidden:!0}];function _s(e){let t=Object.entries(e.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[e.name,...t,...e.args].join(" ")}function vl(e,t=Math.max(...e.map(([n])=>n.length))){return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}var Ev=[["npx @kecan0406/ttheme init -y","Wire the terminals found here, no prompts"],["ttheme add homura madoka","Install two palettes"],["ttheme use homura","Paint this tab with one"],["ttheme list --json madoka","The madoka series as JSON"],["ttheme market add alice/ttheme-pastel","alice's market, alice@pastel — ttheme add alice@pastel/dusk"],["ttheme add dusk --market alice/ttheme-pastel","The same in one step"],["ttheme new rei --from rei","Your own rei, <you>@<market>/rei, to edit and share"]];function Ws(e,t=!1){let n=Gs.filter((o)=>!o.hidden&&!(t&&o.section==="setup")),r=yv.filter(({section:o})=>n.some((a)=>a.section===o)),i=[...t?["ttheme alone lists every installed palette, grouped, with previews"]:[],e?"ttheme help <command> describes one command · ttheme --version prints the version":"ttheme help <command> describes one · ttheme help all lists every command with what it does","https://kecan0406.github.io/ttheme"];if(!e){let o=n.filter((u)=>u.start),a=Math.max(...r.map(({title:u})=>u.length));return["Usage: ttheme <command>","",et.description,"","Start here",...vl(o.map((u)=>[_s(u),u.start])),"",...r.map(({section:u,title:c})=>`${c.padEnd(a)} ${n.filter((l)=>l.section===u).map((l)=>l.name).join(" · ")}`),"",...i].join(`
337
+ `)}let s=Math.max(...n.map((o)=>_s(o).length));return["Usage: ttheme <command>","",et.description,...r.flatMap(({section:o,title:a})=>["",a,...vl(n.filter((u)=>u.section===o).map((u)=>[_s(u),u.about]),s)]),"","Examples",...vl(Ev),"",...i].join(`
338
+ `)}import{readFileSync as xp}from"node:fs";import{join as Ap}from"node:path";var Ml="# ttheme begin",Sl="# ttheme end",Oi=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function lr(e,t){let n=`${Ml}
339
339
  ${t}
340
- ${El}
341
- `;if(Ri.test(e))return e.replace(Ri,n);if(e==="")return n;return`${e.replace(/\n*$/,`
340
+ ${Sl}
341
+ `;if(Oi.test(e))return e.replace(Oi,n);if(e==="")return n;return`${e.replace(/\n*$/,`
342
342
  `)}
343
343
  ${n}`}function fr(e){let t=e.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(t===e)return e;return t.trim()===""?"":t.replace(/\n*$/,`
344
- `)}function dr(e,t){let n=e.replace(Ri,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Tp(e){return`source ${e}/ttheme.zsh`}var $v="# ttheme settings — uncomment a line to change it; exported variables win over this file",Lr={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 vl(e){return Lr[e]?.default}function Ml(e,t){let n=`: \${${e}:=${t}}`;return vl(e)===t?`# ${n}`:n}function xp(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function kv(e,t){if(xp(t).test(e))return e;let n=Lr[t];return`${e.replace(/\n*$/,`
344
+ `)}function dr(e,t){let n=e.replace(Oi,"");return new RegExp(String.raw`^[ \t]*${t}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function Lp(e){return`source ${e}/ttheme.zsh`}var vv="# ttheme settings — uncomment a line to change it; exported variables win over this file",Lr={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 Us(e){return Lr[e]?.default}function Il(e,t){let n=`: \${${e}:=${t}}`;return Us(e)===t?`# ${n}`:n}function Cp(e){return new RegExp(String.raw`^#? ?: \$\{${e}[^\n]*$`,"m")}function Mv(e,t){if(Cp(t).test(e))return e;let n=Lr[t];return`${e.replace(/\n*$/,`
345
345
  `)}
346
346
  ${n.doc}
347
- ${Ml(t,n.default)}
348
- `}var Ap=Object.keys(Lr),yv=8;function Cr(e){let t="";try{t=Fp(Hp(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??Lr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(yv,Math.max(0,r)):0}function Na(e){let t="";try{t=Fp(Hp(e,"ttheme","config.zsh"),"utf8")}catch{}return(/^: \$\{TTHEME_BG_COLORS:=([^}\n]*)\}/m.exec(t)?.[1]??Lr.TTHEME_BG_COLORS.default).replace(/^(["'])(.*)\1$/,"$2")==="original"?"original":"tone"}function Sl(){let e=Object.entries(Lr).map(([t,n])=>`${n.doc}
349
- ${Ml(t,n.default)}`);return`${[$v,...e].join(`
347
+ ${Il(t,n.default)}
348
+ `}var Pa=Object.keys(Lr),Sv=8;function Cr(e){let t="";try{t=xp(Ap(e,"ttheme","config.zsh"),"utf8")}catch{}let n=/^: \$\{TTHEME_BG_BLUR:=([^}\n]*)\}/m.exec(t)?.[1]??Lr.TTHEME_BG_BLUR.default,r=Number(n.replace(/^(["'])(.*)\1$/,"$2"));return Number.isFinite(r)?Math.min(Sv,Math.max(0,r)):0}function Ra(e){let t="";try{t=xp(Ap(e,"ttheme","config.zsh"),"utf8")}catch{}return(/^: \$\{TTHEME_BG_COLORS:=([^}\n]*)\}/m.exec(t)?.[1]??Lr.TTHEME_BG_COLORS.default).replace(/^(["'])(.*)\1$/,"$2")==="original"?"original":"tone"}function Nl(){let e=Object.entries(Lr).map(([t,n])=>`${n.doc}
349
+ ${Il(t,n.default)}`);return`${[vv,...e].join(`
350
350
 
351
351
  `)}
352
- `}function Lp(e,t,n){let r=Ml(t,n),i=xp(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
352
+ `}function _p(e,t,n){let r=Il(t,n),i=Cp(t);if(i.test(e))return e.replace(i,r);return`${e.replace(/\n*$/,`
353
353
  `)}
354
354
  ${r}
355
- `}function Cp(e){if(e==="")return Sl();return Object.keys(Lr).reduce(kv,e)}var _p=/["$`\\]/;function Ev(e){return e.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Il(e,t,n=[],r={}){for(let l of e)for(let f of[l.name,l.group,l.native??"",...l.nativeNames??[],l.ansiSource])if(_p.test(f))throw Error(`${l.name}: "${f}" contains a character that breaks zsh quoting`);let i=Math.max(0,...e.map((l)=>l.name.length)),s=(l,f)=>` ${l.name.padEnd(i)} "${f}"`,o=(l)=>l.map((f)=>f.name).join(" "),a=Xe(e),u=(l)=>`'${l.replaceAll("'","'\\''")}'`,c=Gs.filter((l)=>l.section!=="setup"&&!l.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${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(Ws(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(Ws(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Ap.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Sl().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(Hr(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&&!_p.test(l.booru)).map((l)=>s(l,Ev(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${_t.map((l)=>l.name).join(" ")})`,..._t.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(Yt).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,ba(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 Nl={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Il(e.map(Bt))}]}};import{createHash as vv}from"node:crypto";var Mv=["black","red","green","yellow","blue","magenta","cyan","white"];function Gp(e,t){return[` ${e}:`,...Mv.map((n,r)=>` ${n}: "${t[r]}"`)]}function Sv(e,t,n){let r=vv("sha1");for(let i of t)r.update(i);return`${_(e)}.${r.digest("hex").slice(0,8)}.${n}`}function Wp(e,t,n){let r=2166136261;for(let i of Buffer.from(`${t}
357
- ${n.toLowerCase()}`,"utf8"))r=Math.imul(r^i,16777619)>>>0;return`${_(e)}.${r.toString(16).padStart(8,"0")}.png`}function Us(e,t){return t?Sv(e,[t.image,String(Up(t))],"yaml"):`${_(e)}.yaml`}function Up(e){return Math.max(0,Math.min(100,Math.round(e.opacity*100)))}function js(e,t){return[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Ye(e.background)<0.18?"darker":"lighter"}`,...t?["background_image:",` path: "${t.image}"`,` opacity: ${Up(t)}`]:[],"terminal_colors:",...Gp("normal",e.ansi.slice(0,8)),...Gp("bright",e.ansi.slice(8,16)),""].join(`
358
- `)}var Pl={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){return[{path:`warp/themes/${Us(e.name)}`,content:js(e)}]}};var jp=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,Ol={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${_(e.name)}"`,`origin_url = "${e.ansiSource}"`,"","[colors]",`foreground = "${e.foreground}"`,`background = "${e.background}"`,`cursor_bg = "${e.cursor}"`,`cursor_border = "${e.cursor}"`,`cursor_fg = "${e.background}"`,`selection_bg = "${e.selectionBackground}"`,`selection_fg = "${e.foreground}"`,"",`ansi = ${jp(e.ansi.slice(0,8))}`,`brights = ${jp(e.ansi.slice(8,16))}`,""].join(`
359
- `);return[{path:`wezterm/colors/${_(e.name)}.toml`,content:t}]}},Fi=(e)=>JSON.stringify(e);function Kp(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Fi(e.path)}`,`local COLORS = ${Fi(e.colors)}`,`local BACKGROUNDS = ${Fi(e.backgrounds)}`,`local STARTUP = ${e.startup?Fi(_(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Fi(t.name)}] = ${Fi(t.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. ((palette:gsub('@', '--', 1)):gsub('/', '--', 1)) .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local function framed(window, view)"," local color, image, opacity, W, H, w, h, x, y, at ="," view:match('^([^|]*)|([^|]*)|([^|]*)|(%d+)|(%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%d)$')"," if not image or image == '' or tonumber(W) == 0 or tonumber(H) == 0 then"," return nil, 'none'"," end"," local d = window:get_dimensions()"," local k = math.max(d.pixel_width / W, d.pixel_height / H)"," local n = tonumber(at) - 1"," local ax, ay = n % 3, n // 3"," local px = function(n) return string.format('%.2fpx', n) end"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = image },"," opacity = tonumber(opacity) or 1,"," width = px(w * k),"," height = px(h * k),"," horizontal_align = 'Left',"," vertical_align = 'Top',"," horizontal_offset = px(ax * (d.pixel_width - W * k) / 2 + x * k),"," vertical_offset = px(ay * (d.pixel_height - H * k) / 2 + y * k),"," repeat_x = 'NoRepeat',"," repeat_y = 'NoRepeat',"," },"," }, table.concat({ view, d.pixel_width, d.pixel_height }, '|')","end","","local shown = {}","","local function show(window, pane)"," local vars = pane:get_user_vars()"," local id = window:window_id()"," local background, key"," if vars.ttheme_view and vars.ttheme_view ~= '' then"," background, key = framed(window, vars.ttheme_view)"," elseif vars.ttheme_shown and vars.ttheme_shown ~= '' then"," background, key = layers(vars.ttheme_shown)"," elseif shown[id] == nil then"," return"," end"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' or name == 'ttheme_view' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
360
- `)}var Bp=["black","red","green","yellow","blue","purple","cyan","white"];function Jp(e){return{name:_(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(Bp.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(Bp.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:_(n)}]}:{},schemes:e.map(Jp)};return`${JSON.stringify(r,null,2)}
361
- `}var Fl={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${_(e.name)}.json`,content:`${JSON.stringify(Jp(e),null,2)}
362
- `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Rl(e)}]}};function ar(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}import{execFileSync as Iv}from"node:child_process";import{existsSync as qp,readdirSync as Nv,readFileSync as Pv}from"node:fs";import{join as zp}from"node:path";function Ie(e){return qp(e)?Pv(e,"utf8"):""}function De(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Pa(e){return[...new Set(e.split(`
363
- `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function fn(e,t){let n=Ie(e),r=t(n);return r===n?[]:[{file:e,content:r}]}function Ks(e){return process.env.XDG_DATA_HOME??zp(e,".local","share")}function Oa(e){return qp(e)?Nv(e).flatMap((t)=>t.startsWith(_(""))?[zp(e,t)]:[]):[]}function Hl(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 _r(){return{platform:process.platform,env:process.env,run:(e,t)=>{try{return Iv(e,[...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as Yp}from"node:fs";import{join as Fa}from"node:path";function Ov(e){let t=e.replace(Ri,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var Rv=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Qp=/^[ \t]*\[/m,Vp=/^[ \t]*import[ \t]*=/m,Fv=/^[ \t]*general[ \t]*[.=]/m;function Hv(e){return e?`[general]
364
- import = ["${e}"]`:""}function Tl(e,t){let n=e.replace(Ri,""),r=Rv.exec(n);if(!r){let u=n.search(Qp),c=u<0?n:n.slice(0,u);if(Fv.test(n)||Vp.test(c))return;return lr(e,Hv(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(Qp);if(Vp.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
355
+ `}function Gp(e){if(e==="")return Nl();return Object.keys(Lr).reduce(Mv,e)}var Wp=/["$`\\]/;function Iv(e){return e.replace(/_\([^)]*\)$/,"").replaceAll("_"," ")}function Pl(e,t,n=[],r={}){for(let l of e)for(let f of[l.name,l.group,l.native??"",...l.nativeNames??[],l.ansiSource])if(Wp.test(f))throw Error(`${l.name}: "${f}" contains a character that breaks zsh quoting`);let i=Math.max(0,...e.map((l)=>l.name.length)),s=(l,f)=>` ${l.name.padEnd(i)} "${f}"`,o=(l)=>l.map((f)=>f.name).join(" "),a=Xe(e),u=(l)=>`'${l.replaceAll("'","'\\''")}'`,c=Gs.filter((l)=>l.section!=="setup"&&!l.hidden);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${et.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${t??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,...Object.keys(r).length>0?["","# what a wired terminal's adapter needs to know of it (src/terminals/)",...Object.entries(r).map(([l,f])=>`typeset -g ${l}=${u(f)}`)]:[],"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${c.map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_TAB_VERBS=(${c.filter((l)=>l.section==="tab").map((l)=>l.name).join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${c.filter((l)=>l.shell).map((l)=>l.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...c.map((l)=>` ${l.name} ${u(l.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...c.map((l)=>` ${l.name} ${u(l.about)}`),")",`typeset -g TTHEME_HELP=${u(Ws(!1,!0))}`,`typeset -g TTHEME_HELP_ALL=${u(Ws(!0,!0))}`,"","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${Pa.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Nl().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...e.map((l)=>s(l,[l.background,l.foreground,l.cursor,l.selection,...l.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(a)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Tr(a))})`,"","typeset -gA TTHEME_GROUP=(",...e.map((l)=>s(l,l.group)),")","","# the catalog a market palette sits in — the folder under the market's palettes/, one level below the market in every list","typeset -gA TTHEME_CATALOG=(",...e.filter((l)=>l.catalog).map((l)=>s(l,l.catalog??"")),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...e.filter((l)=>l.native).map((l)=>s(l,l.native??"")),")","","# the character's names in its original language, |-separated, and as its booru tag spells it: preview searches both","typeset -gA TTHEME_NATIVE_NAMES=(",...e.filter((l)=>l.nativeNames).map((l)=>s(l,(l.nativeNames??[]).join("|"))),")","typeset -gA TTHEME_CHARACTER=(",...e.filter((l)=>l.booru&&!Wp.test(l.booru)).map((l)=>s(l,Iv(l.booru??""))),")","","# the example scenes preview draws beside the list (src/scenes.ts), each line as «role»text runs",`typeset -ga TTHEME_SCENES=(${Gt.map((l)=>l.name).join(" ")})`,...Gt.flatMap((l,f)=>[`typeset -ga TTHEME_SCENE_${f+1}=(`,...l.lines.map((d)=>` ${u(d)}`),")"]),"","# each booru's ANSI color, which marks a link to one of its posts",`typeset -gA TTHEME_SITE_ANSI=(${X.map((l)=>`${l.name} ${l.ansi}`).join(" ")})`,"","# the terminals that open OSC 8 links (src/terminal.ts)",`typeset -ga TTHEME_LINKS=(${Object.entries(Vt).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,wa(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 Rl={id:"shell",emitShared(e){return[{path:"shell/palettes.zsh",content:Pl(e.map(Jt))}]}};import{createHash as Nv}from"node:crypto";var Pv=["black","red","green","yellow","blue","magenta","cyan","white"];function Up(e,t){return[` ${e}:`,...Pv.map((n,r)=>` ${n}: "${t[r]}"`)]}function Rv(e,t,n){let r=Nv("sha1");for(let i of t)r.update(i);return`${_(e)}.${r.digest("hex").slice(0,8)}.${n}`}function jp(e,t,n){let r=2166136261;for(let i of Buffer.from(`${t}
357
+ ${n.toLowerCase()}`,"utf8"))r=Math.imul(r^i,16777619)>>>0;return`${_(e)}.${r.toString(16).padStart(8,"0")}.png`}function js(e,t){return t?Rv(e,[t.image,String(Kp(t))],"yaml"):`${_(e)}.yaml`}function Kp(e){return Math.max(0,Math.min(100,Math.round(e.opacity*100)))}function Ks(e,t){return[`name: "${e.name}"`,`background: "${e.background}"`,`foreground: "${e.foreground}"`,`accent: "${e.cursor}"`,`cursor: "${e.cursor}"`,`details: ${Ve(e.background)<0.18?"darker":"lighter"}`,...t?["background_image:",` path: "${t.image}"`,` opacity: ${Kp(t)}`]:[],"terminal_colors:",...Up("normal",e.ansi.slice(0,8)),...Up("bright",e.ansi.slice(8,16)),""].join(`
358
+ `)}var Ol={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(e){return[{path:`warp/themes/${js(e.name)}`,content:Ks(e)}]}};var Bp=(e)=>`[${e.map((t)=>`"${t}"`).join(", ")}]`,Fl={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(e){let t=["[metadata]",`name = "${_(e.name)}"`,`origin_url = "${e.ansiSource}"`,"","[colors]",`foreground = "${e.foreground}"`,`background = "${e.background}"`,`cursor_bg = "${e.cursor}"`,`cursor_border = "${e.cursor}"`,`cursor_fg = "${e.background}"`,`selection_bg = "${e.selectionBackground}"`,`selection_fg = "${e.foreground}"`,"",`ansi = ${Bp(e.ansi.slice(0,8))}`,`brights = ${Bp(e.ansi.slice(8,16))}`,""].join(`
359
+ `);return[{path:`wezterm/colors/${_(e.name)}.toml`,content:t}]}},Fi=(e)=>JSON.stringify(e);function Jp(e){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${Fi(e.path)}`,`local COLORS = ${Fi(e.colors)}`,`local BACKGROUNDS = ${Fi(e.backgrounds)}`,`local STARTUP = ${e.startup?Fi(_(e.startup)):"nil"}`,"local PALETTES = {",...e.palettes.map((t)=>` [${Fi(t.name)}] = ${Fi(t.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. ((palette:gsub('@', '--', 1)):gsub('/', '--', 1)) .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local function framed(window, view)"," local color, image, opacity, W, H, w, h, x, y, at ="," view:match('^([^|]*)|([^|]*)|([^|]*)|(%d+)|(%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%-?%d+)|(%d)$')"," if not image or image == '' or tonumber(W) == 0 or tonumber(H) == 0 then"," return nil, 'none'"," end"," local d = window:get_dimensions()"," local k = math.max(d.pixel_width / W, d.pixel_height / H)"," local n = tonumber(at) - 1"," local ax, ay = n % 3, n // 3"," local px = function(n) return string.format('%.2fpx', n) end"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = image },"," opacity = tonumber(opacity) or 1,"," width = px(w * k),"," height = px(h * k),"," horizontal_align = 'Left',"," vertical_align = 'Top',"," horizontal_offset = px(ax * (d.pixel_width - W * k) / 2 + x * k),"," vertical_offset = px(ay * (d.pixel_height - H * k) / 2 + y * k),"," repeat_x = 'NoRepeat',"," repeat_y = 'NoRepeat',"," },"," }, table.concat({ view, d.pixel_width, d.pixel_height }, '|')","end","","local shown = {}","","local function show(window, pane)"," local vars = pane:get_user_vars()"," local id = window:window_id()"," local background, key"," if vars.ttheme_view and vars.ttheme_view ~= '' then"," background, key = framed(window, vars.ttheme_view)"," elseif vars.ttheme_shown and vars.ttheme_shown ~= '' then"," background, key = layers(vars.ttheme_shown)"," elseif shown[id] == nil then"," return"," end"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' or name == 'ttheme_view' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
360
+ `)}var qp=["black","red","green","yellow","blue","purple","cyan","white"];function zp(e){return{name:_(e.name),background:e.background,foreground:e.foreground,cursorColor:e.cursor,selectionBackground:e.selectionBackground,...Object.fromEntries(qp.map((t,n)=>[t,e.ansi[n]])),...Object.fromEntries(qp.map((t,n)=>[`bright${t[0]?.toUpperCase()}${t.slice(1)}`,e.ansi[n+8]]))}}function Tl(e,t,n){let r={...t&&n?{profiles:[{updates:t,colorScheme:_(n)}]}:{},schemes:e.map(zp)};return`${JSON.stringify(r,null,2)}
361
+ `}var Hl={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(e){return[{path:`windows-terminal/schemes/${_(e.name)}.json`,content:`${JSON.stringify(zp(e),null,2)}
362
+ `}]},emitShared(e){return[{path:"windows-terminal/ttheme.json",content:Tl(e)}]}};function ar(e){return[`# ${e.name} — ${e.group}${e.native?` (${e.native})`:""}`,`# ANSI: ${e.ansiSource}`]}import{execFileSync as Ov}from"node:child_process";import{existsSync as Vp,readdirSync as Fv,readFileSync as Tv}from"node:fs";import{join as Yp}from"node:path";function Ie(e){return Vp(e)?Tv(e,"utf8"):""}function De(e,t){return e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Oa(e){return[...new Set(e.split(`
363
+ `).map((t)=>t.split(/[ =]/)[0]))].join(", ")}function fn(e,t){let n=Ie(e),r=t(n);return r===n?[]:[{file:e,content:r}]}function Bs(e){return process.env.XDG_DATA_HOME??Yp(e,".local","share")}function Fa(e){return Vp(e)?Fv(e).flatMap((t)=>t.startsWith(_(""))?[Yp(e,t)]:[]):[]}function xl(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 _r(){return{platform:process.platform,env:process.env,run:(e,t)=>{try{return Ov(e,[...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).trim()}catch{return}}}}import{existsSync as Qp}from"node:fs";import{join as Ha}from"node:path";function Hv(e){let t=e.replace(Oi,"");return/^[ \t]*\[colors[\].]/m.test(t)||/^[ \t]*colors[ \t]*[.=]/m.test(t)}var xv=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Zp=/^[ \t]*\[/m,Xp=/^[ \t]*import[ \t]*=/m,Av=/^[ \t]*general[ \t]*[.=]/m;function Lv(e){return e?`[general]
364
+ import = ["${e}"]`:""}function Al(e,t){let n=e.replace(Oi,""),r=xv.exec(n);if(!r){let u=n.search(Zp),c=u<0?n:n.slice(0,u);if(Av.test(n)||Xp.test(c))return;return lr(e,Lv(t))}let i=r.index+r[0].length,s=n.slice(i),o=s.search(Zp);if(Xp.test(o<0?s:s.slice(0,o)))return;let a=t?`import = ["${t}"]
365
365
  `:"";return`${n.slice(0,i)}
366
- ${yl}
367
- ${a}${El}${s}`}function Ra(e){return Fa(e,"alacritty","alacritty.toml")}function Zp(e){return Fa(e.configHome,"alacritty","themes")}function Tv(e,t){return t?Fa(e,"alacritty","themes",`${_(t)}.toml`):void 0}var xl={id:"alacritty",name:"Alacritty",emitter:hl,shelf:{from:"themes",dir:Zp},offered:()=>!0,present:(e)=>Yp(Fa(e.configHome,"alacritty")),sync(e,t){t.themes(xl);let n=Ra(e.configHome),r=Tl(Ie(n),Tv(e.configHome,e.startup));if(r!==void 0)t.wire(n,r)},plan(e){let t=Ra(e.configHome);return Tl(Ie(t),void 0)!==void 0?[`Edit ${De(t,e.home)} — a ttheme block: general.import`]:[]},notes(e){let t=Ra(e.configHome),n=Ie(t);return[...Yp(t)&&Tl(n,void 0)===void 0?[`${t} already imports files under [general] — ttheme left it alone; add ${Zp(e)}/<palette>.toml to that import list yourself`]:[],...Ov(n)?[`${De(t,e.home)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`]:[]]},next:()=>["Alacritty Reloads its config by itself"],unwire:(e)=>({edits:fn(Ra(e.configHome),fr),removals:[],touches:[]})};import{existsSync as xv}from"node:fs";import{join as Ta}from"node:path";function Av(e,t,n=""){let r=[];if(!dr(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!dr(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${_(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
368
- `)}function Ha(e){return Ta(e,"ghostty","config")}function Xp(e,t,n){return Av(Ta(e.configHome,"ttheme"),t,n)}var Al={id:"ghostty",name:"Ghostty",emitter:gl,shelf:{from:"themes",dir:(e)=>Ta(e.configHome,"ghostty","themes")},offered:()=>!0,present:(e)=>xv(Ta(e.configHome,"ghostty")),sync(e,t){t.themes(Al);let n=Ha(e.configHome),r=Ie(n);t.wire(n,lr(r,Xp(e,e.startup,r)))},plan(e){let t=Ha(e.configHome);return[`Edit ${De(t,e.home)} — a ttheme block: ${Pa(Xp(e,e.startup,Ie(t)))}`]},notes(e){let t=Ha(e.configHome);return dr(Ie(t),"command")?[`${De(t,e.home)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`]:[]},next:()=>["Restart Ghostty New tabs pick up its config"],unwire:(e)=>({edits:fn(Ha(e.configHome),fr),removals:[],touches:[]})};import{existsSync as Dp}from"node:fs";import{join as nb}from"node:path";var Ll="ttheme-default";function Bs(e){return nb(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function rb(e){return e.itermBase!==void 0&&e.palettes.length>0}function eb(e){let t=Se(e.configHome),n=new Map;for(let i of e.themes){let s=Rs(t,i.name,e.home);if(s)n.set(i.name,s)}let r=new Set(Xe(e.entries).map((i)=>i.name));return wp(e.themes.filter((i)=>r.has(i.name)),n,e.themes.find((i)=>i.name===e.startup),e.state.itermBase,rb(e.state))}function ib(e){return e.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function tb(e){return e.run("defaults",["read",ib(e),"Default Bookmark Guid"])||void 0}var Lv={key:"itermBase",profile:()=>"ttheme · default",base(e){let t=tb(e.host);return t&&!t.startsWith("ttheme-")?{...e.state,itermBase:t}:e.state},point(e,t){let n=tb(e.host),r=e.startup?t||n===Ll?Ll:void 0:n===Ll&&!rb(e.state)?e.state.itermBase:void 0;if(!r||r===n)return;return e.host.run("defaults",["write",ib(e.host),"Default Bookmark Guid","-string",r]),{restart:Boolean(e.host.run("pgrep",["-x","iTerm2"]))}}},sb={id:"iterm2",name:"iTerm2",emitter:ml,bakes:!0,offered:(e,t)=>t.platform==="darwin",present:(e)=>Dp(nb(e.home,"Library","Application Support","iTerm2")),sync(e,t){t.write(Bs(e.home),eb(e))},pictures(e,t){t.write(Bs(e.home),eb(e))},plan:(e)=>[`Write ${De(Bs(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:Dp(Bs(e.home))?[Bs(e.home)]:[],touches:[]}),defaults:Lv};import{existsSync as Cv}from"node:fs";import{join as Aa}from"node:path";function ob(e,t,n=""){return[...e?[`include themes/${_(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!dr(n,r.split(" ")[0]))].join(`
369
- `)}function xa(e){return Aa(e,"kitty","kitty.conf")}function Cl(e){return Aa(e,"ttheme","kitty.py")}function ab(e){return Aa(e.configHome,"kitty","themes")}var _l={id:"kitty",name:"kitty",emitter:pl,shelf:{from:"themes",dir:ab},offered:()=>!0,present:(e)=>Cv(Aa(e.configHome,"kitty")),sync(e,t){t.themes(_l),t.write(Cl(e.configHome),$p({themes:ab(e),backgrounds:Se(e.configHome)}));let n=xa(e.configHome),r=Ie(n);t.wire(n,lr(r,ob(e.startup,Cl(e.configHome),r)))},plan(e){let t=xa(e.configHome),n=ob(e.startup,Cl(e.configHome),Ie(t));return[`Edit ${De(t,e.home)} — a ttheme block: ${Pa(n)}`]},notes(e){let t=Ie(xa(e.configHome));return dr(t,"window_logo_scale")||dr(t,"window_logo_alpha")?["kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them"]:[]},next:()=>["New kitty window Pictures follow it — kitty reloads its colors by itself"],unwire:(e)=>({edits:fn(xa(e.configHome),fr),removals:[],touches:[]})};import{existsSync as Ca}from"node:fs";import{isAbsolute as _v,join as qs}from"node:path";function La(e){return qs(Ks(e),"konsole")}function Js(e){return qs(e,"konsolerc")}function ub(e){return`${_(e)}.profile`}function zs(e){return`ttheme · ${e}`}function cb(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 Gl(e){return new RegExp(String.raw`^\s*${e}\s*=`)}function hr(e,t,n){let r=e.split(`
370
- `),i=cb(r,t);return(i&&r.slice(i[0]+1,i[1]).find((o)=>Gl(n).test(o)))?.replace(Gl(n),"").trim()}function lb(e,t){let n=e.split(`
371
- `),r=cb(n,"Desktop Entry"),i=t===void 0?[]:[`DefaultProfile=${t}`];if(!r)return t===void 0?e:`${e===""?"":e.replace(/\n*$/,`
366
+ ${Ml}
367
+ ${a}${Sl}${s}`}function Ta(e){return Ha(e,"alacritty","alacritty.toml")}function Dp(e){return Ha(e.configHome,"alacritty","themes")}function Cv(e,t){return t?Ha(e,"alacritty","themes",`${_(t)}.toml`):void 0}var Ll={id:"alacritty",name:"Alacritty",emitter:pl,shelf:{from:"themes",dir:Dp},offered:()=>!0,present:(e)=>Qp(Ha(e.configHome,"alacritty")),sync(e,t){t.themes(Ll);let n=Ta(e.configHome),r=Al(Ie(n),Cv(e.configHome,e.startup));if(r!==void 0)t.wire(n,r)},plan(e){let t=Ta(e.configHome);return Al(Ie(t),void 0)!==void 0?[`Edit ${De(t,e.home)} — a ttheme block: general.import`]:[]},notes(e){let t=Ta(e.configHome),n=Ie(t);return[...Qp(t)&&Al(n,void 0)===void 0?[`${t} already imports files under [general] — ttheme left it alone; add ${Dp(e)}/<palette>.toml to that import list yourself`]:[],...Hv(n)?[`${De(t,e.home)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`]:[]]},next:()=>["Alacritty Reloads its config by itself"],unwire:(e)=>({edits:fn(Ta(e.configHome),fr),removals:[],touches:[]})};import{existsSync as _v}from"node:fs";import{join as Aa}from"node:path";function Gv(e,t,n=""){let r=[];if(!dr(n,"command")){if(r.push(`command = ${e}/launch-tab.zsh`),!dr(n,"shell-integration"))r.push("shell-integration = zsh")}if(t)r.push(`theme = ${_(t)}`);return r.push(`config-file = ?${e}/backgrounds/shown.conf`),r.join(`
368
+ `)}function xa(e){return Aa(e,"ghostty","config")}function eb(e,t,n){return Gv(Aa(e.configHome,"ttheme"),t,n)}var Cl={id:"ghostty",name:"Ghostty",emitter:bl,shelf:{from:"themes",dir:(e)=>Aa(e.configHome,"ghostty","themes")},offered:()=>!0,present:(e)=>_v(Aa(e.configHome,"ghostty")),sync(e,t){t.themes(Cl);let n=xa(e.configHome),r=Ie(n);t.wire(n,lr(r,eb(e,e.startup,r)))},plan(e){let t=xa(e.configHome);return[`Edit ${De(t,e.home)} — a ttheme block: ${Oa(eb(e,e.startup,Ie(t)))}`]},notes(e){let t=xa(e.configHome);return dr(Ie(t),"command")?[`${De(t,e.home)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`]:[]},next:()=>["Restart Ghostty New tabs pick up its config"],unwire:(e)=>({edits:fn(xa(e.configHome),fr),removals:[],touches:[]})};import{existsSync as tb}from"node:fs";import{join as ib}from"node:path";var _l="ttheme-default";function Js(e){return ib(e,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function sb(e){return e.itermBase!==void 0&&e.palettes.length>0}function nb(e){let t=Se(e.configHome),n=new Map;for(let i of e.themes){let s=Os(t,i.name,e.home);if(s)n.set(i.name,s)}let r=new Set(Xe(e.entries).map((i)=>i.name));return yp(e.themes.filter((i)=>r.has(i.name)),n,e.themes.find((i)=>i.name===e.startup),e.state.itermBase,sb(e.state))}function ob(e){return e.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"}function rb(e){return e.run("defaults",["read",ob(e),"Default Bookmark Guid"])||void 0}var Wv={key:"itermBase",profile:()=>"ttheme · default",base(e){let t=rb(e.host);return t&&!t.startsWith("ttheme-")?{...e.state,itermBase:t}:e.state},point(e,t){let n=rb(e.host),r=e.startup?t||n===_l?_l:void 0:n===_l&&!sb(e.state)?e.state.itermBase:void 0;if(!r||r===n)return;return e.host.run("defaults",["write",ob(e.host),"Default Bookmark Guid","-string",r]),{restart:Boolean(e.host.run("pgrep",["-x","iTerm2"]))}}},ab={id:"iterm2",name:"iTerm2",emitter:wl,bakes:!0,offered:(e,t)=>t.platform==="darwin",present:(e)=>tb(ib(e.home,"Library","Application Support","iTerm2")),sync(e,t){t.write(Js(e.home),nb(e))},pictures(e,t){t.write(Js(e.home),nb(e))},plan:(e)=>[`Write ${De(Js(e.home),e.home)} — a "ttheme · <palette>" profile per palette`],notes:()=>[],next(e,t){let n=['iTerm2 profiles A "ttheme · <palette>" per palette in Settings › Profiles'];if(e.startup)n.push(t?.restart?`Restart iTerm2 New tabs open on "ttheme · default", which wears ${e.startup}`:`iTerm2 default "ttheme · default" wears ${e.startup} and follows \`ttheme default\``);return n},unwire:(e)=>({edits:[],removals:tb(Js(e.home))?[Js(e.home)]:[],touches:[]}),defaults:Wv};import{existsSync as Uv}from"node:fs";import{join as Ca}from"node:path";function ub(e,t,n=""){return[...e?[`include themes/${_(e)}.conf`]:[],`watcher ${t}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!dr(n,r.split(" ")[0]))].join(`
369
+ `)}function La(e){return Ca(e,"kitty","kitty.conf")}function Gl(e){return Ca(e,"ttheme","kitty.py")}function cb(e){return Ca(e.configHome,"kitty","themes")}var Wl={id:"kitty",name:"kitty",emitter:$l,shelf:{from:"themes",dir:cb},offered:()=>!0,present:(e)=>Uv(Ca(e.configHome,"kitty")),sync(e,t){t.themes(Wl),t.write(Gl(e.configHome),Ep({themes:cb(e),backgrounds:Se(e.configHome)}));let n=La(e.configHome),r=Ie(n);t.wire(n,lr(r,ub(e.startup,Gl(e.configHome),r)))},plan(e){let t=La(e.configHome),n=ub(e.startup,Gl(e.configHome),Ie(t));return[`Edit ${De(t,e.home)} — a ttheme block: ${Oa(n)}`]},notes(e){let t=Ie(La(e.configHome));return dr(t,"window_logo_scale")||dr(t,"window_logo_alpha")?["kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them"]:[]},next:()=>["New kitty window Pictures follow it — kitty reloads its colors by itself"],unwire:(e)=>({edits:fn(La(e.configHome),fr),removals:[],touches:[]})};import{existsSync as Ga}from"node:fs";import{isAbsolute as jv,join as zs}from"node:path";function _a(e){return zs(Bs(e),"konsole")}function qs(e){return zs(e,"konsolerc")}function lb(e){return`${_(e)}.profile`}function Vs(e){return`ttheme · ${e}`}function fb(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 Ul(e){return new RegExp(String.raw`^\s*${e}\s*=`)}function hr(e,t,n){let r=e.split(`
370
+ `),i=fb(r,t);return(i&&r.slice(i[0]+1,i[1]).find((o)=>Ul(n).test(o)))?.replace(Ul(n),"").trim()}function db(e,t){let n=e.split(`
371
+ `),r=fb(n,"Desktop Entry"),i=t===void 0?[]:[`DefaultProfile=${t}`];if(!r)return t===void 0?e:`${e===""?"":e.replace(/\n*$/,`
372
372
 
373
373
  `)}[Desktop Entry]
374
374
  ${i[0]}
375
- `;let s=n.findIndex((a,u)=>u>r[0]&&u<r[1]&&Gl("DefaultProfile").test(a));if(s>=0)n.splice(s,1,...i);else n.splice(r[0]+1,0,...i);let o=r[1]+i.length-(s>=0?1:0);if(n.slice(r[0]+1,o).every((a)=>a.trim()==="")){let a=r[0]>0&&n[r[0]-1]?.trim()===""?r[0]-1:r[0],u=o===n.length&&n[o-1]===""?o-1:o;n.splice(a,u-a)}return n.join(`
376
- `)}function Gv(e){if(e&&Ht(e.toLowerCase()))return e.toLowerCase();let t=e?.split(",").map((n)=>Number(n.trim()));if(!t||t.length<3||t.slice(0,3).some((n)=>!Number.isInteger(n)||n<0||n>255))return;return`#${t.slice(0,3).map((n)=>n.toString(16).padStart(2,"0")).join("")}`}function fb(e,t){let n=t.endsWith(".profile")?t:`${t}.profile`;if(_v(n))return Ca(n)?n:void 0;let r=n.includes("/")?n:qs("konsole",n);return[Ks(e.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((s)=>qs(s,r)).find((s)=>Ca(s))}function db(e,t,n=0){let r=t&&t!=="FALLBACK/"&&n<8?fb(e,t):void 0;if(!r)return{};let i=Ie(r),s=db(e,hr(i,"General","Parent"),n+1);return{scheme:hr(i,"Appearance","ColorScheme")||s.scheme,use:hr(i,"Cursor Options","UseCustomCursorColor")??s.use,cursor:hr(i,"Cursor Options","CustomCursorColor")??s.cursor}}function Wv(e,t){let n=db(e,t),r=n.use==="true"?Gv(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function Uv(e,t){return["[Appearance]",`ColorScheme=${_(e.name)}`,"","[Cursor Options]",`CustomCursorColor=${ve(e.cursor).join(",")}`,`CustomCursorTextColor=${ve(e.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${zs(e.name)}`,`Parent=${t}`,""].join(`
377
- `)}function jv(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 Wl=["--session","--print-reply","--reply-timeout=2000"];function Kv(e){return[...(e.run("dbus-send",[...Wl,"--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",[...Wl,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function Bv(e,{service:t,window:n},r){let i=(s,...o)=>e.run("dbus-send",[...Wl,`--dest=${t}`,n,`org.kde.konsole.Window.${s}`,...o]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function Jv(e,t){let n=fb(e,t);return n?hr(Ie(n),"General","Name"):void 0}function qv(e){return hr(Ie(Js(e)),"Desktop Entry","DefaultProfile")}var zv={key:"konsoleBase",profile:zs,base(e){let t=qv(e.configHome);return t&&!t.startsWith(_(""))?{...e.state,konsoleBase:t}:e.state},point(e,t){let n=Js(e.configHome),r=Ie(n),i=hr(r,"Desktop Entry","DefaultProfile"),s=i?.startsWith(_(""))===!0,o=e.startup?t||s?ub(e.startup):void 0:s?e.state.konsoleBase??"":void 0;if(o===void 0||o===(i??"")&&!t)return;if(o!==(i??""))en(n,lb(r,o||void 0));let a=e.startup?zs(e.startup):o?Jv(e,o):void 0,u=Kv(e.host),c=a!==void 0&&u.every((l)=>Bv(e.host,l,a));return{restart:u.length>0&&!c}}},Ul={id:"konsole",name:"Konsole",emitter:bl,shelf:{from:"",dir:(e)=>La(e.home)},offered:(e,t)=>t.platform!=="darwin"&&t.platform!=="win32",present:(e)=>Ca(La(e.home))||Ca(Js(e.configHome)),sync(e,t){t.themes(Ul);let n=La(e.home),r=e.state.konsoleBase??"FALLBACK/",i=new Set;for(let s of jv(e)){let o=qs(n,ub(s.name));i.add(o),t.write(o,Uv(s,r))}for(let s of Oa(n))if(s.endsWith(".profile")&&!i.has(s))t.remove(s)},layer:(e)=>({TTHEME_KONSOLE_BASE:Wv(e,e.state.konsoleBase)}),plan(e){return[`Write ${De(La(e.home),e.home)}/${_("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...e.startup?[`Edit ${De(Js(e.configHome),e.home)} — DefaultProfile; \`ttheme off\` puts yours back`]:[]]},notes:()=>[],next(e,t){let n=['Konsole profiles A "ttheme · <palette>" per palette in its profile list'];if(e.startup)n.push(t?.restart?`Restart Konsole New tabs open on "${zs(e.startup)}"`:`Konsole default "${zs(e.startup)}", which follows \`ttheme default\``);return n},unwire(e,t){let n=Js(e.configHome),r=Ie(n);return{edits:hr(r,"Desktop Entry","DefaultProfile")?.startsWith(_(""))?[{file:n,content:lb(r,t?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:zv};import{spawn as Yv}from"node:child_process";import{existsSync as gr,mkdirSync as Qv,readdirSync as jl,readFileSync as Kl,realpathSync as Vv,rmSync as Zv,writeFileSync as Xv}from"node:fs";import{dirname as pb,join as St}from"node:path";function Gr(e){return process.platform==="darwin"?St(e,".warp","themes"):St(Ks(e),"warp-terminal","themes")}function mr(e,t){return process.platform==="darwin"?St(e,".warp","settings.toml"):St(t,"warp-terminal","settings.toml")}var _a='"dark"';function Ga(e){return St(e,"ttheme","warp.base")}var bb="[appearance.themes]";function wb(e){let t=e.findIndex((r)=>r.trim()===bb);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function pr(e){let t=e.split(`
378
- `),n=wb(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function Jl(e,t=`${_(e)}.yaml`){return`{ custom = { name = "${e}", path = "${t}" } }`}function Dv(e){return e?.includes(`path = "${_("")}`)===!0?/name = "([^"]+)"/.exec(e)?.[1]:void 0}function Wa(e,t){let n=e.split(`
379
- `),r=wb(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
375
+ `;let s=n.findIndex((a,u)=>u>r[0]&&u<r[1]&&Ul("DefaultProfile").test(a));if(s>=0)n.splice(s,1,...i);else n.splice(r[0]+1,0,...i);let o=r[1]+i.length-(s>=0?1:0);if(n.slice(r[0]+1,o).every((a)=>a.trim()==="")){let a=r[0]>0&&n[r[0]-1]?.trim()===""?r[0]-1:r[0],u=o===n.length&&n[o-1]===""?o-1:o;n.splice(a,u-a)}return n.join(`
376
+ `)}function Kv(e){if(e&&Ht(e.toLowerCase()))return e.toLowerCase();let t=e?.split(",").map((n)=>Number(n.trim()));if(!t||t.length<3||t.slice(0,3).some((n)=>!Number.isInteger(n)||n<0||n>255))return;return`#${t.slice(0,3).map((n)=>n.toString(16).padStart(2,"0")).join("")}`}function hb(e,t){let n=t.endsWith(".profile")?t:`${t}.profile`;if(jv(n))return Ga(n)?n:void 0;let r=n.includes("/")?n:zs("konsole",n);return[Bs(e.home),...(process.env.XDG_DATA_DIRS||"/usr/local/share:/usr/share").split(":")].map((s)=>zs(s,r)).find((s)=>Ga(s))}function gb(e,t,n=0){let r=t&&t!=="FALLBACK/"&&n<8?hb(e,t):void 0;if(!r)return{};let i=Ie(r),s=gb(e,hr(i,"General","Parent"),n+1);return{scheme:hr(i,"Appearance","ColorScheme")||s.scheme,use:hr(i,"Cursor Options","UseCustomCursorColor")??s.use,cursor:hr(i,"Cursor Options","CustomCursorColor")??s.cursor}}function Bv(e,t){let n=gb(e,t),r=n.use==="true"?Kv(n.cursor):void 0;return[`ColorScheme=${n.scheme??"Breeze"}`,`UseCustomCursorColor=${r?"true":"false"}`,...r?[`customCursorColor=${r}`]:[]].join(";")}function Jv(e,t){return["[Appearance]",`ColorScheme=${_(e.name)}`,"","[Cursor Options]",`CustomCursorColor=${ve(e.cursor).join(",")}`,`CustomCursorTextColor=${ve(e.background).join(",")}`,"UseCustomCursorColor=true","","[General]",`Name=${Vs(e.name)}`,`Parent=${t}`,""].join(`
377
+ `)}function qv(e){let t=new Set(Xe(e.entries).map((n)=>n.name));return e.themes.filter((n)=>t.has(n.name)||n.name===e.startup)}var jl=["--session","--print-reply","--reply-timeout=2000"];function zv(e){return[...(e.run("dbus-send",[...jl,"--dest=org.freedesktop.DBus","/org/freedesktop/DBus","org.freedesktop.DBus.ListNames"])??"").matchAll(/string "(org\.kde\.konsole(?:-\d+)?)"/g)].flatMap(([,n=""])=>{let i=e.run("dbus-send",[...jl,`--dest=${n}`,"/Windows","org.freedesktop.DBus.Introspectable.Introspect"])?.match(/<node name="(\d+)"/)?.[1];return i?[{service:n,window:`/Windows/${i}`}]:[]})}function Vv(e,{service:t,window:n},r){let i=(s,...o)=>e.run("dbus-send",[...jl,`--dest=${t}`,n,`org.kde.konsole.Window.${s}`,...o]);return i("setDefaultProfile",`string:${r}`),i("defaultProfile")?.includes(`string "${r}"`)===!0}function Yv(e,t){let n=hb(e,t);return n?hr(Ie(n),"General","Name"):void 0}function Qv(e){return hr(Ie(qs(e)),"Desktop Entry","DefaultProfile")}var Zv={key:"konsoleBase",profile:Vs,base(e){let t=Qv(e.configHome);return t&&!t.startsWith(_(""))?{...e.state,konsoleBase:t}:e.state},point(e,t){let n=qs(e.configHome),r=Ie(n),i=hr(r,"Desktop Entry","DefaultProfile"),s=i?.startsWith(_(""))===!0,o=e.startup?t||s?lb(e.startup):void 0:s?e.state.konsoleBase??"":void 0;if(o===void 0||o===(i??"")&&!t)return;if(o!==(i??""))en(n,db(r,o||void 0));let a=e.startup?Vs(e.startup):o?Yv(e,o):void 0,u=zv(e.host),c=a!==void 0&&u.every((l)=>Vv(e.host,l,a));return{restart:u.length>0&&!c}}},Kl={id:"konsole",name:"Konsole",emitter:kl,shelf:{from:"",dir:(e)=>_a(e.home)},offered:(e,t)=>t.platform!=="darwin"&&t.platform!=="win32",present:(e)=>Ga(_a(e.home))||Ga(qs(e.configHome)),sync(e,t){t.themes(Kl);let n=_a(e.home),r=e.state.konsoleBase??"FALLBACK/",i=new Set;for(let s of qv(e)){let o=zs(n,lb(s.name));i.add(o),t.write(o,Jv(s,r))}for(let s of Fa(n))if(s.endsWith(".profile")&&!i.has(s))t.remove(s)},layer:(e)=>({TTHEME_KONSOLE_BASE:Bv(e,e.state.konsoleBase)}),plan(e){return[`Write ${De(_a(e.home),e.home)}/${_("*")}.profile — a "ttheme · <palette>" profile per palette, on top of your own`,...e.startup?[`Edit ${De(qs(e.configHome),e.home)} — DefaultProfile; \`ttheme off\` puts yours back`]:[]]},notes:()=>[],next(e,t){let n=['Konsole profiles A "ttheme · <palette>" per palette in its profile list'];if(e.startup)n.push(t?.restart?`Restart Konsole New tabs open on "${Vs(e.startup)}"`:`Konsole default "${Vs(e.startup)}", which follows \`ttheme default\``);return n},unwire(e,t){let n=qs(e.configHome),r=Ie(n);return{edits:hr(r,"Desktop Entry","DefaultProfile")?.startsWith(_(""))?[{file:n,content:db(r,t?.konsoleBase)}]:[],removals:[],touches:[]}},defaults:Zv};import{spawn as Xv}from"node:child_process";import{existsSync as gr,mkdirSync as Dv,readdirSync as Bl,readFileSync as Jl,realpathSync as eM,rmSync as tM,writeFileSync as nM}from"node:fs";import{dirname as wb,join as It}from"node:path";function Gr(e){return process.platform==="darwin"?It(e,".warp","themes"):It(Bs(e),"warp-terminal","themes")}function mr(e,t){return process.platform==="darwin"?It(e,".warp","settings.toml"):It(t,"warp-terminal","settings.toml")}var Wa='"dark"';function Ua(e){return It(e,"ttheme","warp.base")}var $b="[appearance.themes]";function kb(e){let t=e.findIndex((r)=>r.trim()===$b);if(t<0)return;let n=e.findIndex((r,i)=>i>t&&r.trimStart().startsWith("["));return[t,n<0?e.length:n]}function pr(e){let t=e.split(`
378
+ `),n=kb(t);if(!n)return;return t.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function zl(e,t=`${_(e)}.yaml`){return`{ custom = { name = "${e}", path = "${t}" } }`}function rM(e){return e?.includes(`path = "${_("")}`)===!0?/name = "([^"]+)"/.exec(e)?.[1]:void 0}function ja(e,t){let n=e.split(`
379
+ `),r=kb(n);if(!r)return t===void 0?e:`${e.replace(/\n*$/,`
380
380
  `)}
381
- ${bb}
381
+ ${$b}
382
382
  theme = ${t}
383
383
  `;let i=n.findIndex((s,o)=>o>r[0]&&o<r[1]&&/^theme\s*=/.test(s));if(i>=0)n.splice(i,1,...t===void 0?[]:[`theme = ${t}`]);else if(t!==void 0)n.splice(r[0]+1,0,`theme = ${t}`);return n.join(`
384
- `)}function Bl(e){return pr(e)?.includes(`path = "${_("")}`)===!0}var eM="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen, theme] = process.argv.slice(-4); if (fs.readFileSync(file, 'utf8') !== seen || !fs.existsSync(theme)) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 500)";function $b(e,t,n){return{image:St(e,Wp(t.name,n.image,t.background)),opacity:n.opacity}}function hb(e){let t=Gr(e.home),n=Se(e.configHome),r=new Map,i=new Set;for(let s of e.themes){let o=Rs(n,s.name,e.home),a=Us(s.name,o&&$b(t,s,o));r.set(s.name,a);for(let u of new Set([a,Us(s.name)]))if(!gr(St(t,u)))i.add(u)}return{files:r,fresh:i}}function gb(e,t,n){let r=Gr(e.home),i=Se(e.configHome),s=new Set(n.values()),o=pr(Ie(mr(e.home,e.configHome)))??"";for(let c of e.themes){let l=Rs(i,c.name,e.home),f=n.get(c.name);if(l&&f){let d=$b(r,c,l);if(!gr(d.image))try{let h=xt(new Uint8Array(Kl(l.image)));K(d.image,qo(Jo(h,c.background,1)))}catch{n.set(c.name,Us(c.name));continue}t.write(St(r,f),js(c,d))}}if(!gr(r))return;let a=(c,l)=>c.startsWith(_(""))&&new RegExp(`\\.[0-9a-f]{8}\\.${l}$`).test(c);for(let c of jl(r))if(a(c,"yaml")&&!s.has(c)&&!o.includes(`path = "${c}"`))t.remove(St(r,c));let u=new Set;for(let c of jl(r)){let l=c.startsWith(_(""))&&c.endsWith(".yaml")?/^ {2}path: "(.+)"$/m.exec(Ie(St(r,c)))?.[1]:void 0;if(l)u.add(l)}for(let c of jl(r))if(a(c,"png")&&!u.has(St(r,c)))t.remove(St(r,c))}function mb(e,t,n,r=!1){let i=mr(e.home,e.configHome);if(!gr(i))return;let s=Ga(e.configHome),o=Kl(i,"utf8"),a=r?Dv(pr(o)):t;if(r&&(a===void 0||!n.files.has(a)))return;let u;if(a){if(!Bl(o)&&!gr(s))Qv(pb(s),{recursive:!0}),Xv(s,pr(o)??"");u=Jl(a,n.files.get(a))}else{if(!Bl(o))return;u=gr(s)&&Kl(s,"utf8")||_a,Zv(s,{force:!0})}let c=Wa(o,u);if(c===o)return;let l=a===void 0?void 0:n.files.get(a)??`${_(a)}.yaml`;if(l!==void 0&&n.fresh.has(l))oc(i),Yv(process.execPath,["-e",eM,Vv(i),c,o,St(Gr(e.home),l)],{detached:!0,stdio:"ignore"}).unref();else en(i,c);return i}var ql={id:"warp",name:"Warp",emitter:Pl,shelf:{from:"themes",dir:(e)=>Gr(e.home)},bakes:!0,offered:(e,t)=>t.platform!=="win32",present:(e)=>gr(pb(Gr(e.home))),sync(e,t){let n=hb(e);t.themes(ql),gb(e,t,n.files);let r=mb(e,e.startup,n);if(r)t.note(r)},pictures(e,t){let n=hb(e);gb(e,t,n.files),mb(e,void 0,n,!0)},plan(e){let t=mr(e.home,e.configHome);return e.startup&&gr(t)?[`Edit ${De(t,e.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears one theme for the whole app, set through its settings.toml — a tab that takes a palette (`ttheme use`, a pin, preview) switches it, and switching tabs puts on the palette of the tab in front, read from Warp’s session database with sqlite3"],next:()=>[],unwire(e){let t=mr(e.home,e.configHome),n=Ie(t);return{edits:Bl(n)?[{file:t,content:Wa(n,Ie(Ga(e.configHome))||_a)}]:[],removals:[],touches:[]}}};import{existsSync as Ka}from"node:fs";import{join as Hi}from"node:path";var kb=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,tM=/^return config[ \t]*$/gm;function nM(e){return`dofile(${JSON.stringify(e)})(config)`}var Eb=`local wezterm = require 'wezterm'
384
+ `)}function ql(e){return pr(e)?.includes(`path = "${_("")}`)===!0}var iM="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen, theme] = process.argv.slice(-4); if (fs.readFileSync(file, 'utf8') !== seen || !fs.existsSync(theme)) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 500)";function yb(e,t,n){return{image:It(e,jp(t.name,n.image,t.background)),opacity:n.opacity}}function mb(e){let t=Gr(e.home),n=Se(e.configHome),r=new Map,i=new Set;for(let s of e.themes){let o=Os(n,s.name,e.home),a=js(s.name,o&&yb(t,s,o));r.set(s.name,a);for(let u of new Set([a,js(s.name)]))if(!gr(It(t,u)))i.add(u)}return{files:r,fresh:i}}function pb(e,t,n){let r=Gr(e.home),i=Se(e.configHome),s=new Set(n.values()),o=pr(Ie(mr(e.home,e.configHome)))??"";for(let c of e.themes){let l=Os(i,c.name,e.home),f=n.get(c.name);if(l&&f){let d=yb(r,c,l);if(!gr(d.image))try{let h=At(new Uint8Array(Jl(l.image)));K(d.image,zo(qo(h,c.background,1)))}catch{n.set(c.name,js(c.name));continue}t.write(It(r,f),Ks(c,d))}}if(!gr(r))return;let a=(c,l)=>c.startsWith(_(""))&&new RegExp(`\\.[0-9a-f]{8}\\.${l}$`).test(c);for(let c of Bl(r))if(a(c,"yaml")&&!s.has(c)&&!o.includes(`path = "${c}"`))t.remove(It(r,c));let u=new Set;for(let c of Bl(r)){let l=c.startsWith(_(""))&&c.endsWith(".yaml")?/^ {2}path: "(.+)"$/m.exec(Ie(It(r,c)))?.[1]:void 0;if(l)u.add(l)}for(let c of Bl(r))if(a(c,"png")&&!u.has(It(r,c)))t.remove(It(r,c))}function bb(e,t,n,r=!1){let i=mr(e.home,e.configHome);if(!gr(i))return;let s=Ua(e.configHome),o=Jl(i,"utf8"),a=r?rM(pr(o)):t;if(r&&(a===void 0||!n.files.has(a)))return;let u;if(a){if(!ql(o)&&!gr(s))Dv(wb(s),{recursive:!0}),nM(s,pr(o)??"");u=zl(a,n.files.get(a))}else{if(!ql(o))return;u=gr(s)&&Jl(s,"utf8")||Wa,tM(s,{force:!0})}let c=ja(o,u);if(c===o)return;let l=a===void 0?void 0:n.files.get(a)??`${_(a)}.yaml`;if(l!==void 0&&n.fresh.has(l))cc(i),Xv(process.execPath,["-e",iM,eM(i),c,o,It(Gr(e.home),l)],{detached:!0,stdio:"ignore"}).unref();else en(i,c);return i}var Vl={id:"warp",name:"Warp",emitter:Ol,shelf:{from:"themes",dir:(e)=>Gr(e.home)},bakes:!0,offered:(e,t)=>t.platform!=="win32",present:(e)=>gr(wb(Gr(e.home))),sync(e,t){let n=mb(e);t.themes(Vl),pb(e,t,n.files);let r=bb(e,e.startup,n);if(r)t.note(r)},pictures(e,t){let n=mb(e);pb(e,t,n.files),bb(e,void 0,n,!0)},plan(e){let t=mr(e.home,e.configHome);return e.startup&&gr(t)?[`Edit ${De(t,e.home)} — [appearance.themes] theme; \`ttheme off\` puts yours back`]:[]},notes:()=>["Warp wears one theme for the whole app, set through its settings.toml — a tab that takes a palette (`ttheme use`, a pin, preview) switches it, and switching tabs puts on the palette of the tab in front, read from Warp’s session database with sqlite3"],next:()=>[],unwire(e){let t=mr(e.home,e.configHome),n=Ie(t);return{edits:ql(n)?[{file:t,content:ja(n,Ie(Ua(e.configHome))||Wa)}]:[],removals:[],touches:[]}}};import{existsSync as Ja}from"node:fs";import{join as Ti}from"node:path";var Eb=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,sM=/^return config[ \t]*$/gm;function oM(e){return`dofile(${JSON.stringify(e)})(config)`}var Mb=`local wezterm = require 'wezterm'
385
385
  local config = wezterm.config_builder()
386
386
 
387
- `;function rM(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${Eb}return config
388
- `?"":t}function zl(e,t){let n=`-- ttheme begin
387
+ `;function aM(e){let t=e.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return t===`${Mb}return config
388
+ `?"":t}function Yl(e,t){let n=`-- ttheme begin
389
389
  ${t}
390
390
  -- ttheme end
391
- `;if(kb.test(e))return e.replace(kb,n);if(e==="")return`${Eb}${n}
391
+ `;if(Eb.test(e))return e.replace(Eb,n);if(e==="")return`${Mb}${n}
392
392
  return config
393
- `;let r=[...e.matchAll(tM)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
394
- ${e.slice(r.index)}`}function Ua(e,t){let n=Hi(t,".wezterm.lua");return Ka(n)?n:Hi(e,"wezterm","wezterm.lua")}function yb(e){return Hi(e.configHome,"wezterm","colors")}function ja(e){return Hi(e.configHome,"ttheme","wezterm.lua")}var Yl={id:"wezterm",name:"WezTerm",emitter:Ol,shelf:{from:"colors",dir:yb},offered:()=>!0,present:(e)=>Ka(Hi(e.configHome,"wezterm"))||Ka(Hi(e.home,".wezterm.lua")),sync(e,t){t.themes(Yl),t.write(ja(e),Kp({path:ja(e),colors:yb(e),backgrounds:Se(e.configHome),...e.startup?{startup:e.startup}:{},palettes:e.themes}));let n=Ua(e.configHome,e.home),r=zl(Ie(n),nM(ja(e)));if(r!==void 0)t.wire(n,r)},plan(e){let t=Ua(e.configHome,e.home);return zl(Ie(t),"")!==void 0?[`Edit ${De(t,e.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(e){let t=Ua(e.configHome,e.home);return Ka(t)&&zl(Ie(t),"")===void 0?[`${t} has no \`return config\` line — ttheme left it alone; call \`dofile("${ja(e)}")(config)\` from it yourself`]:[]},next:()=>["WezTerm Reloads its config by itself"],unwire:(e)=>({edits:fn(Ua(e.configHome,e.home),rM),removals:[],touches:[]})};import{existsSync as Mb,readFileSync as iM,utimesSync as sM}from"node:fs";import{dirname as oM,join as Ba}from"node:path";function Ql(e){return Ba(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function vb(e){return[Ba(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),Ba(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),Ba(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Mb(t))}function aM(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(iM(t,"utf8"))?.[1];if(n)return n}return}function Sb(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 Ib={id:"windows-terminal",name:"Windows Terminal",emitter:Fl,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=vb(n);if(t.write(Ql(n),Rl(e.themes,r??aM(i),e.startup))){let s=new Date;for(let o of i)sM(o,s,s);if(i.length>0)t.repaint()}},plan:(e)=>e.state.wtHome?[`Write ${Ql(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?oM(Ql(n)):void 0;return{edits:[],removals:r&&Mb(r)?[r]:[],touches:n?vb(n):[]}}};var br={ghostty:Al,kitty:_l,alacritty:xl,wezterm:Yl,iterm2:sb,"windows-terminal":Ib,warp:ql,konsole:Ul};function Ce(e=Mt){return e.map((t)=>br[t])}function Wr(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Qt(e){return e.off?void 0:Wr(e)}function le(){return process.env.XDG_CONFIG_HOME??Ja(dn(),".config")}var Ti=(e)=>typeof e==="string"&&e!==""?e:void 0,uM={author:Ti,startup:Ti,off:(e)=>e?!0:void 0,itermBase:Ti,konsoleBase:Ti,wtHome:Ti,wtProfile:Ti,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 se(e){let t=tr(e);if(!Vl(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Nb(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)=>Mt.includes(r)),...Object.fromEntries(Object.entries(uM).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function hn(e,t){K(tr(e),`${JSON.stringify(t,null,2)}
395
- `)}function Pb(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>Me(o)??[]))].filter((o)=>!e.palettes.some((a)=>Me(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:dl(Xe(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Ys(e,t,n){return{configHome:e,home:n,state:t,startup:Qt(t)}}function Ob(e,t,n,r){return{...Ys(e,n,r),entries:t,themes:t.map(Mn)}}function Rb(e){let t=[],n={written:t,repainted:!1,write(r,i){if(t.push(r),Vl(r)&&Nb(r,"utf8")===i)return!1;return K(r,i),!0},wire(r,i){t.push(r),en(r,i)},note(r){t.push(r)},remove(r){Zl(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 Hl(r,s))n.write(Ja(i,o),a)},repaint(){n.repainted=!0}};return n}function cM(e){return Object.assign({},...Ce(e.state.terminals).map((t)=>t.layer?.(e)??{}))}function mt(e,t,n,r=dn()){ct(Se(e));let i=Pb(je(e,t),n.palettes);Jm(e,new Map(i.map((c)=>[c.name,Ps(c)]))),Lm(e),va(e,i);let s=Ob(e,i,n,r),o=Rb(s);for(let c of Ce(n.terminals))c.sync(s,o);let a=Ja(e,"ttheme","palettes.zsh"),u=Il(i,s.startup,n.terminals,cM(s));if(o.repainted||Ie(a)!==u)K(a,u),Zl(`${a}.zwc`,{force:!0});return o.written.push(a),o.written}function It(e,t=dn()){let n=se(e),r=Ce(n.terminals).filter((o)=>o.pictures);if(r.length===0)return;let i=Ob(e,Pb(ln(e),n.palettes),n,t),s=Rb(i);for(let o of r)o.pictures?.(i,s)}function Ur(e){return!Ce(e).some((t)=>t.bakes)}function Fb(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>[...i.shelf?[`Write ${De(i.shelf.dir(r),n)}/${_("*")} — a theme file per palette`]:[],...i.plan(r)])}function Hb(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>i.notes(r))}function Tb(e,t,n,r=dn()){let i=Ys(e,t,r);return Ce(t.terminals).flatMap((s)=>s.next(i,n.get(s.id)))}function qa(e,t,n,r,i=dn()){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 Hl(a,Mn(c))){let f=Ja(u,l);if(Vl(f))Zl(f,{force:!0}),s.push(f)}}return s}function xb(e,t,n,r){return{...Ys(e,t,r),host:n}}function Xl(e,t,n,r=dn()){return Ce(t.terminals).reduce((i,s)=>s.defaults?.base(xb(e,i,n,r))??i,t)}function Qs(e,t,n,r,i=dn()){let s=new Map;for(let o of Ce(t.terminals)){let a=o.defaults?.point(xb(e,t,r,i),n);if(a)s.set(o.id,a)}return s}function gn(e,t,n,r,i=!1,s=_r(),o=dn()){let a=i||!Qt(n)&&Qt(r)!==void 0,u=a?Xl(e,r,s,o):r;return mt(e,t,u,o),hn(e,u),a||Qt(n)!==Qt(r)?Qs(e,u,a,s,o):new Map}var lM=300,fM=80,Ab=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function za(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Ya(e,t){if(!t)return za(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function wr(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=gt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${nt(`${Ab[i%Ab.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},fM),o.unref()},lM);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 vM,mkdirSync as jb,readFileSync as Kb,statSync as MM}from"node:fs";import{homedir as SM}from"node:os";import{dirname as IM,join as Wb}from"node:path";import{existsSync as Dl,mkdirSync as Cb,readFileSync as Ai}from"node:fs";import{homedir as bM}from"node:os";import{dirname as _b,join as Li}from"node:path";import{spawn as dM}from"node:child_process";var hM=30000,gM=3,mM=97,pM=`ObjC.import('Vision')
393
+ `;let r=[...e.matchAll(sM)].at(-1);if(r?.index===void 0)return;return`${e.slice(0,r.index)}${n}
394
+ ${e.slice(r.index)}`}function Ka(e,t){let n=Ti(t,".wezterm.lua");return Ja(n)?n:Ti(e,"wezterm","wezterm.lua")}function vb(e){return Ti(e.configHome,"wezterm","colors")}function Ba(e){return Ti(e.configHome,"ttheme","wezterm.lua")}var Ql={id:"wezterm",name:"WezTerm",emitter:Fl,shelf:{from:"colors",dir:vb},offered:()=>!0,present:(e)=>Ja(Ti(e.configHome,"wezterm"))||Ja(Ti(e.home,".wezterm.lua")),sync(e,t){t.themes(Ql),t.write(Ba(e),Jp({path:Ba(e),colors:vb(e),backgrounds:Se(e.configHome),...e.startup?{startup:e.startup}:{},palettes:e.themes}));let n=Ka(e.configHome,e.home),r=Yl(Ie(n),oM(Ba(e)));if(r!==void 0)t.wire(n,r)},plan(e){let t=Ka(e.configHome,e.home);return Yl(Ie(t),"")!==void 0?[`Edit ${De(t,e.home)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`]:[]},notes(e){let t=Ka(e.configHome,e.home);return Ja(t)&&Yl(Ie(t),"")===void 0?[`${t} has no \`return config\` line — ttheme left it alone; call \`dofile("${Ba(e)}")(config)\` from it yourself`]:[]},next:()=>["WezTerm Reloads its config by itself"],unwire:(e)=>({edits:fn(Ka(e.configHome,e.home),aM),removals:[],touches:[]})};import{existsSync as Ib,readFileSync as uM,utimesSync as cM}from"node:fs";import{dirname as lM,join as qa}from"node:path";function Zl(e){return qa(e,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Sb(e){return[qa(e,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),qa(e,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),qa(e,"Microsoft","Windows Terminal","settings.json")].filter((t)=>Ib(t))}function fM(e){for(let t of e){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(uM(t,"utf8"))?.[1];if(n)return n}return}function Nb(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 Pb={id:"windows-terminal",name:"Windows Terminal",emitter:Hl,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=Sb(n);if(t.write(Zl(n),Tl(e.themes,r??fM(i),e.startup))){let s=new Date;for(let o of i)cM(o,s,s);if(i.length>0)t.repaint()}},plan:(e)=>e.state.wtHome?[`Write ${Zl(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?lM(Zl(n)):void 0;return{edits:[],removals:r&&Ib(r)?[r]:[],touches:n?Sb(n):[]}}};var br={ghostty:Cl,kitty:Wl,alacritty:Ll,wezterm:Ql,iterm2:ab,"windows-terminal":Pb,warp:Vl,konsole:Kl};function Ce(e=St){return e.map((t)=>br[t])}function Wr(e){return e.startup&&e.palettes.includes(e.startup)?e.startup:e.palettes[0]}function Yt(e){return e.off?void 0:Wr(e)}function ue(){return process.env.XDG_CONFIG_HOME??za(dn(),".config")}var Hi=(e)=>typeof e==="string"&&e!==""?e:void 0,dM={author:Hi,startup:Hi,off:(e)=>e?!0:void 0,itermBase:Hi,konsoleBase:Hi,wtHome:Hi,wtProfile:Hi,markets:(e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"):void 0,updates:(e)=>e&&typeof e==="object"?Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="boolean")):void 0};function ne(e){let t=tr(e);if(!Xl(t))throw Error(`nothing installed yet at ${t} — run \`ttheme init\` first`);let n=JSON.parse(Rb(t,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${t} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>St.includes(r)),...Object.fromEntries(Object.entries(dM).flatMap(([r,i])=>{let s=i(n[r]);return s===void 0?[]:[[r,s]]})),palettes:n.palettes}}function hn(e,t){K(tr(e),`${JSON.stringify(t,null,2)}
395
+ `)}function Ob(e,t){let n=new Map(e.palettes.map((i)=>[i.name,i])),r=t.filter((i)=>!n.has(i));if(r.length>0){let i=[...new Set(r.flatMap((o)=>Me(o)??[]))].filter((o)=>!e.palettes.some((a)=>Me(a.name)===o)),s=i.length>0?`add ${i.join(", ")} first — \`ttheme market search\` finds a market's repository`:ml(Xe(e.palettes),r);throw Error(`not in any market: ${r.join(", ")} — ${s}`)}return e.palettes.filter((i)=>t.includes(i.name))}function Ys(e,t,n){return{configHome:e,home:n,state:t,startup:Yt(t)}}function Fb(e,t,n,r){return{...Ys(e,n,r),entries:t,themes:t.map(Mn)}}function Tb(e){let t=[],n={written:t,repainted:!1,write(r,i){if(t.push(r),Xl(r)&&Rb(r,"utf8")===i)return!1;return K(r,i),!0},wire(r,i){t.push(r),en(r,i)},note(r){t.push(r)},remove(r){Dl(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 xl(r,s))n.write(za(i,o),a)},repaint(){n.repainted=!0}};return n}function hM(e){return Object.assign({},...Ce(e.state.terminals).map((t)=>t.layer?.(e)??{}))}function mt(e,t,n,r=dn()){ct(Se(e));let i=Ob(je(e,t),n.palettes);Vm(e,new Map(i.map((c)=>[c.name,Ps(c)]))),Gm(e),Ma(e,i);let s=Fb(e,i,n,r),o=Tb(s);for(let c of Ce(n.terminals))c.sync(s,o);let a=za(e,"ttheme","palettes.zsh"),u=Pl(i,s.startup,n.terminals,hM(s));if(o.repainted||Ie(a)!==u)K(a,u),Dl(`${a}.zwc`,{force:!0});return o.written.push(a),o.written}function Nt(e,t=dn()){let n=ne(e),r=Ce(n.terminals).filter((o)=>o.pictures);if(r.length===0)return;let i=Fb(e,Ob(ln(e),n.palettes),n,t),s=Tb(i);for(let o of r)o.pictures?.(i,s)}function Ur(e){return!Ce(e).some((t)=>t.bakes)}function Hb(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>[...i.shelf?[`Write ${De(i.shelf.dir(r),n)}/${_("*")} — a theme file per palette`]:[],...i.plan(r)])}function xb(e,t,n=dn()){let r=Ys(e,t,n);return Ce(t.terminals).flatMap((i)=>i.notes(r))}function Ab(e,t,n,r=dn()){let i=Ys(e,t,r);return Ce(t.terminals).flatMap((s)=>s.next(i,n.get(s.id)))}function Va(e,t,n,r,i=dn()){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 xl(a,Mn(c))){let f=za(u,l);if(Xl(f))Dl(f,{force:!0}),s.push(f)}}return s}function Lb(e,t,n,r){return{...Ys(e,t,r),host:n}}function ef(e,t,n,r=dn()){return Ce(t.terminals).reduce((i,s)=>s.defaults?.base(Lb(e,i,n,r))??i,t)}function Qs(e,t,n,r,i=dn()){let s=new Map;for(let o of Ce(t.terminals)){let a=o.defaults?.point(Lb(e,t,r,i),n);if(a)s.set(o.id,a)}return s}function gn(e,t,n,r,i=!1,s=_r(),o=dn()){let a=i||!Yt(n)&&Yt(r)!==void 0,u=a?ef(e,r,s,o):r;return mt(e,t,u,o),hn(e,u),a||Yt(n)!==Yt(r)?Qs(e,u,a,s,o):new Map}var gM=300,mM=80,Cb=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Ya(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1000))} KB`}function Qa(e,t){if(!t)return Ya(e);return t>=1e6?`${(e/1e6).toFixed(1)}/${(t/1e6).toFixed(1)} MB`:`${Math.round(e/1000)}/${Math.round(t/1000)} KB`}function wr(e=""){let t=process.stdout;if(!t.isTTY||process.env.TERM==="dumb")return{set(){},say:(c)=>console.log(c),done(){}};let[n,r]=gt()?["",""]:["\x1B[2m","\x1B[22m"],i=0,s=!1,o,a=()=>{t.write(`\r\x1B[2K${n}${rt(`${Cb[i%Cb.length]} ${e}`,(t.columns||80)-1,!1)}${r}`)},u=setTimeout(()=>{s=!0,a(),o=setInterval(()=>{i++,a()},mM),o.unref()},gM);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 NM,mkdirSync as Bb,readFileSync as Jb,statSync as PM}from"node:fs";import{homedir as RM}from"node:os";import{dirname as OM,join as jb}from"node:path";import{existsSync as tf,mkdirSync as Gb,readFileSync as Ai}from"node:fs";import{homedir as yM}from"node:os";import{dirname as Wb,join as Li}from"node:path";import{spawn as pM}from"node:child_process";var bM=30000,wM=3,$M=97,kM=`ObjC.import('Vision')
396
396
  ObjC.import('CoreImage')
397
397
  ObjC.import('CoreGraphics')
398
398
  function run(argv) {
@@ -411,11 +411,11 @@ function run(argv) {
411
411
  $.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
412
412
  $.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
413
413
  if (!written) throw new Error('write failed')
414
- }`;function xi(){return process.platform==="darwin"}function Qa(e){return e>=gM&&e<=mM}function Vs(e,t,n){return new Promise((r,i)=>{let s=dM("osascript",["-l","JavaScript","-e",pM,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(hM)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
415
- `).at(-1)||`osascript exited ${a}`))})})}var Gb=90000;function Va(e,t){let n=Se(e),r=Ct(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),...Xc(n,i)}]:[]});return r.length>0?r:void 0}function wM(e,t){let n=new Set(ct(Se(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ft(r)))}function Ci(e,t){let n=new Set((t??[]).map((r)=>ft(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ft(r)))}}async function $M(e,t,n,r,i,s){let o=X.find((p)=>p.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await ys(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==At&&a.md5)try{sa([a],await oa([a.md5],i))}catch{}let u=ia(o,a)?ra(o,a.id,i).then((p)=>{if(p)vs(a,p)},()=>{}):void 0;if(!ta(o,a,Rr(process.env.TTHEME_FIND_RATING))||ea(a,mi(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=nn(a);if(!c)throw Error("too large to use");let l=Li(rn(o),"orig",`${n.id}.${c.ext}`),f;if(Dl(l))f=new Uint8Array(Ai(l));else{s("Downloading");let p=pi(o,a,c);f=await ua(p.site,p.url,i,(m,$)=>s("Downloading",Ya(m,$))),K(l,f)}let d=Kn(f,$t),h=!1;if(kn(d)===0&&xi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let p=Li(rn(o),"cut",`${n.id}.png`);try{if(!Dl(p))s("Cutting out"),Cb(_b(p),{recursive:!0}),await Vs(l,p,i);let m=Kn(new Uint8Array(Ai(p)),$t);if(Qa(kn(m)))d=m,h=!0}catch{}}await u;let g=Qc(t);s("Drawing"),ma(e,g,yi(g,t.signatureSlots),d,{site:o.key,id:n.id,ext:c.ext,bytes:f,from:`${o.name} ${n.id} ${o.pageUrl(n.id)}`,artist:a.named.artist,source:Es(a.source),cut:h},{width:0,height:0},Cr(e),Na(e));let b=Ct(e,t.name).find((p)=>p.key===ft(n));if(b)Fs(Se(e),b,n,r,bM())}function kM(e,t){let n=X.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${gt()?ss:`\x1B[${30+n.ansi}m${ss}\x1B[39m`} ${Wo(r,n.pageUrl(e.id))}`}async function Pn(e,t,n){let r=t.flatMap((u)=>wM(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=Ur(n),s=process.stdout.isTTY&&Sp(process.env),o=new Set,a=wr();for(let[u,{entry:c,shared:l}]of r.entries()){let f=`${c.name} · ${kM(l,s)}`,d=r.length>1?` · ${u+1}/${r.length}`:"",h=(g,b)=>a.set(`${g} ${f}${b?` · ${b}`:""}${d}`);try{await $M(e,c,l,i,AbortSignal.timeout(Gb),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)=>Ct(e,u.name).some((f)=>f.key===ft(l)));if(c)vi(e,u.name,ft(c))}if(o.size>0)It(e)}function Lb(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 yM(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Li(bi(),n??"local","cut",`${r??e}.png`);if(!Dl(i)){if(!xi())return;Cb(_b(i),{recursive:!0}),await Vs(t,i,AbortSignal.timeout(Gb))}return Kn(new Uint8Array(Ai(i)),$t)}function EM(e,t){try{return kn(xt(new Uint8Array(Ai(Li(e,`${t.stem}.png`)))))>0}catch{return!1}}async function Za(e,t,n,r,i,s,o,a){let u=Se(e),c=ct(u).palettes[t]?.pictures.find((d)=>d.key===n);if(!c?.original)return null;let l=Li(u,c.original),f=Kn(new Uint8Array(Ai(l)),$t);if(c.cut){if(!Lb(f,xt(new Uint8Array(Ai(Li(u,c.cut)))),0))return null;return pa(e,t,c,f,r,i,s,o,!1,a)}if(Os(c)&&kn(f)===0&&EM(u,c)){let d=await yM(n,l);if(!d||!Lb(f,d,3))return null;return pa(e,t,c,f,r,i,s,o,!0,a)}return pa(e,t,c,f,r,i,s,o,!1,a)}var NM=86400000,PM=3600000,tf=5000;function ef(){return Wb(process.env.XDG_STATE_HOME??Wb(SM(),".local","state"),"ttheme","markets.json")}function On(){try{let e=JSON.parse(Kb(ef(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Ub(e,t){let n=On();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};jb(IM(ef()),{recursive:!0}),K(ef(),`${JSON.stringify(n,null,2)}
416
- `)}function Zs(e,t){let n=t===ee?qt(e):yt(t)?Jt(e,t):void 0;try{return n?MM(n).mtimeMs:void 0}catch{return}}function OM(e,t,n,r){return e&&(t===void 0||r-t>=NM)&&(n===void 0||r-n>=PM)}function nf(e,t,n=Date.now()){let r=On();return it(t.markets).filter((i)=>OM(nr(i,t.updates),Zs(e,i),r[i]?.at,n))}async function RM(e,t,n){try{return await Ls(Qm(e),fl,t,n)}catch(r){if(r instanceof Ma)throw Error(`${ye(e)} has no ${an} — is the repository public, and has its action run?`);throw r}}async function Xs(e,t,n){if(e===ee){let s=await Ls(cp,cn,t,n);return{source:e,id:ee,manifest:s,entries:s.palettes}}let r=await RM(e,t,n),i=Ni(e,r);return{source:e,id:i,manifest:r,entries:Ea(r,i)}}function _i(e,t){if(t.source===ee){ya(e,t.manifest);return}jb(nl(e),{recursive:!0}),K(Jt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
417
- `)}function Gi(e,t){try{if(t===ee)return cn(Kb(qt(e),"utf8")).palettes;let n=or(e,t);return Ea(n,Ni(t,n))}catch{return[]}}function FM(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 Ds(e,t,n){let r=Gi(e,t),i;try{i=await Xs(t,n)}catch(s){throw Ub(t,s.message),s}return _i(e,i),Ub(t,void 0),{source:t,id:i.id,...t===ee?{version:i.manifest.version}:{},count:Xe(i.entries).length,change:FM(r,i.entries)}}function dt(e){return`${e} palette${e===1?"":"s"}`}function eo(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 Bb({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 rf(e){let t=Bb(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${dt(e.count)}${t?` (${t})`:""}`}function sf(e){return Bb(e.change)?`Updated ${rf(e)}`:void 0}async function Xa(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=We(e,!1);mt(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await Pn(e,je(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ci(c,u.get(c.name))),t.terminals)}async function Jb(e=le()){try{if(!vM(tr(e)))return;let t=se(e),n=nf(e,t);if(n.length===0)return;let r=In(e),i=wr(`Checking ${n.map(ye).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>Ds(e,a,tf)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>sf(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await Xa(e,t,r,s)}catch{return}}var Vb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,LM=["add","remove","search","init"];function cf(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function CM(){try{let e=HM("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Vb.test(e)?e:void 0}catch{return}}async function _M(e,t){if(t.author)return t.author;let n=CM();if(!n){if(!cf())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 Du({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Vb.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(ht(r))throw Error("no handle given");n=r.toLowerCase()}return hn(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Wi(e,t){if(t===ee)return ee;return xe(t)?Et(un(t)):Ni(t,or(e,t))}function Da(e,t){try{return Wi(e,t)}catch{return}}function Zb(e){return Me(e)??ee}function eu(e){return We(e).palettes.filter((t)=>Me(t.name)===void 0)}function GM(e){let t=jr(import.meta.dirname,"..","dist","manifest.json");return of(t)?cn(uf(t,"utf8")).palettes:eu(e)}function to(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==nr(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function Xb(e,t,n,r){return t.find((i)=>i!==n&&!Ii(i,n)&&Da(e,i)===r)}function af(e,t,n,r){let i=se(e),s=it(i.markets),o=Xb(e,s,t,n);if(o)throw Error(`${n} already names the market at ${ye(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};hn(e,to(i,s.includes(t)?s:[...s,t],a))}async function WM(e){if(!cf())return!1;let t=await An({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 Db(e){let t=wr(`Fetching ${ye(e)}`);try{return await Xs(e)}finally{t.done()}}async function UM(e,t,n){let r=await Db(n),i=se(e),s=it(i.markets),o=Xb(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${ye(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return hn(e,to(i,s.map((l)=>l===t?n:l),c)),_i(e,r),r}async function lf(e,t){let n=rr(t),r=it(se(e).markets);if(r.includes(n))return console.log(`${ye(n)} is already added`),{source:n,id:Wi(e,n),fresh:!1};let i=yt(n)?r.find((u)=>yt(u)&&Ii(u,n)):void 0;if(i){let u=await UM(e,i,n);return console.log(`Moved ${u.id} to ${tl(n)??"its default branch"} · ${ye(n)} — ${dt(Xe(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(xe(n)){let u=Et(un(n));af(e,n,u);let c=sr(n,u,eu(e)).length;return console.log(`Added ${u} · ${ye(n)} — ${dt(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await Db(n),o=n===ee?void 0:await WM(s.id);af(e,n,s.id,o),_i(e,s);let a=dt(Xe(s.entries).length);return console.log(n===ee?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${ye(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function jM(e){let t=le(),{source:n,id:r,fresh:i}=await lf(t,e);if(!i)return;if(xe(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===ee)console.log("\n`ttheme browse` picks them");else console.log(`
418
- \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function ff(e,t){if(t===ee)zb(qt(e),{force:!0});else if(yt(t))zb(Jt(e,t),{force:!0})}function df(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 KM(e){let t=le(),n=se(t),r=it(n.markets),i=r.find((c)=>Da(t,c)===e)??r.find((c)=>c===ew(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=Da(t,i),o=n.palettes.filter((c)=>Zb(c)===s),a=r.filter((c)=>c!==i),u=to(n,a,n.updates??{});if(hn(t,u),ff(t,i),mt(t,We(t),u),console.log(`Removed ${s??e} · ${ye(i)}`),o.length>0)console.log(df(o))}function ew(e){try{return rr(e)}catch{return}}function BM(e,t){try{if(t===ee)return Xe(cn(uf(qt(e),"utf8")).palettes).length;if(xe(t))return sr(t,Wi(e,t),eu(e),!1).length;return or(e,t).palettes.length}catch{return}}function hf(e,t,n=On(),r=Date.now()){if(xe(t))return"read in place";let i=n[t],s=Zs(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${eo(i.at,r)}`;return s===void 0?"never updated":`updated ${eo(s,r)}`}function JM(){let e=le(),t=se(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=On(),i=n.map((a)=>{let u=Da(e,a)??"?",c=BM(e,a),l=t.palettes.filter((d)=>Zb(d)===u).length,f=xe(a)?[]:[`auto-update ${nr(a,t.updates)?"on":"off"}`];return{name:u,where:ye(a),note:[c===void 0?"Unreadable":dt(c),...l>0?[`${l} installed`]:[],...f,hf(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 gf(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function mf(e,t){let n=encodeURIComponent(`topic:${Mi}${e?` ${e}`:""}`);try{let{items:r}=await Ls(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof Sa)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function qM(e){let t=le(),n=await mf(e);if(n.length===0){console.log(`No repository carries the ${Mi} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(it(se(t).markets).map(er)),i=n.map((o)=>{let a=gf(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 zM=`name: ttheme market
414
+ }`;function xi(){return process.platform==="darwin"}function Za(e){return e>=wM&&e<=$M}function Zs(e,t,n){return new Promise((r,i)=>{let s=pM("osascript",["-l","JavaScript","-e",kM,e,t],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(bM)])}),o="";s.stderr.on("data",(a)=>{o+=a}),s.on("error",i),s.on("close",(a)=>{if(a===0){r();return}i(Error(o.trim().split(`
415
+ `).at(-1)||`osascript exited ${a}`))})})}var Ub=90000;function Xa(e,t){let n=Se(e),r=_t(e,t).flatMap((i)=>{let[,s,o]=/^([a-z.]+)_(\d+)$/.exec(i.key)??[];return s&&o&&X.some((a)=>a.key===s)?[{site:s,id:Number(o),...tl(n,i)}]:[]});return r.length>0?r:void 0}function EM(e,t){let n=new Set(ct(Se(e)).palettes[t.name]?.pictures.map((r)=>r.key));return(t.pictures??[]).filter((r)=>!n.has(ft(r)))}function Ci(e,t){let n=new Set((t??[]).map((r)=>ft(r)));return{...e,pictures:(e.pictures??[]).filter((r)=>!n.has(ft(r)))}}async function vM(e,t,n,r,i,s){let o=X.find((p)=>p.key===n.site);if(!o)throw Error(`no site called ${n.site}`);s("Fetching");let a=await ys(o,n.id,i);if(!a)throw Error("the post is gone");if(o!==Lt&&a.md5)try{oa([a],await aa([a.md5],i))}catch{}let u=sa(o,a)?ia(o,a.id,i).then((p)=>{if(p)vs(a,p)},()=>{}):void 0;if(!na(o,a,Or(process.env.TTHEME_FIND_RATING))||ta(a,mi(process.env.TTHEME_FIND_BLOCK)).length>0)throw Error("outside your find filters — TTHEME_FIND_RATING and TTHEME_FIND_BLOCK");let c=nn(a);if(!c)throw Error("too large to use");let l=Li(rn(o),"orig",`${n.id}.${c.ext}`),f;if(tf(l))f=new Uint8Array(Ai(l));else{s("Downloading");let p=pi(o,a,c);f=await ca(p.site,p.url,i,(m,$)=>s("Downloading",Qa(m,$))),K(l,f)}let d=Kn(f,$t),h=!1;if(kn(d)===0&&xi()&&process.env.TTHEME_FIND_REMOVE_BG!=="off"){let p=Li(rn(o),"cut",`${n.id}.png`);try{if(!tf(p))s("Cutting out"),Gb(Wb(p),{recursive:!0}),await Zs(l,p,i);let m=Kn(new Uint8Array(Ai(p)),$t);if(Za(kn(m)))d=m,h=!0}catch{}}await u;let g=Xc(t);s("Drawing"),pa(e,g,yi(g,t.signatureSlots),d,{site:o.key,id:n.id,ext:c.ext,bytes:f,from:`${o.name} ${n.id} ${o.pageUrl(n.id)}`,artist:a.named.artist,source:Es(a.source),cut:h},{width:0,height:0},Cr(e),Ra(e));let b=_t(e,t.name).find((p)=>p.key===ft(n));if(b)Fs(Se(e),b,n,r,yM())}function MM(e,t){let n=X.find((s)=>s.key===e.site),r=`${n?.name??e.site} ${e.id}`;if(!n||!t)return r;return`${gt()?ss:`\x1B[${30+n.ansi}m${ss}\x1B[39m`} ${Uo(r,n.pageUrl(e.id))}`}async function Pn(e,t,n){let r=t.flatMap((u)=>EM(e,u).map((c)=>({entry:u,shared:c})));if(r.length===0)return;let i=Ur(n),s=process.stdout.isTTY&&Pp(process.env),o=new Set,a=wr();for(let[u,{entry:c,shared:l}]of r.entries()){let f=`${c.name} · ${MM(l,s)}`,d=r.length>1?` · ${u+1}/${r.length}`:"",h=(g,b)=>a.set(`${g} ${f}${b?` · ${b}`:""}${d}`);try{await vM(e,c,l,i,AbortSignal.timeout(Ub),h),a.say(` ▣ ${f}`),o.add(c)}catch(g){a.say(` ▢ ${f} — ${g instanceof Error?g.message:String(g)}`)}}a.done();for(let u of o){let c=(u.pictures??[]).find((l)=>_t(e,u.name).some((f)=>f.key===ft(l)));if(c)vi(e,u.name,ft(c))}if(o.size>0)Nt(e)}function _b(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 SM(e,t){let[,n,r]=/^(.+)_(\d+)$/.exec(e)??[],i=Li(bi(),n??"local","cut",`${r??e}.png`);if(!tf(i)){if(!xi())return;Gb(Wb(i),{recursive:!0}),await Zs(t,i,AbortSignal.timeout(Ub))}return Kn(new Uint8Array(Ai(i)),$t)}function IM(e,t){try{return kn(At(new Uint8Array(Ai(Li(e,`${t.stem}.png`)))))>0}catch{return!1}}async function Da(e,t,n,r,i,s,o,a){let u=Se(e),c=ct(u).palettes[t]?.pictures.find((d)=>d.key===n);if(!c?.original)return null;let l=Li(u,c.original),f=Kn(new Uint8Array(Ai(l)),$t);if(c.cut){if(!_b(f,At(new Uint8Array(Ai(Li(u,c.cut)))),0))return null;return ba(e,t,c,f,r,i,s,o,!1,a)}if(Rs(c)&&kn(f)===0&&IM(u,c)){let d=await SM(n,l);if(!d||!_b(f,d,3))return null;return ba(e,t,c,f,r,i,s,o,!0,a)}return ba(e,t,c,f,r,i,s,o,!1,a)}var FM=86400000,TM=3600000,rf=5000;function nf(){return jb(process.env.XDG_STATE_HOME??jb(RM(),".local","state"),"ttheme","markets.json")}function Rn(){try{let e=JSON.parse(Jb(nf(),"utf8"));return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]?.at==="number"&&typeof t[1].error==="string"))}catch{return{}}}function Kb(e,t){let n=Rn();if(t===void 0){if(!(e in n))return;delete n[e]}else n[e]={at:Date.now(),error:t};Bb(OM(nf()),{recursive:!0}),K(nf(),`${JSON.stringify(n,null,2)}
416
+ `)}function Xs(e,t){let n=t===ee?zt(e):yt(t)?qt(e,t):void 0;try{return n?PM(n).mtimeMs:void 0}catch{return}}function HM(e,t,n,r){return e&&(t===void 0||r-t>=FM)&&(n===void 0||r-n>=TM)}function sf(e,t,n=Date.now()){let r=Rn();return st(t.markets).filter((i)=>HM(nr(i,t.updates),Xs(e,i),r[i]?.at,n))}async function xM(e,t,n){try{return await Ls(Xm(e),gl,t,n)}catch(r){if(r instanceof Sa)throw Error(`${ye(e)} has no ${an} — is the repository public, and has its action run?`);throw r}}async function Ds(e,t,n){if(e===ee){let s=await Ls(dp,cn,t,n);return{source:e,id:ee,manifest:s,entries:s.palettes}}let r=await xM(e,t,n),i=Ni(e,r);return{source:e,id:i,manifest:r,entries:va(r,i)}}function _i(e,t){if(t.source===ee){Ea(e,t.manifest);return}Bb(sl(e),{recursive:!0}),K(qt(e,t.source),`${JSON.stringify(t.manifest,null,2)}
417
+ `)}function Gi(e,t){try{if(t===ee)return cn(Jb(zt(e),"utf8")).palettes;let n=or(e,t);return va(n,Ni(t,n))}catch{return[]}}function AM(e,t){let n=new Map(e.map((i)=>[i.name,JSON.stringify(i)])),r=new Map(t.map((i)=>[i.name,JSON.stringify(i)]));return{added:[...r.keys()].filter((i)=>!n.has(i)),changed:[...r].filter(([i,s])=>n.has(i)&&n.get(i)!==s).map(([i])=>i),gone:[...n.keys()].filter((i)=>!r.has(i))}}async function eo(e,t,n){let r=Gi(e,t),i;try{i=await Ds(t,n)}catch(s){throw Kb(t,s.message),s}return _i(e,i),Kb(t,void 0),{source:t,id:i.id,...t===ee?{version:i.manifest.version}:{},count:Xe(i.entries).length,change:AM(r,i.entries)}}function dt(e){return`${e} palette${e===1?"":"s"}`}function to(e,t=Date.now()){let n=Math.floor(Math.max(0,t-e)/60000);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function qb({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 of(e){let t=qb(e.change);return`${e.version?`${e.id} ${e.version}`:e.id} — ${dt(e.count)}${t?` (${t})`:""}`}function af(e){return qb(e.change)?`Updated ${of(e)}`:void 0}async function eu(e,t,n,r){let i=new Set(r.flatMap((c)=>[...c.change.changed,...c.change.gone])),s=t.palettes.filter((c)=>i.has(c));if(s.length===0)return;let o=We(e,!1);mt(e,o,t);let a=new Set(r.flatMap((c)=>c.change.gone));for(let c of s.filter((l)=>a.has(l)))console.log(`${c} left its market — ttheme keeps the copy you have`);let u=new Map(n.map((c)=>[c.name,c.pictures]));await Pn(e,je(e,o,!1).palettes.filter((c)=>s.includes(c.name)&&u.has(c.name)).map((c)=>Ci(c,u.get(c.name))),t.terminals)}async function zb(e=ue()){try{if(!NM(tr(e)))return;let t=ne(e),n=sf(e,t);if(n.length===0)return;let r=In(e),i=wr(`Checking ${n.map(ye).join(", ")} for updates`),s=(await Promise.allSettled(n.map((a)=>eo(e,a,rf)))).flatMap((a)=>a.status==="fulfilled"?[a.value]:[]);i.done();let o=s.flatMap((a)=>af(a)??[]);if(o.length===0)return;for(let a of o)console.log(a);await eu(e,t,r,s)}catch{return}}var Xb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,WM=["add","remove","search","init"];function ff(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function UM(){try{let e=LM("gh",["api","user","--jq",".login"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim().toLowerCase();return Xb.test(e)?e:void 0}catch{return}}async function jM(e,t){if(t.author)return t.author;let n=UM();if(!n){if(!ff())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 nc({message:"Your GitHub handle — your palettes are named <handle>@<market>/<palette>",validate:(i)=>Xb.test((i??"").toLowerCase())&&(i??"").length<=39?void 0:"that is not a GitHub handle"});if(ht(r))throw Error("no handle given");n=r.toLowerCase()}return hn(e,{...t,author:n}),console.log(`Your palettes are named ${n}@<market>/<palette>`),n}function Wi(e,t){if(t===ee)return ee;return xe(t)?Et(un(t)):Ni(t,or(e,t))}function tu(e,t){try{return Wi(e,t)}catch{return}}function Db(e){return Me(e)??ee}function nu(e){return We(e).palettes.filter((t)=>Me(t.name)===void 0)}function KM(e){let t=jr(import.meta.dirname,"..","dist","manifest.json");return uf(t)?cn(lf(t,"utf8")).palettes:nu(e)}function no(e,t,n){let{updates:r,...i}=e,s=Object.entries(n).filter(([o,a])=>t.includes(o)&&a!==nr(o,{}));return{...i,markets:t,...s.length>0?{updates:Object.fromEntries(s)}:{}}}function ew(e,t,n,r){return t.find((i)=>i!==n&&!Ii(i,n)&&tu(e,i)===r)}function cf(e,t,n,r){let i=ne(e),s=st(i.markets),o=ew(e,s,t,n);if(o)throw Error(`${n} already names the market at ${ye(o)} — \`ttheme market remove ${n}\` first`);let a=r===void 0?{...i.updates}:{...i.updates,[t]:r};hn(e,no(i,s.includes(t)?s:[...s,t],a))}async function BM(e){if(!ff())return!1;let t=await An({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 tw(e){let t=wr(`Fetching ${ye(e)}`);try{return await Ds(e)}finally{t.done()}}async function JM(e,t,n){let r=await tw(n),i=ne(e),s=st(i.markets),o=ew(e,s,n,r.id);if(o)throw Error(`${r.id} already names the market at ${ye(o)} — \`ttheme market remove ${r.id}\` first`);let{[t]:a,...u}=i.updates??{},c=a===void 0?u:{...u,[n]:a};return hn(e,no(i,s.map((l)=>l===t?n:l),c)),_i(e,r),r}async function df(e,t){let n=rr(t),r=st(ne(e).markets);if(r.includes(n))return console.log(`${ye(n)} is already added`),{source:n,id:Wi(e,n),fresh:!1};let i=yt(n)?r.find((u)=>yt(u)&&Ii(u,n)):void 0;if(i){let u=await JM(e,i,n);return console.log(`Moved ${u.id} to ${il(n)??"its default branch"} · ${ye(n)} — ${dt(Xe(u.entries).length)}`),{source:n,id:u.id,fresh:!1}}if(xe(n)){let u=Et(un(n));cf(e,n,u);let c=sr(n,u,nu(e)).length;return console.log(`Added ${u} · ${ye(n)} — ${dt(c)}, read in place`),{source:n,id:u,fresh:!0}}let s=await tw(n),o=n===ee?void 0:await BM(s.id);cf(e,n,s.id,o),_i(e,s);let a=dt(Xe(s.entries).length);return console.log(n===ee?`Added the ttheme catalog — ${a}`:`Added ${s.id} · ${ye(n)} — ${a}${o?", updating on its own":""}`),{source:n,id:s.id,fresh:!0}}async function qM(e){let t=ue(),{source:n,id:r,fresh:i}=await df(t,e);if(!i)return;if(xe(n))console.log("\n`ttheme browse` picks them · `ttheme market build` there writes the index others fetch");else if(n===ee)console.log("\n`ttheme browse` picks them");else console.log(`
418
+ \`ttheme browse\` picks them, or \`ttheme add ${r}/<palette>\``)}function hf(e,t){if(t===ee)Yb(zt(e),{force:!0});else if(yt(t))Yb(qt(e,t),{force:!0})}function gf(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 zM(e){let t=ue(),n=ne(t),r=st(n.markets),i=r.find((c)=>tu(t,c)===e)??r.find((c)=>c===nw(e));if(!i)throw Error(`no market named ${e} — \`ttheme market\` lists them`);let s=tu(t,i),o=n.palettes.filter((c)=>Db(c)===s),a=r.filter((c)=>c!==i),u=no(n,a,n.updates??{});if(hn(t,u),hf(t,i),mt(t,We(t),u),console.log(`Removed ${s??e} · ${ye(i)}`),o.length>0)console.log(gf(o))}function nw(e){try{return rr(e)}catch{return}}function VM(e,t){try{if(t===ee)return Xe(cn(lf(zt(e),"utf8")).palettes).length;if(xe(t))return sr(t,Wi(e,t),nu(e),!1).length;return or(e,t).palettes.length}catch{return}}function mf(e,t,n=Rn(),r=Date.now()){if(xe(t))return"read in place";let i=n[t],s=Xs(e,t);if(i&&(s===void 0||i.at>s))return`update failed ${to(i.at,r)}`;return s===void 0?"never updated":`updated ${to(s,r)}`}function YM(){let e=ue(),t=ne(e),n=st(t.markets);if(n.length===0){console.log("No markets — `ttheme market add official` brings the ttheme catalog back");return}let r=Rn(),i=n.map((a)=>{let u=tu(e,a)??"?",c=VM(e,a),l=t.palettes.filter((d)=>Db(d)===u).length,f=xe(a)?[]:[`auto-update ${nr(a,t.updates)?"on":"off"}`];return{name:u,where:ye(a),note:[c===void 0?"Unreadable":dt(c),...l>0?[`${l} installed`]:[],...f,mf(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 pf(e){return`${e.owner.login.toLowerCase()}/${e.name}`}async function bf(e,t){let n=encodeURIComponent(`topic:${Mi}${e?` ${e}`:""}`);try{let{items:r}=await Ls(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=50`,(i)=>JSON.parse(i),void 0,t);return r}catch(r){if(r instanceof Ia)throw Error("GitHub lets a search through about ten times a minute without signing in — try again in a minute");throw r}}async function QM(e){let t=ue(),n=await bf(e);if(n.length===0){console.log(`No repository carries the ${Mi} topic${e?` and matches ${e}`:""} yet`);return}let r=new Set(st(ne(t).markets).map(er)),i=n.map((o)=>{let a=pf(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 ZM=`name: ttheme market
419
419
 
420
420
  on:
421
421
  push:
@@ -430,16 +430,16 @@ jobs:
430
430
  runs-on: ubuntu-latest
431
431
  steps:
432
432
  - uses: kecan0406/ttheme/market@v1
433
- `;function tw({name:e}){return`ttheme-${e}`}function YM(e,t){qb($a(e),{recursive:!0}),qb(jr(e,".github","workflows"),{recursive:!0}),nw(e,t,[]),K(jr(e,".github","workflows","ttheme.yml"),zM),K(jr(e,"README.md"),`# ${Et(t)}
433
+ `;function rw({name:e}){return`ttheme-${e}`}function XM(e,t){Vb(ka(e),{recursive:!0}),Vb(jr(e,".github","workflows"),{recursive:!0}),iw(e,t,[]),K(jr(e,".github","workflows","ttheme.yml"),ZM),K(jr(e,"README.md"),`# ${Et(t)}
434
434
 
435
435
  A [ttheme](https://github.com/kecan0406/ttheme) market:
436
436
 
437
437
  \`\`\`sh
438
- ttheme market add ${t.owner}/${tw(t)}
438
+ ttheme market add ${t.owner}/${rw(t)}
439
439
  ttheme browse
440
440
  \`\`\`
441
- `)}function nw(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Hs(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};K(jr(e,an),`${JSON.stringify(a,null,2)}
442
- `)}function rw(e){return on(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function iw(){if(!cf())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await Du({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>rw((t??"").toLowerCase())});if(ht(e))throw Error("no market name given");return e.toLowerCase()}async function sw(e,t){let n=xr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===ew(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 iw();return ow(e,rl(e,s),s)}async function ow(e,t,n){let r=!of(jr(t,an)),i;if(r){let o=rw(n);if(o)throw Error(`the market name ${n} ${o}`);if(of(t)&&TM(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await _M(e,se(e)),name:n},YM(t,i)}else i=un(t);let s=Et(i);return af(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ye(t)}`),{dir:t,...i,id:s}}function Yb(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function QM(e){let t=le(),n=e&&!Yb(e)?e.toLowerCase():e?xM(rr(e)).toLowerCase():await iw(),r=e&&Yb(e)?rr(e):rl(t,n),i=await ow(t,r,n),s=`${i.owner}/${tw(i)}`;console.log(`
441
+ `)}function iw(e,{owner:t,name:n},r){let{version:i,gate:s,placement:o}=Ts(),a={version:i,gate:s,placement:o,owner:t,name:n,palettes:r};K(jr(e,an),`${JSON.stringify(a,null,2)}
442
+ `)}function sw(e){return on(`x@${e}/x`)?"takes lowercase letters, digits and single hyphens":void 0}async function ow(){if(!ff())throw Error("name the market: ttheme market init <name>, or --in <name> on new");let e=await nc({message:"Your market's name — its palettes are <you>@<name>/<palette>",validate:(t)=>sw((t??"").toLowerCase())});if(ht(e))throw Error("no market name given");return e.toLowerCase()}async function aw(e,t){let n=xr(e);if(t){let o=n.find((a)=>a.name===t||a.id===t||a.dir===nw(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 ow();return uw(e,ol(e,s),s)}async function uw(e,t,n){let r=!uf(jr(t,an)),i;if(r){let o=sw(n);if(o)throw Error(`the market name ${n} ${o}`);if(uf(t)&&CM(t).length>0)throw Error(`${t} is not empty — pick a new folder for the market`);i={owner:await jM(e,ne(e)),name:n},XM(t,i)}else i=un(t);let s=Et(i);return cf(e,t,s),console.log(`${r?"Made":"Added"} your market ${s} · ${ye(t)}`),{dir:t,...i,id:s}}function Qb(e){return e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}async function DM(e){let t=ue(),n=e&&!Qb(e)?e.toLowerCase():e?_M(rr(e)).toLowerCase():await ow(),r=e&&Qb(e)?rr(e):ol(t,n),i=await uw(t,r,n),s=`${i.owner}/${rw(i)}`;console.log(`
443
443
  \`ttheme new <palette> --from <palette>\` puts palettes in it, and a folder under palettes/ shelves them in a catalog — others see them once it is on GitHub:
444
444
 
445
445
  cd ${ye(r)}
@@ -447,16 +447,16 @@ ttheme browse
447
447
  gh repo create ${s} --public --source . --push
448
448
  gh repo edit ${s} --add-topic ${Mi}
449
449
 
450
- Its action rebuilds ${an} on every push; then \`ttheme market add ${s}\` works anywhere`)}function VM(e){let t=e?rr(e):process.cwd(),n=un(t),r=Et(n),i=GM(le()),s=new Map,o=[],a=[];for(let u of ir(t))try{let c=xs(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=vt(`${r}/${u.slug}`,uf(u.path,"utf8"),i),f=Bt({...l,name:u.slug});o.push(u.catalog?{...f,catalog:u.catalog}:f)}catch(c){a.push(` ${AM(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
+ Its action rebuilds ${an} on every push; then \`ttheme market add ${s}\` works anywhere`)}function eS(e){let t=e?rr(e):process.cwd(),n=un(t),r=Et(n),i=KM(ue()),s=new Map,o=[],a=[];for(let u of ir(t))try{let c=xs(u,s);if(c)throw Error(c);s.set(u.slug,u);let l=vt(`${r}/${u.slug}`,lf(u.path,"utf8"),i),f=Jt({...l,name:u.slug});o.push(u.catalog?{...f,catalog:u.catalog}:f)}catch(c){a.push(` ${GM(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:
451
451
  ${a.join(`
452
452
  `)}`),1;for(let u of o){let l=As(u).filter((d)=>d.startsWith(" ✗")),f=u.catalog?`${u.catalog}/${u.name}`:u.name;console.log(` ${f}${l.length>0?`
453
453
  ${l.join(`
454
- `)}`:" passes the gate"}`)}return nw(t,n,o),console.log(`
455
- ${r} · ${dt(o.length)} → ${jr(t,an)}`),0}async function aw(e,t){switch(e){case void 0:JM();return;case"add":await jM(Qb(e,t));return;case"remove":KM(Qb(e,t));return;case"search":await qM(t);return;case"init":await QM(t);return;case"build":return VM(t);default:throw Error(`unknown market action ${e} — ${LM.join(", ")}, or none to list them`)}}function Qb(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 uw(e,t){let n=Wi(e,t);return`${n} — ${dt(sr(t,n,eu(e),!1).length)}, read in place`}function ro(e,t){return`${e}/${t}`}function cw(e){return Me(e.name)?$i(e.name):e.name}function no(e){return e.catalog!==void 0&&fw(e.group)?ro(e.group,e.catalog):void 0}function pf(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${ro(e.group,e.name)}`;return e?.kind??""}function tu(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function lw(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)=>tu(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)=>no(d)!==void 0);for(let d of new Set(f.map((h)=>h.catalog))){let h=f.filter((b)=>b.catalog===d),g=r.length>0||t.has(ro(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)=>no(d)===void 0).map(o))}return i}function ZM(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||tu(i,n))).map((i)=>i.group));return lw(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function fw(e){return e.includes("@")}function bf(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 wf(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 XM(e){let t=e.findIndex((n)=>n.kind==="group"&&fw(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 DM(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var $r="\x1B[0m",io="\x1B[2m",so="\x1B[1m",Kr="\x1B[22m",$f="\x1B[36m",kf="\x1B[33m";function nu(e){return e==="decode"||e==="glitch"?e:"typewriter"}class oo{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+cw(t).length))}indent(e){return no(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===""||tu(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)=>tu(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"?ZM(this.entries,this.filter):lw(this.entries,this.expanded,this.filter);this.rows=n.length>0?XM([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[DM(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=pf(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>pf(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=bf(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)=>pf(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(ro(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=no(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?`${io}${"── Markets ──────────"}${$r}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(m)=>this.color?`${io}${m}${Kr}`:m,s=(m)=>this.color?`${so}${m}${Kr}`:m,o=(m)=>this.color?` ${ih(ba(m),r?Xt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${Xt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Go(n.selection,n.foreground)} ${m} ${$r}`:`${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?`${so}${Xt(c.entry.cursor)}${$}${Kr}\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"&&no(c.entry)===ro(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=cw(f),b=this.color?g.padEnd(this.namePad-h.length):g,p=t?s(b):b;return u(`${h}${d} ${p}${o(f)}`)}}function yf(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 ru{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 Ef extends Rt{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 oo({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 ru(e.fx??"typewriter",()=>yf(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=wf(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?`${io}${h}${$r}`:h,t=(h)=>this.color?`${$f}${h}${$r}`:h,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((h)=>`${t("│")} ${h}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",f=this.scope==="series"?"continue":"install",d=this.state==="error"?`${t("└")} ${this.color?`${kf}${this.error}${$r}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,s,...u,c,d].join(`
456
- `)}}var ao=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],vf=34,eS=72,tS=94,Mf={title:"",lines:[],brief:""};function iu(e){let t=e.trim();if(t!==ee&&!t.includes("/")&&!t.startsWith("~"))return;try{return rr(t)}catch{return}}function nS(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Sf extends Rt{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 oo({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new oo({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new ru(e.fx??"typewriter",()=>yf(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=wf(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=ao.findIndex((i)=>i.tab===this.tab),n=ao[(t+e+ao.length)%ao.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]=bf(this.cursor[n],e,r.length,(i)=>r[i]===!0)}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!xe(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>Ii(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(xe(e)||e===ee)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!iu(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=iu(this.filters.markets);if(i&&!n.some((o)=>Ii(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:gf(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?`${io}${e}${Kr}`:e}bold(e){return this.color?`${so}${e}${Kr}`:e}warn(e){return this.color?`${kf}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${Xt(e.cursor)}▌\x1B[39m ${Go(e.selection,e.foreground)} ${n} ${$r}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${ye(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!iu(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 ao.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 Mf;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=Cs(n),s=`Gate ${bt.length-i.length}/${bt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=Me(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${so}${Xt(n.cursor)}${n.name}${Kr}\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 Mf;if(e.kind==="market"){let i=e.market,s=i.source===ee?"The ttheme catalog":i.shown,o=i.entries.filter((h)=>!h.default),a=o.filter((h)=>this.installed.has(h.name)).map((h)=>h.name),u=`${dt(o.length)} · ${a.length} installed`,c=xe(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??nS(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,"",xe(i.source)?c:`${c} ${this.dim("←→")}`,...xe(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,...xe(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(ye(e.source)),lines:["Not added","",...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&&!iu(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}:Mf}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?`${$f}${f}${$r}`:f;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=tS,r=n?Math.min(t-vf-4,eS):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()}`,bn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?vf:r-2);return[...n?u.map((f,d)=>`${nt(f,r)} ${this.dim("│")} ${nt(d===0?c.title:c.lines[d-1]??"",vf,!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(`
457
- `)}}import{existsSync as JN}from"node:fs";import{existsSync as Mo,mkdirSync as CN,readFileSync as nd}from"node:fs";import{dirname as _N}from"node:path";import{execFile as rS}from"node:child_process";import{createHash as mw}from"node:crypto";import{existsSync as iS,mkdtempSync as sS,readFileSync as uu,rmSync as oS,statSync as pw,writeFileSync as bw}from"node:fs";import{homedir as aS,tmpdir as uS}from"node:os";import{join as su}from"node:path";import{fileURLToPath as cS}from"node:url";import{promisify as lS}from"node:util";var mn=lS(rS),ou=67108864,fS=4096,Pf=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],dS=["text/uri-list","text/plain;charset=utf-8","text/plain"],If=[...Pf,"text/uri-list","text/plain"];function hS(e){try{return pw(e).isFile()}catch{return!1}}function gS(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 dw(e){if(/^file:\/\//i.test(e))try{return cS(e)}catch{return}if(e.startsWith("~/"))return su(aS(),e.slice(2));return e.startsWith("/")?e:void 0}function Ui(e,t=hS){let n=[];for(let r of e.replace(/\r\n?/g,`
454
+ `)}`:" passes the gate"}`)}return iw(t,n,o),console.log(`
455
+ ${r} · ${dt(o.length)} → ${jr(t,an)}`),0}async function cw(e,t){switch(e){case void 0:YM();return;case"add":await qM(Zb(e,t));return;case"remove":zM(Zb(e,t));return;case"search":await QM(t);return;case"init":await DM(t);return;case"build":return eS(t);default:throw Error(`unknown market action ${e} — ${WM.join(", ")}, or none to list them`)}}function Zb(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 lw(e,t){let n=Wi(e,t);return`${n} — ${dt(sr(t,n,nu(e),!1).length)}, read in place`}function io(e,t){return`${e}/${t}`}function fw(e){return Me(e.name)?$i(e.name):e.name}function ro(e){return e.catalog!==void 0&&hw(e.group)?io(e.group,e.catalog):void 0}function wf(e){if(e?.kind==="palette")return`palette ${e.entry.name}`;if(e?.kind==="group")return`group ${e.name}`;if(e?.kind==="catalog")return`catalog ${io(e.group,e.name)}`;return e?.kind??""}function ru(e,t){let n=t.toLowerCase();return[e.name,e.group,e.native??"",e.catalog??""].some((r)=>r.toLowerCase().includes(n))}function dw(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)=>ru(d,r)):u;if(r&&c.length===0)continue;let l=r.length>0||t.has(a.group);if(i.push({kind:"group",name:a.group,native:a.native,lead:u.find((d)=>d.lead)??a,expanded:l,count:c.length}),!l)continue;let f=c.filter((d)=>ro(d)!==void 0);for(let d of new Set(f.map((h)=>h.catalog))){let h=f.filter((b)=>b.catalog===d),g=r.length>0||t.has(io(a.group,d));if(i.push({kind:"catalog",group:a.group,name:d,lead:h[0],expanded:g,count:h.length}),g)i.push(...h.map(o))}i.push(...c.filter((d)=>ro(d)===void 0).map(o))}return i}function tS(e,t){let n=t.trim(),r=new Set(e.filter((i)=>!i.default&&(n===""||ru(i,n))).map((i)=>i.group));return dw(e,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function hw(e){return e.includes("@")}function $f(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 kf(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 nS(e){let t=e.findIndex((n)=>n.kind==="group"&&hw(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 rS(e){let t=e.findIndex((n)=>n.kind==="palette");return t===-1?0:t}var $r="\x1B[0m",so="\x1B[2m",oo="\x1B[1m",Kr="\x1B[22m",yf="\x1B[36m",Ef="\x1B[33m";function iu(e){return e==="decode"||e==="glitch"?e:"typewriter"}class ao{picked;scope;maxItems;named=[];series=[];color;onFocus;entries=[];seriesPad=0;namePad=0;expanded=new Set;rows=[];cursor=0;top=0;filter="";lastFocused="";constructor(e){this.picked=e.picked,this.scope=e.scope??"palette",this.maxItems=e.maxItems??12,this.color=e.color??!0,this.onFocus=e.onFocus,this.load(e.entries),this.rebuild("first")}load(e){this.entries=e,this.named=e.filter((t)=>!t.default),this.series=[...new Set(this.named.map((t)=>t.group))],this.seriesPad=Math.max(0,...this.series.map((t)=>t.length)),this.namePad=Math.max(0,...this.named.map((t)=>this.indent(t).length+fw(t).length))}indent(e){return ro(e)===void 0?" ":" "}setEntries(e){this.load(e),this.rebuild("stay")}setFilter(e){if(e!==this.filter)this.filter=e,this.rebuild("keep")}focusedRow(){return this.rows[this.cursor]}refocus(){this.lastFocused="",this.sync()}members(e,t){let n=this.scope==="palette"?this.filter.trim():"";return this.named.filter((r)=>r.group===e&&(t===void 0||r.catalog===t)&&(n===""||ru(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)=>ru(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"?tS(this.entries,this.filter):dw(this.entries,this.expanded,this.filter);this.rows=n.length>0?nS([{kind:"all",count:this.allCount(n)},...n]):[];let r=n.length>0?this.rows.indexOf(n[rS(n)]):0;if(e==="first")this.cursor=r;else if(e==="keep"||e==="stay"){let i=wf(t),s=t?.kind==="palette"||e==="stay"?this.rows.findIndex((o)=>wf(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=$f(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)=>wf(n)===t)),this.sync()}fold(e){if(this.filter||this.scope==="series")return;let t=this.rows[this.cursor];if(t?.kind==="group"){if(e!==t.expanded)this.toggle(t.name)}else if(t?.kind==="catalog"){if(e!==t.expanded)this.toggle(io(t.group,t.name));else if(!e)this.climb(t.group,`group ${t.group}`)}else if(t?.kind==="palette"&&!e&&!t.entry.default){let n=ro(t.entry);if(n===void 0)this.climb(t.entry.group,`group ${t.entry.group}`);else this.climb(n,`catalog ${n}`)}}window(){if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let e=this.rows.slice(this.top,this.top+this.maxItems);return{lines:e.map((t,n)=>this.renderRow(t,this.top+n===this.cursor)),below:this.rows.length-this.top-e.length}}renderRow(e,t){if(e.kind==="rule")return` ${this.color?`${so}${"── Markets ──────────"}${$r}`:"── Markets ──────────"}`;let n=e.kind==="palette"?e.entry:e.kind==="all"?void 0:e.lead,r=this.color&&t&&n!==void 0,i=(m)=>this.color?`${so}${m}${Kr}`:m,s=(m)=>this.color?`${oo}${m}${Kr}`:m,o=(m)=>this.color?` ${ah(wa(m),r?Xt(m.foreground):"\x1B[39m")}`:"",a=t?r?`${Xt(n.cursor)}▌\x1B[39m `:"▌ ":" ",u=(m)=>r?`${a}${Wo(n.selection,n.foreground)} ${m} ${$r}`:`${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?`${oo}${Xt(c.entry.cursor)}${$}${Kr}\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"&&ro(c.entry)===io(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=fw(f),b=this.color?g.padEnd(this.namePad-h.length):g,p=t?s(b):b;return u(`${h}${d} ${p}${o(f)}`)}}function vf(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 su{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 Mf extends Ft{picked;list;scope;color;hint;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output,validate:e.required?()=>this.picked.size===0?`Pick at least one ${this.scope}`:void 0:void 0},!0);this.scope=e.scope??"palette",this.picked=new Set(e.installed??[]),this.color=e.color??!0,this.list=new ao({entries:e.entries,picked:this.picked,scope:this.scope,...e.maxItems===void 0?{}:{maxItems:e.maxItems},color:this.color,...e.onFocus?{onFocus:e.onFocus}:{}}),this.hint=new su(e.fx??"typewriter",()=>vf(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=kf(n?.name,this.list.maxItems);if(r!==void 0)this.list.move(r);else if(n?.name==="space")this.list.pick()})}_isActionKey(e){return e==="\t"||e===" "}draw(){let e=(h)=>this.color?`${so}${h}${$r}`:h,t=(h)=>this.color?`${yf}${h}${$r}`:h,n=this.scope==="series"?"Series":"Catalog";if(this.state==="submit")return`${e("◇")} ${n} ${e(`· ${this.list.pickedCount()} picked`)}`;if(this.state==="cancel")return`${e(`◇ ${n} · cancelled`)}`;let r=`${t("◆")} ${n} ${e(`(${this.list.matched()}/${this.list.total()} · ${this.list.pickedCount()} picked)`)}`,i=this.hint.text(),s=`${t("│")} ${this.userInput?`${this.userInput}_`:e(`Search…${i?` e.g. ${i}`:""}`)}`,{lines:o,below:a}=this.list.window(),u=o.length>0?o.map((h)=>`${t("│")} ${h}`):[`${t("│")} ${e(`No ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(u.length<this.list.maxItems)u.push(t("│"));let c=a>0?`${t("│")} ${e(`↓ ${a} more`)}`:t("│"),l=this.scope==="series"?"":" · ←→ fold",f=this.scope==="series"?"continue":"install",d=this.state==="error"?`${t("└")} ${this.color?`${Ef}${this.error}${$r}`:this.error}`:`${t("└")} ${e(`↑↓ move${l} · space pick · type to filter · enter ${f} · esc cancel`)}`;return[r,s,...u,c,d].join(`
456
+ `)}}var uo=[{tab:"catalog",title:"Catalog"},{tab:"installed",title:"Installed"},{tab:"markets",title:"Markets"},{tab:"errors",title:"Errors"}],Sf=34,iS=72,sS=94,If={title:"",lines:[],brief:""};function ou(e){let t=e.trim();if(t!==ee&&!t.includes("/")&&!t.startsWith("~"))return;try{return rr(t)}catch{return}}function oS(e){return e.charAt(0).toUpperCase()+e.slice(1)}class Nf extends Ft{picked;tab="catalog";filters={catalog:"",installed:"",markets:"",errors:""};cursor={markets:0,errors:0};top={markets:0,errors:0};adds=new Map;removes=new Set;want=new Map;busy=new Map;failed=new Map;refreshed=[];inflight=new Set;markets;problems;kept;installed;startup;io;order;color;maxItems;paint;catalog;mine;hint;asking;repos;searching=!1;searchError;lastInput="";constructor(e){super({render:()=>this.draw(),input:e.input,output:e.output},!0);this.markets=e.markets,this.problems=e.problems,this.kept=e.kept,this.installed=new Set(e.installed),this.startup=e.startup,this.io=e.io,this.order=e.order??((n)=>n),this.color=e.color??!0,this.maxItems=e.maxItems??12,this.paint=e.onFocus,this.picked=new Set(e.installed);let t=this.entries();this.catalog=new ao({entries:t,picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("catalog",n)}),this.mine=new ao({entries:this.mineOf(t),picked:this.picked,color:this.color,maxItems:this.maxItems,onFocus:(n)=>this.focus("installed",n)}),this.hint=new su(e.fx??"typewriter",()=>vf(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=kf(t?.name,this.maxItems);if(n!==void 0)this.move(n);else if(t?.name==="tab")this.switchTab(t.shift?-1:1);else if(t?.name==="space")this.activate();else if(t?.ctrl&&t.name==="r"){let r=this.tab==="markets"?this.marketRow():void 0;if(r?.kind==="market"&&!this.adds.has(r.market.source))this.update(r.market.source)}}redraw(){if(this.state==="active"||this.state==="error")this.output.emit("resize")}focus(e,t){if(this.tab===e&&this.state!=="submit"&&this.state!=="cancel")this.paint?.(t)}track(e){this.inflight.add(e);let t=()=>this.inflight.delete(e);return e.then(t,t),e}list(){return this.tab==="catalog"?this.catalog:this.tab==="installed"?this.mine:void 0}active(){return[...this.markets.filter((e)=>!this.removes.has(e.source)),...this.adds.values()]}entries(){let e=this.active().flatMap((i)=>i.entries),t=new Set(e.map((i)=>i.name)),n=new Map,r=this.markets.filter((i)=>this.removes.has(i.source)).flatMap((i)=>i.entries);for(let i of[...this.kept,...r])if(this.installed.has(i.name)&&!t.has(i.name))n.set(i.name,i);return this.order([...e,...n.values()])}mineOf(e){return e.filter((t)=>this.installed.has(t.name))}reload(){let e=this.entries();this.catalog.setEntries(e),this.mine.setEntries(this.mineOf(e))}switchTab(e){let t=uo.findIndex((i)=>i.tab===this.tab),n=uo[(t+e+uo.length)%uo.length]?.tab??"catalog",r=this.filters[n];this.tab=n,this._clearUserInput(),this._setUserInput(r,!0),this.lastInput=r,this.list()?.refocus()}move(e){let t=this.list();if(t){t.move(e);return}let n=this.tab==="markets"?"markets":"errors",r=n==="markets"?this.marketRows().map((i)=>i.kind==="rule"):this.problemRows().map(()=>!1);this.cursor[n]=$f(this.cursor[n],e,r.length,(i)=>r[i]===!0)}side(e){let t=this.list();if(t){t.fold(e);return}let n=this.tab==="markets"?this.marketRow():void 0;if(n?.kind==="market"&&!xe(n.market.source))if(e===n.market.auto)this.want.delete(n.market.source);else this.want.set(n.market.source,e)}activate(){let e=this.list();if(e){e.pick();return}let t=this.tab==="markets"?this.marketRow():void 0;if(t?.kind==="market")this.toggleMarket(t.market);else if(t?.kind==="add")this.fetch(t.source);else if(t?.kind==="repo"){let n=this.known(t.source),r=this.marketRows().findIndex((i)=>i.kind==="market"&&i.market===n);if(n&&r>=0)this.cursor.markets=r;else if(!n)this.fetch(t.source)}else if(t?.kind==="find")this.search()}toggleMarket(e){if(this.adds.has(e.source))this.adds.delete(e.source),this.want.delete(e.source);else if(this.removes.has(e.source))this.removes.delete(e.source);else this.removes.add(e.source);this.reload()}known(e){return[...this.markets,...this.adds.values()].find((t)=>Ii(t.source,e))}fetch(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Fetching…"),this.track(this.io.fetch(e)).then((t)=>{this.busy.delete(e);let n=this.active().find((r)=>r.id===t.id);if(n)this.failed.set(e,`${t.id} already names the market at ${n.shown}`);else if(xe(e)||e===ee)this.stage(t,t.auto);else this.asking=t;this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,t.message),this.redraw()})}answer(e){let t=this.asking;if(this.asking=void 0,t)this.stage(t,e)}stage(e,t){if(this.adds.set(e.source,e),t===e.auto)this.want.delete(e.source);else this.want.set(e.source,t);this.reload(),this.cursor.markets=Math.max(0,this.marketRows().findIndex((n)=>n.kind==="market"&&n.market.source===e.source))}update(e){if(this.busy.has(e))return;this.failed.delete(e),this.busy.set(e,"Updating…"),this.track(this.io.refresh(e)).then(({market:t,refreshed:n})=>{this.busy.delete(e),this.markets=this.markets.map((r)=>r.source===e?t:r),this.problems=this.problems.filter((r)=>r.source!==e),this.refreshed.push(n),this.reload(),this.redraw()},(t)=>{this.busy.delete(e),this.failed.set(e,`Update failed: ${t.message}`),this.redraw()})}search(){if(this.searching)return;this.searching=!0,this.searchError=void 0;let e=this.filters.markets.trim();this.track(this.io.search(e&&!ou(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=ou(this.filters.markets);if(i&&!n.some((o)=>Ii(o.source,i)))r.push({kind:"add",source:i});r.push({kind:"find"});let s=(this.repos??[]).map((o)=>({repo:o,source:pf(o)})).filter(({repo:o,source:a})=>t(a,o.description??""));if(s.length>0)r.push({kind:"rule"},...s.map(({repo:o,source:a})=>({kind:"repo",repo:o,source:a})));return r}marketRow(){let e=this.marketRows();return e[Math.min(this.cursor.markets,e.length-1)]}problemList(){let e=new Map([...this.markets,...this.adds.values()].map((t)=>[t.source,t.id]));return[...this.problems.filter((t)=>!(t.update&&t.source&&this.failed.has(t.source))),...[...this.failed].map(([t,n])=>({where:e.get(t)??t,message:n,source:t}))]}problemRows(){let e=this.filters.errors.trim().toLowerCase();return this.problemList().filter((t)=>e===""||`${t.where} ${t.message}`.toLowerCase().includes(e))}windowOf(e,t,n,r=()=>!1){let i=Math.min(this.cursor[t],Math.max(0,e.length-1));if(r(e[i]))i-=1;this.cursor[t]=i;let s=Math.min(this.top[t],i);if(i>=s+this.maxItems)s=i-this.maxItems+1;s=Math.max(0,Math.min(s,e.length-this.maxItems)),this.top[t]=s;let o=e.slice(s,s+this.maxItems);return{lines:o.map((a,u)=>n(a,s+u===i)),below:e.length-s-o.length}}dim(e){return this.color?`${so}${e}${Kr}`:e}bold(e){return this.color?`${oo}${e}${Kr}`:e}warn(e){return this.color?`${Ef}${e}\x1B[39m`:e}lit(e,t,n){if(t&&this.color&&e)return`${Xt(e.cursor)}▌\x1B[39m ${Wo(e.selection,e.foreground)} ${n} ${$r}`;return`${t?"▌ ":" "} ${n}`}status(e){return this.adds.has(e.source)?"Will add":this.removes.has(e.source)?"Will remove":this.busy.get(e.source)??(this.failed.has(e.source)||e.status.startsWith("update failed")?"Update failed":"")}marketLine(e,t){if(e.kind==="rule")return` ${this.dim("── On GitHub ──────────")}`;if(e.kind==="market"){let i=e.market,s=this.status(i),o=this.removes.has(i.source)?"○":"●",a=t?this.bold(i.id):i.id;return this.lit(i.entries.find((u)=>!u.default),t,`${o} ${a}${s?` ${this.dim(s)}`:""}`)}if(e.kind==="add"){let i=this.busy.get(e.source);return this.lit(void 0,t,`+ Add ${ye(e.source)}${i?` ${this.dim(i)}`:""}`)}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searching?"Searching GitHub…":i&&!ou(i)?`Find "${i}" on GitHub`:"Find markets on GitHub";return this.lit(void 0,t,`⌕ ${s}`)}let n=this.busy.get(e.source),r=this.known(e.source)?"●":"○";return this.lit(void 0,t,`${r} ${e.source} ${this.dim(`★${e.repo.stargazers_count}`)}${n?` ${this.dim(n)}`:""}`)}problemLine(e,t){return this.lit(void 0,t,`${this.warn("✗")} ${e.where} ${this.dim(e.message)}`)}body(){let e=this.list();if(e){let n=this.filters[this.tab];return{...e.window(),empty:n?`No palettes match '${n}'`:this.tab==="installed"?"Nothing installed yet":"No palettes"}}if(this.tab==="markets")return{...this.windowOf(this.marketRows(),"markets",(n,r)=>this.marketLine(n,r),(n)=>n?.kind==="rule"),empty:""};let t=this.filters.errors;return{...this.windowOf(this.problemRows(),"errors",(n,r)=>this.problemLine(n,r)),empty:t?`No problems match '${t}'`:"No problems"}}changes(){return this.adds.size+this.removes.size+this.want.size}counts(){let e=[...this.busy.values()].includes("Updating…")?"Updating… · ":"",t=this.list();if(t)return`${e}${t.matched()}/${t.total()} · ${t.pickedCount()} picked`;if(this.tab==="markets"){let n=this.markets.length+this.adds.size,r=this.marketRows().filter((s)=>s.kind==="market").length,i=this.changes();return`${e}${r}/${n} markets${i>0?` · ${i} to apply`:""}`}return`${this.problemRows().length}/${this.problemList().length}`}searchText(){if(this.userInput)return`${this.userInput}_`;if(this.tab==="markets")return this.dim("Search… or add one: owner/repo");let e=this.tab==="errors"?"":this.hint.text();return this.dim(`Search…${e?` e.g. ${e}`:""}`)}tabBar(){return uo.map(({tab:e,title:t})=>{let n=e==="errors"?this.problemList().length:0,r=n>0?`${t} ${n}`:t;if(!this.color)return e===this.tab?`[${r}]`:` ${r} `;return e===this.tab?this.bold(r):this.dim(r)}).join(this.color?" ":" ")}sourceOf(e){let t=this.active().find((n)=>n.entries.some((r)=>r.name===e.name));if(!t)return"In no market you added";return t.source===ee?"The ttheme catalog":t.shown}paletteState(e){let t=this.picked.has(e.name),n=this.installed.has(e.name),r=t&&n?"Installed":t?"Will install":n?"Will remove":"Not installed";return this.startup===e.name?`${r} · Default`:r}paletteDetail(e,t){if(!e||e.kind==="rule")return If;if(e.kind==="all")return{title:this.bold("Select all"),lines:["space picks every palette shown"],brief:""};if(e.kind==="group"){let c=this.entries().filter((d)=>d.group===e.name&&!d.default),l=this.sourceOf(e.lead),f=`${dt(c.length)} · ${c.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(e.name),lines:[...e.native?Qe(e.native,t).map((d)=>this.dim(d)):[],...Qe(l,t),f],brief:`${l} · ${f}`}}if(e.kind==="catalog"){let c=this.entries().filter((d)=>d.group===e.group&&d.catalog===e.name),l=this.sourceOf(e.lead),f=`${dt(c.length)} · ${c.filter((d)=>this.installed.has(d.name)).length} installed`;return{title:this.bold(e.name),lines:[e.group,...Qe(l,t),f],brief:`${e.group} · ${f}`}}let n=e.entry,r=this.sourceOf(n),i=Cs(n),s=`Gate ${bt.length-i.length}/${bt.length}`,o=n.pictures?.length??0,a=[...o>0?[`${o} picture${o===1?"":"s"}`]:[],...n.base?[`Base ${n.base}`]:[]].join(" · "),u=Me(n.name)?n.catalog?[n.catalog]:[]:[n.group,...n.native?[this.dim(n.native)]:[]];return{title:this.color?`${oo}${Xt(n.cursor)}${n.name}${Kr}\x1B[39m`:n.name,lines:[...Qe(r,t),...u,this.paletteState(n),"",i.length===0?`${s} · passes`:s,...i.flatMap((c)=>Qe(c,t-2).map((l,f)=>`${f===0?this.warn("✗"):" "} ${l}`)),...a?["",a]:[]],brief:[r,s,...a?[a]:[],this.paletteState(n)].join(" · ")}}marketDetail(e,t){if(!e||e.kind==="rule")return If;if(e.kind==="market"){let i=e.market,s=i.source===ee?"The ttheme catalog":i.shown,o=i.entries.filter((h)=>!h.default),a=o.filter((h)=>this.installed.has(h.name)).map((h)=>h.name),u=`${dt(o.length)} · ${a.length} installed`,c=xe(i.source)?"Read in place":`Auto-update ${this.want.get(i.source)??i.auto?"on":"off"}`,l=this.busy.get(i.source)??oS(i.status),f=this.failed.get(i.source),d=this.adds.has(i.source)?["Will add"]:this.removes.has(i.source)?[a.length>0?`Will remove — ${a.join(", ")} stay${a.length===1?"s":""} installed`:"Will remove"]:this.want.has(i.source)?[`Auto-update turns ${this.want.get(i.source)?"on":"off"}`]:[];return{title:this.bold(i.id),lines:[...Qe(s,t),u,"",xe(i.source)?c:`${c} ${this.dim("←→")}`,...xe(i.source)?[]:[l],...f?Qe(f,t).map((h)=>this.warn(h)):[],...d.length>0?["",...d.flatMap((h)=>Qe(h,t))]:[]],brief:[s,c,...d,...xe(i.source)?[]:[l]].join(" · ")}}if(e.kind==="add"){let i=this.busy.get(e.source)??this.failed.get(e.source)??"space fetches its index";return{title:this.bold(ye(e.source)),lines:["Not added","",...Qe(i,t)],brief:i}}if(e.kind==="find"){let i=this.filters.markets.trim(),s=this.searchError??(this.searching?"Searching…":this.repos?`${this.repos.length} found`:"space searches GitHub");return{title:this.bold("GitHub"),lines:[...Qe(`Repositories with the ${Mi} topic`,t),...i&&!ou(i)?[`Matching "${i}"`]:[],"",...Qe(s,t)],brief:s}}let r=this.known(e.source)?"Added":this.busy.get(e.source)??this.failed.get(e.source)??"space adds it";return{title:this.bold(e.source),lines:[`★ ${e.repo.stargazers_count}`,...Qe(e.repo.description??"",t),"",...Qe(r,t)],brief:r}}detail(e){let t=this.list();if(t)return this.paletteDetail(t.focusedRow(),e);if(this.tab==="markets")return this.marketDetail(this.marketRow(),e);let n=this.problemRows(),r=n[Math.min(this.cursor.errors,n.length-1)];return r?{title:this.bold(r.where),lines:Qe(r.message,e),brief:r.message}:If}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?`${yf}${f}${$r}`:f;if(this.state==="submit")return`${this.dim("◇")} Browse ${this.dim(`· ${this.summary()}`)}`;if(this.state==="cancel")return this.dim("◇ Browse · cancelled");let t=this.columns(),n=t>=sS,r=n?Math.min(t-Sf-4,iS):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()}`,bn(`${e("│")} ${this.searchText()}`,this.dim(this.counts()),r),...a,s>0?`${e("│")} ${this.dim(`↓ ${s} more`)}`:e("│")],c=this.detail(n?Sf:r-2);return[...n?u.map((f,d)=>`${rt(f,r)} ${this.dim("│")} ${rt(d===0?c.title:c.lines[d-1]??"",Sf,!1)}`):[...u.map((f)=>rt(f,r,!1)),rt(`${e("│")} ${this.dim(c.brief)}`,r,!1)],rt(this.footer(e,n),t-1,!1)].join(`
457
+ `)}}import{existsSync as YN}from"node:fs";import{existsSync as So,mkdirSync as UN,readFileSync as id}from"node:fs";import{dirname as jN}from"node:path";import{execFile as aS}from"node:child_process";import{createHash as bw}from"node:crypto";import{existsSync as uS,mkdtempSync as cS,readFileSync as lu,rmSync as lS,statSync as ww,writeFileSync as $w}from"node:fs";import{homedir as fS,tmpdir as dS}from"node:os";import{join as au}from"node:path";import{fileURLToPath as hS}from"node:url";import{promisify as gS}from"node:util";var mn=gS(aS),uu=67108864,mS=4096,Of=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],pS=["text/uri-list","text/plain;charset=utf-8","text/plain"],Pf=[...Of,"text/uri-list","text/plain"];function bS(e){try{return ww(e).isFile()}catch{return!1}}function wS(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 gw(e){if(/^file:\/\//i.test(e))try{return hS(e)}catch{return}if(e.startsWith("~/"))return au(fS(),e.slice(2));return e.startsWith("/")?e:void 0}function Ui(e,t=bS){let n=[];for(let r of e.replace(/\r\n?/g,`
458
458
  `).split(`
459
- `)){let i=dw(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of gS(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=dw(s);if(o&&t(o))n.push(o)}}return n}function mS(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 hw(e){let t=di(e)?Jn(e):mS(e);if(!t)return;return{ext:di(e)?"png":"jpg",width:t.width,height:t.height}}async function au(e,t){let n=hw(e);if(n&&n.width*n.height<=$t)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${$t/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=sS(su(uS(),"ttheme-attach-"));try{let i=su(r,"in"),s=su(r,"out.png");bw(i,e);let o=!n||n.width*n.height>$t?["--resampleHeightWidthMax",String(fS)]:[];await mn("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(uu(s)),u=hw(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{oS(r,{recursive:!0,force:!0})}}async function Of(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":Fc},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>ou)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 au(r,e)}if(pw(e).size>ou)throw Error("that picture is over 64 MB");return au(new Uint8Array(uu(e)),e)}var ww=new Map,Br={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)=>ww.get(e)??"",parse:()=>[],count:()=>0};function $w(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function kw(e,t){ww.set(e,t)}function yw(e){return Number.parseInt(mw("sha1").update(e).digest("hex").slice(0,8),16)%Vn}var pS=`ObjC.import('AppKit')
459
+ `)){let i=gw(r.trim());if(i&&t(i)){n.push(i);continue}for(let s of wS(r)){if(/^https?:\/\/\S+$/i.test(s)){n.push(s);continue}let o=gw(s);if(o&&t(o))n.push(o)}}return n}function $S(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 mw(e){let t=di(e)?Jn(e):$S(e);if(!t)return;return{ext:di(e)?"png":"jpg",width:t.width,height:t.height}}async function cu(e,t){let n=mw(e);if(n&&n.width*n.height<=$t)return{bytes:e,...n,source:t};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${$t/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=cS(au(dS(),"ttheme-attach-"));try{let i=au(r,"in"),s=au(r,"out.png");$w(i,e);let o=!n||n.width*n.height>$t?["--resampleHeightWidthMax",String(mS)]:[];await mn("sips",["-s","format","png",...o,i,"--out",s]).catch(()=>{throw Error("that is not a picture macOS can read")});let a=new Uint8Array(lu(s)),u=mw(a);if(!u)throw Error("that is not a picture macOS can read");return{bytes:a,...u,source:t}}finally{lS(r,{recursive:!0,force:!0})}}async function Ff(e,t){if(/^https?:\/\//i.test(e)){let n=await fetch(e,{headers:{"User-Agent":xc},signal:t});if(!n.ok)throw Error(`${new URL(e).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>uu)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 cu(r,e)}if(ww(e).size>uu)throw Error("that picture is over 64 MB");return cu(new Uint8Array(lu(e)),e)}var kw=new Map,Br={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)=>kw.get(e)??"",parse:()=>[],count:()=>0};function yw(e){if(/^https?:\/\//i.test(e))return"";return e.split("/").pop()??e}function Ew(e,t){kw.set(e,t)}function vw(e){return Number.parseInt(bw("sha1").update(e).digest("hex").slice(0,8),16)%Qn}var kS=`ObjC.import('AppKit')
460
460
  function run(argv) {
461
461
  const pb = $.NSPasteboard.generalPasteboard
462
462
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -481,16 +481,16 @@ function run(argv) {
481
481
  if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
482
482
  const text = pb.stringForType('public.utf8-plain-text')
483
483
  return text && !text.isNil() ? text.js : ''
484
- }`,bS=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
484
+ }`,yS=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
485
485
  $c = [Windows.Forms.Clipboard]
486
486
  $f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
487
487
  $p = Join-Path $env:TEMP 'ttheme-clipboard.png'
488
488
  $s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
489
489
  $i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
490
- $c::GetText()`;function Ew(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(uu("/proc/version","utf8"))}catch{return!1}}async function wS(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await mn(n[0],n[1])).stdout.split(`
491
- `).map((o)=>o.trim()),i=(o)=>t?mn("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:ou}):mn("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:ou});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Pf.find((o)=>r.includes(o));if(s)return bw(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 Rf(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function vw(e){if(process.platform==="darwin"){let t=(await mn("osascript",["-l","JavaScript","-e",pS,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Ew()){let t=(await mn("powershell.exe",["-NoProfile","-STA","-Command",bS])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
490
+ $c::GetText()`;function Mw(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(lu("/proc/version","utf8"))}catch{return!1}}async function ES(e){let t=Boolean(process.env.WAYLAND_DISPLAY),n=t?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await mn(n[0],n[1])).stdout.split(`
491
+ `).map((o)=>o.trim()),i=(o)=>t?mn("wl-paste",["--no-newline","--type",o],{encoding:"buffer",maxBuffer:uu}):mn("xclip",["-selection","clipboard","-t",o,"-o"],{encoding:"buffer",maxBuffer:uu});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let s=Of.find((o)=>r.includes(o));if(s)return $w(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 Sw(e){if(process.platform==="darwin"){let t=(await mn("osascript",["-l","JavaScript","-e",kS,e])).stdout.trim();return t===e?{image:e}:{text:t}}if(Mw()){let t=(await mn("powershell.exe",["-NoProfile","-STA","-Command",yS])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(t.split(`
492
492
  `).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await mn("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
493
- `)}}if(process.platform==="linux")return wS(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var $S=`ObjC.import('AppKit')
493
+ `)}}if(process.platform==="linux")return ES(e);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var vS=`ObjC.import('AppKit')
494
494
  function run() {
495
495
  const pb = $.NSPasteboard.generalPasteboard
496
496
  const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
@@ -502,50 +502,51 @@ function run() {
502
502
  picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
503
503
  }
504
504
  return pb.changeCount + '\\t' + (picture ? 'picture' : '')
505
- }`;async function Mw(){if(Rf())return;if(process.platform==="darwin"){let[e="",t=""]=(await mn("osascript",["-l","JavaScript","-e",$S])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Ew()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await mn("wl-paste",["--list-types"])).stdout:(await mn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function cu(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:kS(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 kS(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 uo=(e)=>Buffer.from(e).toString("base64"),Nf=(e)=>Buffer.from(e,"base64");function gw(e,t){return t.find((n)=>e.includes(n))}class Ff{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=uo(mw("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;${If.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=${uo("ttheme")}:pw=${this.pw};${uo(".")}\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?Nf(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Nf(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=gw(s,[...Pf,...dS]);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=${uo(u)}:pw=${a};${uo(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=If.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=gw(a,If);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(Nf(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?Ui(a).find((c)=>iS(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(uu(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}import{readFileSync as yS}from"node:fs";var Je={pitch:25,cols:22,rows:9,height:13},qr={cols:25,rows:16},ES=2147483648,vS=-1073741826,MS=1600,Sw=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],SS=56,IS=4,Iw=20,NS=50,Nw=[["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",J="\x1B[2m",fo="\x1B[32m",pn="\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 du(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===`
506
- `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Cw="\x1B]1337;ReportCellSize\x07\x1B[16t\x1B[14t\x1B[18t",Pw="\x1B]1337;ReportCellSize=";function Lf(e){let t=e.indexOf(Pw);if(t!==-1){let o=e.slice(t+Pw.length),a=[o.indexOf("\x07"),o.indexOf("\x1B\\")].filter((l)=>l!==-1),u=a.length>0?Math.min(...a):-1,c=u===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(o.slice(0,u));if(c){let l=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*l),w:Math.round(Number(c[2])*l)},rest:e.slice(0,t)+o.slice(u+(o[u]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(r)return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)};let i=Ow(e,4),s=Ow(e,8);if(!i||!s||s.a===0||s.b===0)return null;return{cell:{h:Math.floor(i.a/s.a),w:Math.floor(i.b/s.b)},rest:e.replace(i.text,"").replace(s.text,"")}}function Ow(e,t){let n=e.indexOf(`\x1B[${t};`),r=n===-1?null:new RegExp(`^\\[${t};(\\d+);(\\d+)t`).exec(e.slice(n+1));return r?{a:Number(r[1]),b:Number(r[2]),text:`\x1B${r[0]}`}:null}function zr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Je.pitch)),rowsVis:Math.max(1,Math.floor(n/Je.height)),height:n}}function _w(e,t=!0){if(t)return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`;let n;try{n=yS(e.path).toString("base64")}catch{return}let r=n.match(/.{1,4096}/g)??[""];return r.map((i,s)=>{let o=s<r.length-1?1:0;return s===0?`\x1B_Ga=t,f=100,i=${e.id},m=${o},q=2;${i}\x1B\\`:`\x1B_Gm=${o},q=2;${i}\x1B\\`}).join("")}function Gw(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 Cf(e){return`\x1B_Ga=d,d=i,i=${e},p=${e},q=2\x1B\\`}function Ww(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function ji(e){return`\x1B[38;2;${ve(e).join(";")}m`}function fu(e){return`\x1B[48;2;${ve(e).join(";")}m`}var Hf=!1;function hu(e){return Hf=!0,e.beat}function Ki(e){return Sw[hu(e)%Sw.length]}function _e(e){return $e(e)}function Uw(e,t){if($e(e)<=t)return e;let n="";for(let r of e){if($e(n+r)>t)break;n+=r}return n}function Bi(e){return`\x1B[${30+e}m`}function Ji(e,t,n,r){return n?[[`${ss} `,r],[e,t,n]]:[[e,t]]}function Tf(e){return e.reduce((t,[n])=>t+_e(n),0)}function RS(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([`${Uw(i,r)}…`,s,o]);break}return n}class lu{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=Uw(n,this.cols-t);e+=`\x1B[${t+1}G${r}${Wo(s,i)}${r?PS:""}`}return e}}function FS(e){return e.replace(/_\([^)]*\)?$/,"")}function jw(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<MS?pn:J]}function ho(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Tf(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=RS(s,Math.max(0,Tf(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}`,J]])].forEach((l,f)=>{u=e.run(u+(f?3:0),l)}),o)e.right(t,[[o[0],Qe],[` ${o[1]}`,J]])}function HS(e,t){if(e==="d")return J;if(e==="b")return Qe;if(e==="s")return fu(t.colors.selection);if(e==="c")return fu(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=_t.indexOf(Ia(r.scene)),o=_t.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Qe+i:J]]),a=o.reduce((u,[c])=>u+_e(c),0)<=n;e?.run(t,a?o:[[Ia(r.scene).name,Qe+i],[` ${s+1}/${_t.length}`,J]])}function xS(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<kp?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let d=0;d<8;d++)l=(e[t]?.put(l,"▀".repeat(c),ji(a[d]??u)+fu(a[d+8]??u))??l)+1;let f=t+2;for(let d of Ia(s.scene).lines){let h=yp(d,r);if(!h)continue;if(f>i)return;e[f]?.run(n,h.map(([g,b])=>[g,HS(b,s)])),f++}}function AS(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 Rw(e){return e.replace(/^https?:\/\/(?:www\.)?/,"")}function LS(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Bi(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?Ji(Rw(s.page),"",s.page,a):[["—",J]]],["Source",s?.source?Ji(Rw(s.source),"",s.link,i):[["—",J]]],["Artist",[o.length>0?[o.join(" "),""]:["—",J]]]].forEach(([c,l],f)=>{e[t+f]?.put(n,c,J),e[t+f]?.run(n+12,l)})}function 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?[za(u.bytes)]:[]].join(" · "),d=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),h=(p,m)=>p.length>0?AS(p,l,m).map(($)=>[[$,""]]):[[["—",J]]],g=[["Characters",h(o.characters,2)],["Series",h(o.series,1)],["Tags",h(o.tags,3)],["Rating",[[[d,d==="—"?J:""]]]],["File",[[[f,""],...u?[[" ",""]]:[],...u?Kw(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",J]]]]],b=t;for(let[p,m]of g){if(b+m.length-1>i)return;e[b]?.put(n,p,J);for(let $ of m)e[b]?.run(c,$),b++}}var _S=["Size","Position","Opacity"],GS=[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",J],...a?[[" · ",J],...Ji(`${a.site} ${a.id}`,J,a.page||void 0,Bi(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[f,d]of _S.entries()){let h=t+GS[f],g=o.field===f,b=g?Qe:J;if(g)e[h]?.put(n,"▶",s);e[h]?.put(n+2,d,b);let p;if(f===1){for(let m=1;m<=9;m++){let $=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,$?"■":"·",$?Qe+s:J)}p=kt[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)),p=$==="fill"?"fill":`${$}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),p=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),J]])}if(e[h]?.right(r-2,[[p,b]]),WS(i,f))e[h]?.put(r-1,"↺",g?Qe+s:J)}}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 xf(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function lo(e){return`${X[Math.floor(e/Vn)]?.name??"local"} ${e%Vn}`}function co(e,t,n){let r=X[Math.floor(t/Vn)],i=lo(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],...Ji(i,n,r.pageUrl(t%Vn),Bi(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function BS(e,t,n){let r=[{name:"all",moved:!1},...X].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?xf(n,a):[` ${a} `,J];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+_e(o),0)<=t;e.run(0,i?r:[xf(n)])}function JS(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,J);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":J]]),s=Pr.filter((u)=>!n.block.includes(u)),o=X.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,J),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,J]);e.right(t,u)}}function Kw(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,fo]];if(e.cut==="off")return[["Opaque · x cuts out",pn]];if(e.cut==="failed")return[["Opaque · no cut-out",pn]];return[e.clear>0?[`${e.clear}% transparent`,fo]:["Opaque",pn]]}function Fw(e){return e.site==="all"?"any site":e.site}function Af(e,t){if(e.installing!==void 0)return co(`${Ki(e)} Installing ${e.palette} ← ${lo(e.installing)}`,e.installing,pn);if(e.hint)return[[e.hint,fo]];if(e.error)return[[e.error,pn]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,pn]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return co(`${Ki(e)} Fetching ${lo(n)} · ${Ya(r,i)}`,n,pn)}if(e.cutting!==void 0)return co(`${Ki(e)} Cutting out ${lo(e.cutting)}`,e.cutting,pn);if(e.preparing!==void 0)return co(`${Ki(e)} Preparing ${lo(e.preparing)}`,e.preparing,pn);if(t)return[t];if(e.saved)return co(e.saved.text,e.saved.key,fo);if(e.note)return[[e.note,J]];return}function Bw(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 Jw(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=hu(r)%(Iw*2)/Iw,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),b=Array.from({length:n},(m,$)=>{let E=(c>=0?$<c:$>=d&&$<d+l)?h:g;return $===0||$===n-1?rt(E,s,0.55):E}),p=0;for(let m=1;m<=n;m++)if(m===n||b[m]!==b[p])e?.put(t+p," ".repeat(m-p),fu(b[p])),p=m}function zS(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(hu(i)-i.loaderFrom)/IS),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[Bw(i),Qe+ji(rt(s,o,a))],[Jw(i," "),ji(rt(s,rt(o,s,0.45),a))]]);let c=Math.min(SS,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?[[" · ",ji(rt(s,o,0.25*a))]]:[],[l,ji(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:J)}}function QS(e,t,n){if(t)return[`${Ki(e)} ${Bw(e)}${Jw(e," · ")}`,J];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Ki(e)} Loading thumbnails · ${i}/${r.length}`,J]:void 0}function VS(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=zr(n,r);JS(e[0],n,i,s),BS(e[1],n,i);let c=e.map((k,N)=>N>=2&&N<2+u?k:void 0),l=Math.floor(i.scroll/Je.height),f=Math.floor((i.scroll+u-1)/Je.height),d=[];for(let k=l;k<=f;k++){let N=2+k*Je.height-i.scroll;for(let O=0;O<o;O++){let T=k*o+O,x=O*Je.pitch,C=i.tiles[T];if(!C)continue;d.push(C);let W=T===i.focus;if(W)KS(c,N,x,Je.height,Je.pitch-1,s);let A=N+1,F=Math.max(A,2),q=Math.min(A+Je.rows,2+u);if(C.thumb&&q>F)t.push({id:C.key,path:C.thumb,row:F,col:x+1,cols:Je.cols,rows:q-F,...q-F<Je.rows?{crop:F-A}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",fo]]:[],...C.page||i.site!=="all"?Ji(String(C.id),W?Qe:"",C.page||void 0,Bi(C.siteAnsi)):[["● ",Bi(C.siteAnsi)],[String(C.id),W?Qe:""]],[" ",""],jw(C)],be=Je.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(x+1,Tf(Ee)>be?Ee.map(([Ae,he,ue])=>[Ae.replace(/^(\S) $/,"$1"),he,ue]):Ee),C.mates.length>0)c[N+10]?.put(x+Je.cols,"≈",s);c[N+11]?.put(x+1,C.artist?FS(C.artist).slice(0,Je.cols-8):"—",J);let Q=[];if(C.score>0)Q.push([`★${C.score}`,J]);if(C.variants>1)Q.push([` ×${C.variants}`,s]);if(Q.length>0)c[N+11]?.right(x+Je.cols+1,Q)}}let h=Math.ceil(i.tiles.length/o)*Je.height;YS(e,n,i,u,h,s);let g=Math.max(2,2+h-i.scroll),b=2+u-g,p=i.searching&&b>=2;if(p)zS(c,g,b,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[k,N]=Nw[Math.floor(hu(i)/NS)%Nw.length];e[r-2]?.run(0,[["Tip ",J],[k,Qe],[` ${N}`,J]])}let $=i.top*o,E=i.tiles.length-(i.top+a)*o,M=[...$>0?[`↑ ${$} above`]:[],...E>0?[`↓ ${E} more`]:[]];if(M.length>0)e[r-2]?.put(0,M.join(" "),J);if(!i.searching&&i.tiles.length===0&&!i.error&&i.tag)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${Fw(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${Fw(i)} — tab tries ${i.nextSite}`,J);let w=QS(i,p,d),S=Af(i,w);return ho(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"]}),p}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=[xf(i,o.site,o.siteAnsi),[" ",""],...Ji(String(o.id),Qe,o.page||void 0,Bi(o.siteAnsi)),[" ",""],jw(o)];if(o.score>0)u.push([` · ★${o.score}`,J]);if(a)u.push([` · ${za(a.bytes)}`,J]);if(a)u.push([" ",""],...Kw(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),J]]);if(LS(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 xS(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){ho(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);ho(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",`⇧←→ ${_t.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"]]},_f=6,eI=24;function go(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function tI(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function Hw(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>tI(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function qw(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 Jr(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 nI(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 rI(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":J}];let o=s?[]:e.value.split(" "),a=(s?e.choices:nI(e)).map((u,c)=>{let l=o.includes(u),f=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${f}7;${30+r}m`:"":f?`\x1B[4m${J}`:J}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function Tw(e){if(e.entry==="text")return[{text:" ".repeat(eI),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(_f)}█ `,sgr:""}]:t}function iI(e){return e.reduce((t,n)=>t+_e(n.text)+1,0)-1}function xw(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 Aw(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 Lw(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 sI(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 oI(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((A)=>_e(A.label))),c=Math.max(...r.settings.map((A)=>_e(Aw(A)))),l=u+Math.max(...r.settings.map((A)=>iI(Tw(A))))+c+5,f=Math.min(t-2,Math.max(48,l)),d=f-u-c-5,h=f-7,g=[!1,!0].map((A)=>({advanced:A,rows:go({settings:r.settings,advanced:A}).slice(0,-1)})),b=r.settings.map((A)=>xw(Tw(A),d).length),p=Math.max(...g.map((A)=>A.rows.reduce((F,q)=>F+b[q],0))),m=Math.max(...g.map((A)=>Jr(Hw({settings:r.settings,advanced:A.advanced}),h).length),...r.settings.map((A)=>Jr(A.about,h).length)),$=`${r.tag}: ${X.map((A)=>`${A.name} 0,000,000`).join(" · ")}`,E=r.tag?Math.max(Jr($,h).length,Jr(Lw(r),h).length):0,M=p+m+E+8,w=Math.floor((t-f)/2),S=Math.max(1,Math.floor((n-1-M)/2)),k=`\x1B[7;${30+r.siteAnsi}m`;e[S]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let A=S+1;A<S+M-1;A++)e[A]?.put(w,`│${" ".repeat(f-2)}│`);let N=S+2;for(let A of go(r).slice(0,-1)){let F=r.settings[A],q=A===s;if(q)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,F.label,q?Qe:""),F.value!==F.default)e[N]?.right(w+f-3,[[Aw(F),J]]);xw(rI(F,q,r.typing,r.siteAnsi),d).forEach((Ee,be)=>{let Q=w+u;for(let Ae of Ee)Q=e[N+be].put(Q,Ae.text,Ae.sgr)+1}),N+=b[A]}let O=g.find((A)=>A.advanced!==r.advanced)?.rows??[],T=e[S+3+p];if(s===o)T.put(w+2,"▶",i);let x=T.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?k:Qe);if(O.some((A)=>r.settings[A]?.value!==r.settings[A]?.default))T.put(x+1,"•",J);e[S+5+p]?.put(w+2,"─".repeat(f-4),J),Jr(r.settings[s]?.about??Hw(r),h).forEach((A,F)=>{e[S+6+p+F]?.put(w+4,A)}),Jr(Lw(r),h).forEach((A,F)=>{e[S+6+p+m+F]?.put(w+4,A,J)}),e[S+M-1]?.put(w,`╰${"─".repeat(f-2)}╯`);let{keys:C,right:W}=sI(r,r.settings[s]);ho(e[n-1],t,i,{keys:C,right:W})}function aI(e,t,n,r,i){let s=r.tuning?XS:DS[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,d])=>_e(d)+16))),a=s.map(([d,h])=>({label:d,parts:Jr(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)}╯`),ho(e[n-1],t,i,{badge:"HELP",right:["? esc","close"]})}function uI(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],J]])})}function Gf(e,t,n){let r=Array.from({length:n},()=>new lu(t)),i=[],s=ji(e.colors.cursor);if(Hf=!1,t<qr.cols||n<qr.rows)return r[0]?.put(0,"ttheme find",Qe+s),r[1]?.put(0,`Needs ${qr.cols}×${qr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",J),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")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 lu(t);return uI(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 lu(t);if(e.help)aI(r,t,n,e,s);else oI(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:Hf}}var Wf=5,cI=6,zw=0.05,lI=[1,2,3,4,5,6,9,10,11,12,13,14],Yw=(e,t)=>(t-e+360)%360<=180?1:-1;function mo(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 Gt(e,t,n){let r=0,i=t;if(mo(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(mo(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(mo(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function fI(e,t){let{l:n,c:r}=Be(e);return Gt(n,r,(t+360)%360)}function dI(e,t,n){let{l:r,c:i,h:s}=Be(e),o=Ye(t)<0.18,a=(l)=>Gt(o?r+(1-r)*l:r*(1-l),i,s);if(Ke(a(1),t)<n+zw)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+zw)c=f;else u=f}return a(c)}function hI(e,t){let{l:n,c:r,h:i}=Be(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(Ye(Gt(u,r,i))<=t-0.005)s=u;else o=u}return Gt(s,r,i)}function gI(e,t,n){let r=$n[t],[i,s]=[Be(e[t]),Be(e[t+8])],o=(l,f)=>n.has(l)?[f]:Array.from({length:2*r.width+1},(d,h)=>(r.center-r.width+h+360)%360),a=(l,f,d)=>Cn.every((h)=>{let g=(l>8?8:0)+h;if(g===l)return!0;let b=Be(e[g]);return b.c<as||Dt(b.h,f)>=ii+1||Math.abs(b.l-d)>=si}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let f of o(t+8,s.h)){if(Dt(l,f)>Ut-Wf||!n.has(t+8)&&!a(t+8,f,s.l))continue;let d=Dt(l,i.h)+Dt(f,s.h);if(d<c)c=d,u=[l,f]}}return u}class Qw{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,fI(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of ri(this.theme)){let i=$n[_n(n)];this.rehue(n,"ansi-role",i.center+Yw(i.center,r)*(i.width-Wf))}for(let{normal:n,gap:r}of Mr(this.theme)){if(r<=Ut)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Be(this.theme.ansi[i]).h,a=Be(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+Yw(o,a)*(Ut-Wf))}let t=oi(this.theme);for(let[n,r]of Sr(this.theme)){let i=_n(t.has(r)?n:r),s=gI(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,dI(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",lI.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",hI(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 gu(e){let t=new Qw(e);for(let n=0;n<cI;n++)if(t.readability(),t.roles(),Ir(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Ir(t.theme)}}var po=[{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}],mu={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},Vw=(e,t,n)=>Math.min(n,Math.max(t,e));function Zw(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:Vw(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function Yr(e){let t=(r,i,s)=>Gt(Vw(r,0,1),i,s),n=Array.from({length:16},()=>"#000000");n[0]=t(e.background+0.06,e.tint,e.hue),n[8]=t(e.background+0.25,e.tint,e.hue),n[7]=t(e.foreground-0.06,e.tint/2,e.hue),n[15]=t(e.foreground+0.06,e.tint/2,e.hue);for(let r of Cn){let i=$n[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 $o=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],Nt=["Background","Foreground","Cursor","Selection"],ku=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],bo=Nt.length+ku.length,Qr=[{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}],Xw=5;function mI(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Ui(t).length>0}function pu(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function Fn(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function bu(e){if(e<Nt.length)return{name:Nt[e],about:$o[e]};let t=e-Nt.length,n=ku[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var wu=(e,t,n)=>Math.min(n,Math.max(t,e));function pI(e){return wu(Math.round(e),0,255).toString(16).padStart(2,"0")}function Dw(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)=>pI(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 Gt(wu(s,0,1),Number(i[3]),Number(i[4])%360)}return}function $u(e){let t=bt.find((n)=>n.rule===e);return t?.min??t?.max??0}function wo(e,t,n){let r=Fn(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function bI(e,t,n){let r=wo(e,t,n),i=(f)=>!n.includes(f),{background:s,foreground:o,selection:a,ansi:u}=Fn(e),c=new Set,l=(f,d,h,g)=>{if(i(g)&&Ke(d,h)<$u(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])>$u("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:f}of ri(r))c.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of Mr(r))if(d>Ut)c.add(4+f+8)}if(i("distinct"))for(let[f,d]of Sr(r))c.add(4+f).add(4+d);return c}function Rn(e,t,n,r,i){let s=Ke(e,t),o=$u(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 e0(e,t,n,r){let i=Fn(e),s=wo(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce(($,E)=>Ke(i.ansi[$],i.background)<=Ke(i.ansi[E],i.background)?$:E);return[Rn(i.foreground,i.background,"foreground","Foreground on it",n),Rn(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),Rn(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[Rn(i.foreground,i.background,"foreground","On background",n),Rn(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[Rn(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-Nt.length,a=i.ansi[o];if(o===0){let p=Ye(a),m=$u("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${p.toFixed(3)} · waived`}:{ok:p<=m,text:`Luminance ${p.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[Rn(a,i.background,"light-ansi","On background",n)];if(o===8)return[Rn(a,i.background,"ansi8-visible","On background",n)];let u=[Rn(a,i.background,"accents","On background",n)],c=Be(a),l=_n(o),f=$n[l],d=`${f.name} ${f.center}±${f.width}°`;if(c.c<as)u.push({ok:void 0,text:"Too grey to have a hue"});else if(oi(s).has(o))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · a signature, free of ${d}`});else if(n.includes("ansi-role"))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · ${d} waived`});else{let p=Dt(c.h,f.center)-f.width;u.push(p>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${p.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${d}`})}let h=o<8?o+8:o-8,g=Mr(s).find((p)=>p.normal===l);if(g)u.push(n.includes("bright-follows")?{ok:void 0,text:`${g.gap.toFixed(0)}° from ANSI ${h} · waived`}:{ok:g.gap<=Ut,text:`${g.gap.toFixed(0)}° from ANSI ${h} · ≤ ${Ut}°`});let b=Sr(s).flatMap(([p,m])=>p===o?[m]:m===o?[p]:[]);if(b.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${b.join(", ")} · within ${ii}° and ${si} lightness`});return u}function t0(e,t,n){let r=Gn(wo(e,t,n));return bt.map((i,s)=>{let o=r[s],a=n.includes(i.rule);return{ok:a||Number.isNaN(o)?void 0:(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),label:i.label,value:Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2),bound:a?"waived":i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:""}})}var wI=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class Uf{mode;seeds=mu;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=pu(e.colors??Yr(this.seeds)),this.lch=this.list.map(Be),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 Fn(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<Nt.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 bI(this.list,this.signature,this.waive)}failing(){return Ir(wo(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(mI(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=Dw(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()]=Be(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=po.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=po[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:Xw:1);this.seeds=Zw(this.seeds,n,r),this.list=pu(Yr(this.seeds)),this.lch=this.list.map(Be)}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"?bo-1:1))%bo,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:bo-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:Nt.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=Qr.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=Qr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:Xw:1))}else if(/^[0-9]$/.test(e)){let n=Qr[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=Qr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=Qr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:wu(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=Gt(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=Dw(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()]=Be(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=pu(n.colors),this.lch=this.list.map(Be),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||wI.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Ht(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Be(t)}follow(){if(this.row<Nt.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:wu(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=Gt(r.l,r.c,r.h),this.col=1,this.notice=`${bu(t).name} follows ${bu(e).name.toLowerCase()}`}mark(){let e=$o[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=wo(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=gu({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=Ir(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=pu({...this.colors(),foreground:t.foreground,selection:t.selectionBackground,ansi:t.ansi});this.lch=i.map((s,o)=>s===this.list[o]?this.lch[o]:Be(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 Kf=80,Bf=24,yu=48,jf=11;function $I(e){return{color:e,dim:(t)=>e?`\x1B[2m${t}\x1B[22m`:t,bold:(t)=>e?`\x1B[1m${t}\x1B[22m`:t,fg:(t)=>e?Xt(t):"",bg:(t)=>e?`\x1B[48;2;${ve(t).join(";")}m`:""}}function kI(e){return Ye(e)>0.35?"#000000":"#ffffff"}function r0(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(kI(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function yI(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 mo(o.l,o.c,o.h)?Gt(o.l,o.c,o.h):void 0})}function i0(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var n0={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 s0(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function o0(e,t,n){let r=t0(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=yu-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${s0(e,a.ok)} ${bn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function EI(e,t,n){let r=t.misses(),i=Fn(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($o[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Ke(i.foreground,i.selection):Ke(f,i.background),b=g===void 0?"":g.toFixed(1),p=r.has(l)?"✗":" ",$=`${e.color?`${e.fg(f)}${h}${d?e.fg(i.foreground):"\x1B[39m"} `:`${h} `}${f} ${b.padStart(4)}${p}`;return d?o(` ${$} `):` ${$} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<Nt.length;l++){let f=l===t.row,d=Nt[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=Nt.length;l<bo;l++){let f=l===t.row,d=ku[l-Nt.length].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...o0(e,t,n-c.length)]}function vI(e,t,n){let r=Fn(t.list),i=[` ${e.dim("Seeds")}`];po.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:jf},(b,p)=>{let m=s.min+(s.max-s.min)*p/(jf-1);return n0[s.key](Yr({...t.seeds,[s.key]:m}))}),l=r0(e,c,i0(u,s.min,s.max,jf),a),f=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),d=n0[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.",yu-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...o0(e,t,n-i.length)]}function a0(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 MI(e,t,n,r){let i=t.slot(),s=t.list[i],o=t.lch[i],a=Be(s),u=t.start[i],{name:c,about:l}=bu(i),f=t.signature.includes($o[i]),d=[bn(`${e.bold(c)} ${e.dim(l)}`,f?e.dim("◆ signature"):"",n),""],h=e.color?`${e.fg(s)}${"█".repeat(8)}\x1B[39m `:"",g=t.typing!==void 0?`${e.bold(`${t.typing}▏`)}`:void 0,[b,p,m]=ve(s),$=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 ${b} ${p} ${m}`)}`),d.push(`${h}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let E=Math.max(8,Math.min(64,n-12));Qr.forEach((S,k)=>{let N=t.mode==="tune"&&k===t.channel,O=o[S.key],T=`${O.toFixed(S.digits)}${S.wraps?"°":""}`.padStart(6),x=r0(e,yI(o,S,E),i0(O,S.min,S.max,E),N),C=S.key.toUpperCase();d.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${x} ${N?e.bold(T):e.dim(T)}`)}),d.push("");let M=e0(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((k,N)=>{d.push(`${N===0?s0(e,S.ok):" "} ${S.ok===!1?k:e.dim(k)}`)});let w=r-d.length-1;if(w>=3)d.push("",...a0(e,Fn(t.shown()),n).slice(0,w));return d}function SI(e,t,n,r){return[bn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...a0(e,Fn(t.list),n).slice(0,r-2)]}var II=[["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 NI(e,t,n){let r=[` ${e.bold("Help")}`,""];for(let[i,s]of II.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 PI(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=[bn(` ${e.bold("Take colors from")} ${o}`,e.dim(`${i.length}/${s}`),n),""],u=r-2,c=Math.max(0,Math.min(t.pick-Math.floor(u/2),i.length-u)),l=Math.min(40,Math.max(12,...i.map((f)=>$e(f.name))));if(i.slice(c,c+u).forEach((f,d)=>{let h=c+d===t.pick,g=f.colors,b=e.color?`${e.bg(g.background)} ${[...g.ansi].map(($)=>`${e.fg($)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",p=h?"▌ ":" ",m=f.name.padEnd(l);a.push(`${p}${h?e.bold(m):m} ${b}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function OI(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?bn(f,c,n):nt(f,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function RI(e,t,n,r){let i=$I(r);if(t<Kf||n<Bf){let g=[i.bold("ttheme palette editor"),`Needs ${Kf}×${Bf} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(b,p)=>nt(g[p]??"",t))}let s=e.failing().length,o=s===0?"✓ Passes the gate":`✗ ${s} ${s===1?"miss":"misses"} in the gate`,a=e.pictures>0?i.dim(`▣ ${e.pictures} ${e.pictures===1?"picture":"pictures"} `):"",u=`${e.dirty()?`${i.color?"\x1B[33m●\x1B[39m":"●"} unsaved `:""}${a}${i.dim(o)}`,l=`${i.fg(e.list[2])}◆${i.color?"\x1B[39m":""} ${i.bold(e.options.title)} ${i.dim(`· ${e.options.name}`)}`,f=n-4,d;if(e.overlay==="keys")d=NI(i,e,t);else if(e.overlay==="open")d=PI(i,e,t,f);else{let g=t-yu-2,b=e.mode==="seeds"?vI(i,e,f):EI(i,e,f),p=e.mode==="seeds"?SI(i,e,g,f):MI(i,e,g,f);d=Array.from({length:f},(m,$)=>`${nt(b[$]??"",yu)}${i.dim("│")} ${nt(p[$]??"",g)}`)}let h=[bn(l,u,t),""];for(let g=0;g<f;g++)h.push(nt(d[g]??"",t));return h.push("",OI(i,e,t)),h}async function u0(e,t){let n=new Uf(e),{stdin:r,stdout:i}=process,s=i.columns||Kf,o=i.rows||Bf,a=[],u=[],c="",l="",f,d=(M)=>i.write(M),h=()=>{if(f=void 0,t.look){let w=n.shown();if(w.join(" ")!==c)c=w.join(" "),t.look(w);return}let M="";if(n.shown().forEach((w,S)=>{if(u[S]!==w&&t.only?.includes(S))M+=wl(S,w),u[S]=w}),M)d(M)},g=()=>{let M=RI(n,s,o,t.color),w="";if(M.forEach((S,k)=>{if(a[k]!==S)w+=`\x1B[${k+1};1H\x1B[0m\x1B[2K${S}`}),a=M,w)d(`\x1B[?2026h${w}\x1B[0m\x1B[?2026l`);if(t.only||t.look)f??=setTimeout(h,33)},b,p,m=!1,$=()=>{d(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${Oi}`),r.setRawMode(!0),r.resume()},E=(M)=>{if(b&&p)r[M?"on":"off"]("data",b),i[M?"on":"off"]("resize",p)};$();try{return await new Promise((M)=>{let w=async(S)=>{let k=e.find;if(!k)return;m=!0,E(!1),clearTimeout(f),f=void 0;try{n.found(await k(n.edited(),S))}catch(N){n.notice=N instanceof Error?N.message:String(N)}m=!1,$(),E(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,c="",g()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],d(Oi),g()},b=(S)=>{l+=S.toString("utf8");let k=cu(l);l=k.pending;for(let O of k.events)if(O.kind==="paste")n.paste(O.text);if(k.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(k.keys)&&n.typing===void 0)n.paste(k.keys);else for(let O of du(k.keys))if(n.press(O),n.result||n.wants)break;if(n.result){M(n.result==="saved"?n.edited():void 0);return}let N=n.wants;if(N&&!m){n.wants=void 0,w(N.start);return}g()},E(!0),g()})}finally{clearTimeout(f),E(!1),r.setRawMode(!1),r.pause(),d("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as QI}from"node:child_process";import{createHash as O0}from"node:crypto";import{existsSync as qi,mkdirSync as VI,mkdtempSync as ZI,readFileSync as R0,rmSync as ko,statSync as XI}from"node:fs";import{homedir as DI,tmpdir as eN}from"node:os";import{dirname as tN,join as Vt}from"node:path";import{pathToFileURL as w0}from"node:url";var FI=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),HI=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),TI=0.04,xI=0.1,AI=0.05,LI=4096;function CI(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function _I(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...CI(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)+([...FI].some((l)=>o.has(l))?-3:0)+([...HI].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 Eu(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:_I(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 l0(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 Jf(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function c0(e,t,n){let[r,i,s]=[Jf(e),Jf(t),Jf(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 f0(e,t){let n=t.map((o)=>c0(...ve(o))).filter(([,o,a])=>Math.hypot(o,a)>=TI);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/LI))),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]=c0(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([d,h,g],b)=>{if(Math.hypot(c-d,l-h,f-g)<xI)i[b]=i[b]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/AI),0)/n.length}import{mkdirSync as jI,readFileSync as zf,writeFileSync as p0}from"node:fs";import{dirname as KI}from"node:path";import{isMainThread as BI,parentPort as b0,Worker as JI}from"node:worker_threads";var GI=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,WI=[[/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 qf(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 d0(e,t){let n=GI.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...WI.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function h0(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 g0(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),f=0;for(let d=o;d<a;d++)for(let h=c;h<l;h++){let g=(d*e.width+h)*4,b=e.data[g+3]/255,p=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=p*b+255*(1-b)}r.push(f/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function UI(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function m0(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&&UI(e.hash,t.hash)<=2}var qI={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},vu;async function zI(e){if(e.job==="redraw")return Za(e.home,e.name,e.key,e.paint,e.blur,e.aligns,e.user);if(e.job==="show"){if(vu?.from!==e.from){let o=Kn(new Uint8Array(zf(e.from)),$t);vu={from:e.from,clear:kn(o),inked:Yc(o)}}let{image:r,fill:i,opacity:s}=xm(vu.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune,e.coloring);return jI(KI(e.to),{recursive:!0}),p0(e.to,Bn(r)),{clear:vu.clear,fill:i,opacity:s}}let t=Kn(new Uint8Array(zf(e.from)),$t);if(e.job==="backdrop"){ma(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(zf(e.source)),cut:e.from!==e.source},e,e.blur,e.coloring);let r=e.tune&&Ct(e.home,e.colors.name).find((i)=>i.key===ft(e.origin));if(e.tune&&r)Fs(Se(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:f0(t,e.colors),hash:g0(t)};if(e.job==="thumb")return K(e.to,Bn(Mg(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return p0(e.to,Bn({width:t.width,height:e.height,data:n})),0}function YI(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await zI(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Yf{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 JI(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 Qf{lines=new Map;run(e){let t=qI[e.job],n=this.lines.get(t);if(!n)n=new Yf,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Vf{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Yf)}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(!BI&&b0)YI(b0);var Vr=[{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:hi,multi:{read:Rr}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Pr,multi:{read:mi,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...xi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Jg,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:qg,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:X.map((e)=>e.name),multi:{read:$s},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:Rc,multi:{read:Zo,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 $0(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return ks(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var nN=["fit","newest","score"];function Zf(e){return nN.find((t)=>t===e)??"fit"}var rN={left:-1,right:1,"shift-left":-10,"shift-right":10};function iN(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=iN(process.env.TTHEME_BG_MARGIN);function sN(e,t,n){if(t<0){if(e!=="fill")return Math.max(M0,e+t);if(!n)return e;return Math.max(M0,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function F0(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function oN(e,t){if(F0(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:kt[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function aN(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var k0=12,uN=4,cN=150,lN=300,y0=12,fN=2,dN=150,hN=30,gN=4000,mN=8000,E0=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,pN=process.platform==="win32"?"alt+v":"ctrl+v",v0=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",bN=1280,wN=16,$N=kt.indexOf("top-right")+1,M0=20,zi=2147483645,yo=2147483646,S0=-1073741827,kN=-1073741828,I0=2,yN=80,EN=16,vN=0.4,MN=3221225472,SN=256,IN=3,NN=8;function Mu(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 Eo(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return Eo(e.errors[0]);if(e.cause)return Eo(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 Df(e,t){return`${e}: ${Eo(t)}`}function N0(e){return e.width*e.height}function P0(e,t){return`${e}-${O0("sha1").update(t).digest("hex").slice(0,8)}`}function PN(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function ON(e,t){try{return JSON.parse(R0(Vt(rn(e),t),"utf8"))}catch{return{}}}function RN(e,t,n){K(Vt(rn(e),t),`${JSON.stringify(n)}
507
- `)}class ed{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(Vr.map((e)=>[e.name,$0(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 Qf;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=Np(process.env);files=Pp(process.env);moves=Rp(process.env);layers=Op(process.env);bandFiles=new Map;nextBand=MN;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Ff((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=ZI(Vt(eN(),"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=yi(n,n.signatureSlots),this.blurring=Cr(e),this.coloring=Na(e);let s={size:"fill",at:$N,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:Zf(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Rr(this.setting("TTHEME_FIND_RATING")),block:mi(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:$s(this.setting("TTHEME_FIND_SITES")),hide:Zo(this.setting("TTHEME_FIND_HIDE")),hideTags:ks(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Vr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:$0(o,vl(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,_t.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=Mu(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??uN}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 Hc(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return Vt(rn(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=Do(e.site,e.post);return Vt(rn(e.site),"thumb",`${P0(e.post.id,t)}.${Qn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Lt(n,r.id),s=nn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,page:n===Br?"":n.pageUrl(r.id),artist:n===Br?$w(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${Oi}`);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\\${Oi}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),ko(this.scratch,{recursive:!0,force:!0}),sm(),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(Cw)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=Lf(this.input);n;n=Lf(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=cu(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),PN(this.typed)){this.partial=setTimeout(this.flushKeys,hN);return}this.flushKeys()};flushKeys=()=>{let e=du(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!Xo(t,this.site??X[0]);return Ui(t).length>0}async got(e){if(e.kind==="error"){this.notice(e.message);return}if(e.kind==="text"){if(e.text.trim()===""){this.notice(`No picture on the clipboard — ${v0}`);return}this.pasted(e.text);return}await this.bring(()=>au(e.bytes,e.source))}notice(e,t=gN){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 Mw()}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 · ${pN} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},mN),this.draw()}async fromClipboard(){let e=this.view;if(Rf()){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 vw(Vt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${Eo(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await Of(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${v0}`);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=Xo(t,this.site??X[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ui(t).sort((i,s)=>Number(!E0.test(i))-Number(!E0.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)=>Of(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(Eo(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=yw(i.bytes);kw(s,i.source);let o=this.origPath(Br,s,i.ext);K(o,i.bytes);let a=w0(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:O0("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Br,post:u},l=this.previewPath(c);K(l,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=Mu(`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(Lt(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)=>Yn(i)>Yn(r)?i:r),t=Math.ceil((Yn(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<qr.cols||this.rows<qr.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}=zr(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=go(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=go(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=qw(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(Vr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":ks(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<_f:/^[\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),lN)}pending(){let e=(t)=>this.view.settings[Vr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Zf(e("TTHEME_FIND_ORDER")),rating:Rr(e("TTHEME_FIND_RATING")),narrow:Hc(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:$s(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:X.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await Lc(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=Vr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Vr[i];if(s)this.values.set(s.name,r.value)});let n=Vr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=Rr(this.setting("TTHEME_FIND_RATING")),e.block=mi(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=Zf(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=$s(this.setting("TTHEME_FIND_SITES")),e.hide=Zo(this.setting("TTHEME_FIND_HIDE")),e.hideTags=ks(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=Vt(this.home,"ttheme","config.zsh");try{let n=qi(t)?R0(t,"utf8"):"";return K(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(!aN(t)){e.suggest=void 0;return}let n=[...new Map(hp(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,IN);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await am(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,NN),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},cN)}async commit(e){let t=Xo(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=Mu(`${e.key}|post:${t}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await ys(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,i,e)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let e=this.boards.get(this.boardKey);if(!e){await this.search();return}this.gen++,this.board=e,this.view.error=e.error,this.show(),this.draw(),await this.pump()}unfold(){let e=this.view,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(Lt(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{QI(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=rN[e];if(i!==void 0){if(n.field===0)r.size=sN(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=rm(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=Es(n.source),a=/^https?:\/\//i.test(o)?o:t===Br&&o.startsWith("/")?w0(o).href:void 0;return{page:t===Br?"":t.pageUrl(n.id),source:o,...a?{link:a}:{},artists:r.artist,characters:r.character,series:r.copyright,tags:n.tags.filter((u)=>!s.has(u)),...i?{rating:i}:{},...n.posted?{posted:n.posted}:{},ext:(nn(n)??n).ext,uploader:n.owner}}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.glide(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=zr(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=zr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Je.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)*vN)),this.draw(),this.gliding=setTimeout(t,EN)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Je.height}prebake(){let e=this.view;for(let t of Gf({...e,scroll:e.top*Je.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?gp(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(Ac([...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=Mu(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=Ac(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})=>Lc(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=Df(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,Df(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=zr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+I0)*e}need(){let{perRow:e,rowsVis:t}=zr(this.cols,this.rows);return(t+I0)*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=om(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===At?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{sa(n,await oa(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<zn;let c=e.last.get(a);for(let l of u){let f=c&&h0(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:f};let d=Lt(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,...d0(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?l0(i):i;else{let a=Eu(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=[...Eu(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(Lt(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=Eu(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=qf(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++,N0(r.post)<=N0(s.post))continue;for(let a of[...i,...qf(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(Lt(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:y0},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Lt(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=Do(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<k0&&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<k0&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.searching=!1,this.show(),this.draw()}catch(i){this.fail(e,i)}finally{if(this.saveKept(),this.pumping===e)this.pumping=0}}eligible({site:e,post:t}){let n=nn(t);if(!ta(e,t,this.view.rating)||ea(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"||nm(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=ON(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 aa(e,t,this.signal),s=pi(e,t),o=(i===void 0?await um(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)RN(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Lt(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)=>m0(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(!ia(n,r))return Promise.resolve();let i=Lt(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 ra(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}vs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=jm(this.home),r=this.keep(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await ys(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);this.unsaved.add(`${e.key}/owners.json`);let a=im(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(qi(t))return XI(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await ua(e,n,this.signal,r);return K(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(!this.signal.aborted&&this.thumbing<y0&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Lt(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Je.cols*this.cell.w,i=Je.rows*this.cell.h,s=Do(t,n),o=Vt(rn(t),"tile",`${P0(n.id,s.url)}-${r}x${i}.png`);if(!qi(o)){let a=this.previewPath(e);if(await this.cached(s.site,a,s.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(Lt(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),dN),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n)return;let r=new AbortController;if(this.fetch=r,this.credit(n,r.signal),!nn(n.post))return;let{site:i}=n,s=this.board;try{await aa(i,n.post,r.signal);let o=nn(n.post),a=this.origPath(i,e.id,o.ext);if(!qi(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=pi(i,n.post,o),c=await this.cached(u.site,a,u.url,(d,h)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:d,size:h},this.draw()});if(r.signal.aborted)return;if(t.fetching=void 0,s!==this.board)return;let l={site:i,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let f=await this.render(l,"plain");if(r.signal.aborted||s!==this.board)return;if(f.clear===0&&xi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(i,e.id,a,r.signal),r.signal.aborted||s!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let d=await this.render(l,"cut").catch(()=>{return});if(r.signal.aborted||s!==this.board)return;if(d&&Qa(d.clear))l.using="cut";else ko(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=Df(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=Vt(rn(e),"cut",`${t}.png`);if(qi(i))return i;try{return VI(tN(i),{recursive:!0}),await Vs(n,i,r),i}catch{ko(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>=fN||!r||!nn(r.post))continue;let{site:i,post:s}=r;this.prefetching++,aa(i,s,this.signal).then(async()=>{let o=nn(s),a=this.origPath(i,s.id,o.ext),u=pi(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,bN),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!F0(o,this.view.untuned),u=o.opacity!==this.view.untuned.opacity,c=a?`-${o.size}-${o.at}${u?`-${Math.round(o.opacity*100)}`:""}`:"",l=Vt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}${c}.png`),f=`${e.site.key}:${e.id}:${t}:${i}x${s}`,d=this.clarity.get(f);if(d&&qi(l))return e.fill=d.fill,{clear:d.clear,path:l,opacity:d.opacity,touched:u};let h=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:l,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/qc(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>wN){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;ko(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=oN(e.tune,e.untuned),i=this.posts.get(n.key)?.post;try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`,artist:i?.named.artist??[],source:Es(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,coloring:this.coloring,...r?{tune:r,aligns:Ur(se(this.home).terminals),user:DI()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),It(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${kt[o-1]} · ${a.toFixed(2)}`:"",c=i?.named.artist.length?`${i.named.artist.join(", ")} · `:"";e.saved={text:`Background · ${this.entry.name} ← ${c}${n.site.name} ${n.id}${u}`,key:t.key},e.installed.push(t.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(s){e.error=s instanceof Error?s.message:String(s)}e.installing=void 0,this.draw()}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let e=Gf(this.view,this.cols,this.rows);this.view.loaderFrom=e.loader?this.view.loaderFrom??this.view.beat:void 0;let t="";e.lines.forEach((i,s)=>{if(this.screen[s]!==i)t+=`\x1B[${s+1};1H\x1B[K${i}`,this.screen[s]=i});let n=new Set;for(let i of e.images){let s=this.bands?this.banded(i):i;if(!s)continue;if(n.add(s.id),this.sent.get(s.id)!==s.path){let a=_w(s,this.files);if(a===void 0)continue;t+=a,this.sent.set(s.id,s.path),this.placed.delete(s.id)}let o=`${s.row};${s.col};${s.cols};${s.rows};${s.crop};${s.z}`;if(this.placed.get(s.id)!==o){if(!this.moves&&this.placed.has(s.id))t+=Cf(s.id);t+=Gw(s,this.cell),this.placed.set(s.id,o)}}for(let i of this.sent.keys())if(!n.has(i))t+=Ww(i),this.sent.delete(i),this.placed.delete(i);t+=this.cover();let r=this.view.mode==="grid"&&this.view.editing!==void 0?this.caret():"";if(t||r)this.write(`\x1B[?2026h${t}${r}\x1B[?2026l`);this.pace(e.tick)}cover(){let e=`${this.cols};${this.rows}`;if(!this.layers||this.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(ve(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${zi},q=2;${n}\x1B\\`,Xf)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${yo},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${yo},p=${yo},c=1,r=1,C=1,z=${kN},q=2\x1B\\`}else if(!this.moves)t+=Cf(zi);if(this.covered=e,Xf){let{x:n,y:r}=Xf;return`${t}\x1B_Ga=p,i=${zi},p=${zi},P=${yo},Q=${yo},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${S0},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${zi},p=${zi},c=${this.cols},r=${this.rows},C=1,z=${S0},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()},yN);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:Vt(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<=SN)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),ko(t.path,{force:!0})}}}async function H0(e,t,n){let r=new ed(e,ln(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function T0(e){let t=le(),n=ln(t),r=Ar(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new ed(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
508
- `),0;return s}import{existsSync as Iu,readdirSync as FN,readFileSync as td,rmSync as x0,statSync as A0}from"node:fs";import{homedir as HN}from"node:os";import{join as vo}from"node:path";var TN=150,xN=260;function Su(e){return e?.includes(`path = "${_("")}`)===!0}function AN(e){try{return se(e).terminals.includes("warp")}catch{return!1}}function LN(e,t){let n=_(t);if(!Iu(e))return;return FN(e).filter((i)=>i.startsWith(`${n}.`)&&/^[0-9a-f]{8}\.yaml$/.test(i.slice(n.length+1))).map((i)=>({file:i,at:A0(vo(e,i)).mtimeMs})).sort((i,s)=>s.at-i.at)[0]?.file??(Iu(vo(e,`${n}.yaml`))?`${n}.yaml`:void 0)}function kr(e,t,n,r=HN()){if(!t||gt(e)||e.TMUX||zt(e)!=="warp")return;let i=mr(r,n);if(!Iu(i)||!AN(n))return;let s=Gr(r),o=Ga(n),a=[],u,c,l=(g)=>{let b=td(i,"utf8"),p=pr(b);if(p===g)return;if(Su(g)&&!Su(p)&&!Iu(o))K(o,p??"");if(en(i,Wa(b,g)),!Su(g))x0(o,{force:!0})},f=(g)=>{for(let b of a.splice(0))if(b===g)a.push(b);else x0(vo(s,b),{force:!0})},d=()=>{clearTimeout(u),clearTimeout(c)},h=(g,b)=>{d(),u=setTimeout(()=>{let p=b;if(!p)p=`${_(g.name)}.view-${process.pid}-${a.length+1}.yaml`,K(vo(s,p),js(g)),a.push(p);let m=p,$=Date.now()-A0(vo(s,m)).mtimeMs;c=setTimeout(()=>{l(Jl(g.name,m)),f(m)},Math.max(0,xN-$))},TN)};return{slots:[],paint:(g)=>{return h(g,LN(s,g.name)),""},look:(g,b)=>{let[p="",m="",$="",,...E]=b;h({name:g,background:p,foreground:m,cursor:$,ansi:E})},wear:(g,b)=>b.includes("warp")?"":void 0,saved:async()=>new Map([["theme",pr(td(i,"utf8"))??""]]),restore:(g)=>{d();let b=g.get("theme");if(b)l(b);else if(Su(pr(td(i,"utf8"))))l(_a);return f(),""}}}function L0(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function C0(e,t){if(e.includes("/"))return e;let n=xr(t,!1),r=n.filter((s)=>ir(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function GN(e,t,n){let r=se(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)gn(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))mt(e,t,r);return{state:r,fresh:i}}function WN(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 _0(e,t,n){let r=sp(t),i=Bt(vt(r.name,al(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 ${Me(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)va(e,[...In(e),i]);return i.name}var UN=["background","foreground","cursor"];function G0(e){try{e();return}catch(t){return t.message}}function W0(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 U0(e,t){let n=new Set(Ct(e,t).map((r)=>r.key));return{count:()=>Ct(e,t).length,added:()=>Ct(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(Va(e,t)??[]).filter((r)=>!n.has(ft(r))),discard:()=>{let r=Ct(e,t).filter((i)=>!n.has(i.key));for(let i of r)vi(e,t,i.key),ga(e,t);if(r.length>0)It(e)}}}function jN(...e){let t=new Map;for(let n of e.flatMap((r)=>r??[]))t.set(ft(n),n);return t.size>0?[...t.values()]:void 0}function j0(e,t,n,r){if(!Ip(process.env))return;return async(i,s)=>{let o=Bt(vt(t,r(i),n.palettes)),{saved:a}=await H0(e,o,s);return{...a?{note:a}:{},count:Ct(e,t).length}}}async function K0(e){let t=process.stdout.isTTY===!0,n=cr(process.env,t)??kr(process.env,t,le()),r=n?await n.saved():new Map,i=n?.look?{look:(s)=>n.look?.(e.name,s)}:n?{only:n.slots}:{};try{return await u0(e,{color:!gt(),...i})}finally{if(n)process.stdout.write(n.restore(r))}}async function B0(e,t,n){let r=le(),i=We(r),s=await sw(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=on(o);if(a)throw Error(`${o} ${a}`);if(Me(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=sl(r,o);if(Mo(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?Ar(je(r,i).palettes,t):void 0;if(!L0())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(Me(c.name)?c.base:c.default?void 0:c.name),f=c?ol(c,o,`kept from ${c.name}`):void 0,d=c?Va(r,c.name)??c.pictures:void 0,{base:h,ansiSource:g,group:b,...p}=f??{name:o,signature:UN,...Yr(mu)},m=U0(r,o),$=({colors:w,signature:S})=>{let k=jN(d,m.fresh());return al({...p,...w,signature:S,...l?{base:l}:{},...k?{pictures:k}:{}})},E=await K0({title:"New palette",name:o,...f?{colors:f}:{},signature:p.signature,...p.waive?{waive:p.waive}:{},palettes:W0(r,i,o),pictures:m.count(),find:j0(r,o,i,$),check:(w)=>G0(()=>vt(o,$(w),i.palettes))});if(!E){m.discard(),console.log("Nothing made");return}CN(_N(u),{recursive:!0}),K(u,$(E));let{state:M}=GN(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
505
+ }`;async function Iw(){if(Tf())return;if(process.platform==="darwin"){let[e="",t=""]=(await mn("osascript",["-l","JavaScript","-e",vS])).stdout.trim().split("\t");return{stamp:e,picture:t==="picture"}}if(process.platform==="linux"&&!Mw()){let t=Boolean(process.env.WAYLAND_DISPLAY)?(await mn("wl-paste",["--list-types"])).stdout:(await mn("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:t,picture:/^image\//m.test(t)}}return}function fu(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:MS(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 MS(e){let t={};for(let n of e.split(":")){let r=n.indexOf("=");if(r>0)t[n.slice(0,r)]=n.slice(r+1)}return t}var co=(e)=>Buffer.from(e).toString("base64"),Rf=(e)=>Buffer.from(e,"base64");function pw(e,t){return t.find((n)=>e.includes(n))}class Hf{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=co(bw("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;${Pf.join(" ")}\x1B\\`;this.send(e)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${co("ttheme")}:pw=${this.pw};${co(".")}\x1B\\`)}take(e){if(e.code==="5522")this.clip(e.meta,e.payload);else if(e.code==="72")this.drop(e.meta,e.payload)}clip(e,t){if(e.type!=="read")return;let n=e.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:e.pw??"",listing:!0},e.pw)this.reading.pw=e.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=e.mime?Rf(e.mime).toString("utf8"):r.mime,t)r.chunks.push(Rf(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=pw(s,[...Of,...pS]);if(!o){this.deliver({kind:"text",text:""});return}let a=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:o,chunks:[],pw:a,listing:!1},this.send(`\x1B]5522;type=read:name=${co(u)}:pw=${a};${co(o)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(e,t){let n=e.t??"";if(n==="m"){if(e.x==="-1"){this.offered=[];return}if(t){this.offered=t.split(" ").filter(Boolean);let a=Pf.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=pw(a,Pf);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(Rf(t));if(e.m==="1"||t)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),s=r.mimes[r.index-1]??"",o;if(s.startsWith("image/"))o={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let a=i.toString("utf8"),u=s==="text/uri-list"?Ui(a).find((c)=>uS(c)):void 0;o=u?{kind:"bytes",bytes:new Uint8Array(lu(u)),source:u}:{kind:"text",text:a}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(o)}}import{readFileSync as SS}from"node:fs";var Je={pitch:25,cols:22,rows:9,height:13},qr={cols:25,rows:16},IS=2147483648,NS=-1073741826,PS=1600,Nw=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],RS=56,OS=4,Pw=20,FS=50,Rw=[["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"]],TS="\x1B[0m",Ye="\x1B[1m",J="\x1B[2m",ho="\x1B[32m",pn="\x1B[33m",HS={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 gu(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(HS[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let s=e[n+1]??"";if(/^[a-z]$/.test(s)){t.push(`alt-${s}`),n+=2;continue}t.push("esc"),n++;continue}t.push(r==="\r"||r===`
506
+ `?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return t}var Gw="\x1B]1337;ReportCellSize\x07\x1B[16t\x1B[14t\x1B[18t",Ow="\x1B]1337;ReportCellSize=";function _f(e){let t=e.indexOf(Ow);if(t!==-1){let o=e.slice(t+Ow.length),a=[o.indexOf("\x07"),o.indexOf("\x1B\\")].filter((l)=>l!==-1),u=a.length>0?Math.min(...a):-1,c=u===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(o.slice(0,u));if(c){let l=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*l),w:Math.round(Number(c[2])*l)},rest:e.slice(0,t)+o.slice(u+(o[u]==="\x07"?1:2))}}}let n=e.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(e.slice(n+1));if(r)return{cell:{h:Number(r[1]),w:Number(r[2])},rest:e.slice(0,n)+e.slice(n+1+r[0].length)};let i=Fw(e,4),s=Fw(e,8);if(!i||!s||s.a===0||s.b===0)return null;return{cell:{h:Math.floor(i.a/s.a),w:Math.floor(i.b/s.b)},rest:e.replace(i.text,"").replace(s.text,"")}}function Fw(e,t){let n=e.indexOf(`\x1B[${t};`),r=n===-1?null:new RegExp(`^\\[${t};(\\d+);(\\d+)t`).exec(e.slice(n+1));return r?{a:Number(r[1]),b:Number(r[2]),text:`\x1B${r[0]}`}:null}function zr(e,t){let n=t-4;return{perRow:Math.max(1,Math.floor((e-1)/Je.pitch)),rowsVis:Math.max(1,Math.floor(n/Je.height)),height:n}}function Ww(e,t=!0){if(t)return`\x1B_Ga=t,t=f,f=100,i=${e.id},q=2;${Buffer.from(e.path).toString("base64")}\x1B\\`;let n;try{n=SS(e.path).toString("base64")}catch{return}let r=n.match(/.{1,4096}/g)??[""];return r.map((i,s)=>{let o=s<r.length-1?1:0;return s===0?`\x1B_Ga=t,f=100,i=${e.id},m=${o},q=2;${i}\x1B\\`:`\x1B_Gm=${o},q=2;${i}\x1B\\`}).join("")}function Uw(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 Gf(e){return`\x1B_Ga=d,d=i,i=${e},p=${e},q=2\x1B\\`}function jw(e){return`\x1B_Ga=d,d=I,i=${e},q=2\x1B\\`}function ji(e){return`\x1B[38;2;${ve(e).join(";")}m`}function hu(e){return`\x1B[48;2;${ve(e).join(";")}m`}var xf=!1;function mu(e){return xf=!0,e.beat}function Ki(e){return Nw[mu(e)%Nw.length]}function _e(e){return $e(e)}function Kw(e,t){if($e(e)<=t)return e;let n="";for(let r of e){if($e(n+r)>t)break;n+=r}return n}function Bi(e){return`\x1B[${30+e}m`}function Ji(e,t,n,r){return n?[[`${ss} `,r],[e,t,n]]:[[e,t]]}function Af(e){return e.reduce((t,[n])=>t+_e(n),0)}function xS(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([`${Kw(i,r)}…`,s,o]);break}return n}class du{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=Kw(n,this.cols-t);e+=`\x1B[${t+1}G${r}${Uo(s,i)}${r?TS:""}`}return e}}function AS(e){return e.replace(/_\([^)]*\)?$/,"")}function Bw(e){return[`${e.reduced?"↓":""}${e.width}×${e.height}`,Math.max(e.width,e.height)<PS?pn:J]}function go(e,t,n,r){let i=[...r.keys??[]],s=r.lead,o=r.right,a=()=>{let l=[...s?[Af(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=xS(s,Math.max(0,Af(s)-(a()-t)-1));let u=0;if(r.badge)u=e.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...s?[s]:[],...i.map(([l,f])=>[[l,Ye],[` ${f}`,J]])].forEach((l,f)=>{u=e.run(u+(f?3:0),l)}),o)e.right(t,[[o[0],Ye],[` ${o[1]}`,J]])}function LS(e,t){if(e==="d")return J;if(e==="b")return Ye;if(e==="s")return hu(t.colors.selection);if(e==="c")return hu(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 CS(e,t,n,r,i){let s=Gt.indexOf(Na(r.scene)),o=Gt.flatMap((u,c)=>[...c?[[" ",""]]:[],[u.name,c===s?Ye+i:J]]),a=o.reduce((u,[c])=>u+_e(c),0)<=n;e?.run(t,a?o:[[Na(r.scene).name,Ye+i],[` ${s+1}/${Gt.length}`,J]])}function _S(e,t,n,r,i,s,o){let{ansi:a,cursor:u}=s.colors;CS(e[t-2],n,r,s,o);let c=r<vp?3:4;if(r>=56)c=Math.min(7,Math.floor((r+1)/8)-1);let l=n;for(let d=0;d<8;d++)l=(e[t]?.put(l,"▀".repeat(c),ji(a[d]??u)+hu(a[d+8]??u))??l)+1;let f=t+2;for(let d of Na(s.scene).lines){let h=Mp(d,r);if(!h)continue;if(f>i)return;e[f]?.run(n,h.map(([g,b])=>[g,LS(b,s)])),f++}}function GS(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 WS(e,t,n,r,i){let s=r.info,o=s?.artists??[],a=Bi(r.tiles[r.focus]?.siteAnsi??r.siteAnsi);[["Post",s?.page?Ji(Tw(s.page),"",s.page,a):[["—",J]]],["Source",s?.source?Ji(Tw(s.source),"",s.link,i):[["—",J]]],["Artist",[o.length>0?[o.join(" "),""]:["—",J]]]].forEach(([c,l],f)=>{e[t+f]?.put(n,c,J),e[t+f]?.run(n+12,l)})}function US(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?[Ya(u.bytes)]:[]].join(" · "),d=[o.rating??"—",a.score>0?`★${a.score}`:"",o.posted??""].filter(Boolean).join(" · "),h=(p,m)=>p.length>0?GS(p,l,m).map(($)=>[[$,""]]):[[["—",J]]],g=[["Characters",h(o.characters,2)],["Series",h(o.series,1)],["Tags",h(o.tags,3)],["Rating",[[[d,d==="—"?J:""]]]],["File",[[[f,""],...u?[[" ",""]]:[],...u?Jw(u):[]]]],["Uploader",[[o.uploader?[o.uploader,""]:["—",J]]]]],b=t;for(let[p,m]of g){if(b+m.length-1>i)return;e[b]?.put(n,p,J);for(let $ of m)e[b]?.run(c,$),b++}}var jS=["Size","Position","Opacity"],KS=[0,3,6];function BS(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 JS(e){return e.toFixed(2)}function qS(e,t,n,r,i,s){let o=i.tuning;if(!o)return;let a=i.tiles[i.focus];e[t-3]?.run(n,[[i.palette,Ye+s],[" Background",J],...a?[[" · ",J],...Ji(`${a.site} ${a.id}`,J,a.page||void 0,Bi(a.siteAnsi))]:[]]);let u=Math.max(8,r-n-21),c=20,l=Math.max(100,o.fill);for(let[f,d]of jS.entries()){let h=t+KS[f],g=o.field===f,b=g?Ye:J;if(g)e[h]?.put(n,"▶",s);e[h]?.put(n+2,d,b);let p;if(f===1){for(let m=1;m<=9;m++){let $=m===i.tune.at;e[t+2+Math.floor((m-1)/3)]?.put(n+12+(m-1)%3*3,$?"■":"·",$?Ye+s:J)}p=kt[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)),p=$==="fill"?"fill":`${$}%`}else m=Math.floor(Math.round(i.tune.opacity*100)*(u-1)/100),p=JS(i.tune.opacity);m=Math.max(0,Math.min(u-1,m)),e[h]?.run(n+12,[["━".repeat(m),s],["●",Ye],["─".repeat(u-1-m),J]])}if(e[h]?.right(r-2,[[p,b]]),BS(i,f))e[h]?.put(r-1,"↺",g?Ye+s:J)}}function zS(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 Lf(e,t=e.site,n=e.siteAnsi){return[` ${t} `,`\x1B[7;${30+n}m`]}function fo(e){return`${X[Math.floor(e/Qn)]?.name??"local"} ${e%Qn}`}function lo(e,t,n){let r=X[Math.floor(t/Qn)],i=fo(t),s=e.indexOf(i);if(!r||s===-1)return[[e,n]];return[[e.slice(0,s),n],...Ji(i,n,r.pageUrl(t%Qn),Bi(r.ansi)),[e.slice(s+i.length),n]].filter(([a])=>a!=="")}function VS(e,t,n){let r=[{name:"all",moved:!1},...X].flatMap((s,o)=>{let a=`${s.name}${s.moved?"*":""}`,u=s.name===n.site?Lf(n,a):[` ${a} `,J];return o?[[" ",""],u]:[u]}),i=r.reduce((s,[o])=>s+_e(o),0)<=t;e.run(0,i?r:[Lf(n)])}function YS(e,t,n,r){if(n.editing!==void 0){let u=e.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),c=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";e.put(u,n.editing?c:` A tag, a post URL or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,J);return}let i=e.run(0,[["⌕ ",r],[n.tag||"Nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":J]]),s=Pr.filter((u)=>!n.block.includes(u)),o=X.filter((u)=>!n.enabled.includes(u.name)).map((u)=>u.name),a=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...s.length>0?[`allows ${s.join("+")}`]:[],...n.narrow.size>0?[`≥${n.narrow.size}px`]:[],...n.narrow.score>0?[`score≥${n.narrow.score}`]:[],...n.narrow.png?["png"]:[],...n.hide.length+n.hideTags.length>0?[`hides ${[...n.hide,...n.hideTags].join("+")}`]:[],...o.length>0?[`all skips ${o.join("+")}`]:[]];if(e.put(i,` ${a.join(" ")}`,J),n.total>0||!n.searching){let u=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)u.push([` of ${n.total}`,J]);e.right(t,u)}}function Jw(e){if(e.cut==="on")return[[`Cut out · ${e.clear}% transparent`,ho]];if(e.cut==="off")return[["Opaque · x cuts out",pn]];if(e.cut==="failed")return[["Opaque · no cut-out",pn]];return[e.clear>0?[`${e.clear}% transparent`,ho]:["Opaque",pn]]}function Hw(e){return e.site==="all"?"any site":e.site}function Cf(e,t){if(e.installing!==void 0)return lo(`${Ki(e)} Installing ${e.palette} ← ${fo(e.installing)}`,e.installing,pn);if(e.hint)return[[e.hint,ho]];if(e.error)return[[e.error,pn]];if(e.waiting!==void 0)return[[`${e.slow??e.site} asked to slow down · ${e.waiting}s`,pn]];if(e.fetching){let{id:n,got:r,size:i}=e.fetching;return lo(`${Ki(e)} Fetching ${fo(n)} · ${Qa(r,i)}`,n,pn)}if(e.cutting!==void 0)return lo(`${Ki(e)} Cutting out ${fo(e.cutting)}`,e.cutting,pn);if(e.preparing!==void 0)return lo(`${Ki(e)} Preparing ${fo(e.preparing)}`,e.preparing,pn);if(t)return[t];if(e.saved)return lo(e.saved.text,e.saved.key,ho);if(e.note)return[[e.note,J]];return}function qw(e){if(e.ranking)return"Ranking previews by palette colors";if(e.stage==="check")return e.preset==="cutouts"?"Checking PNG headers":"Loading previews";return"Fetching posts"}function zw(e,t){return e.ranking?`${t}${e.ranking.done}/${e.ranking.total}`:""}function 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=mu(r)%(Pw*2)/Pw,d=Math.round((n-l)*(0.5-0.5*Math.cos(Math.PI*(f<1?f:2-f)))),h=it(s,o,i),g=it(s,it(a,s,0.15),i),b=Array.from({length:n},(m,$)=>{let E=(c>=0?$<c:$>=d&&$<d+l)?h:g;return $===0||$===n-1?it(E,s,0.55):E}),p=0;for(let m=1;m<=n;m++)if(m===n||b[m]!==b[p])e?.put(t+p," ".repeat(m-p),hu(b[p])),p=m}function ZS(e,t,n,r,i){let{background:s,foreground:o}=i.colors,a=i.loaderFrom===void 0?0:Math.min(1,(mu(i)-i.loaderFrom)/OS),u=t+(n>=5?Math.floor((n-5)/2):0);e[u]?.center(r,[[qw(i),Ye+ji(it(s,o,a))],[zw(i," "),ji(it(s,it(o,s,0.45),a))]]);let c=Math.min(RS,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?[[" · ",ji(it(s,o,0.25*a))]]:[],[l,ji(it(s,f?it(o,s,0.2):o,f?a:0.32*a))]]))}function XS(e,t,n,r,i,s){if(i<=r)return;let o=Math.max(1,Math.round(r*r/i)),a=Math.max(0,Math.min(r-o,Math.round(n.scroll*r/i)));for(let u=0;u<r;u++){let c=u>=a&&u<a+o;e[2+u]?.put(t-1,c?"┃":"│",c?s:J)}}function DS(e,t,n){if(t)return[`${Ki(e)} ${qw(e)}${zw(e," · ")}`,J];let r=n.filter((s)=>!s.missing),i=r.filter((s)=>s.thumb).length;return i<r.length?[`${Ki(e)} Loading thumbnails · ${i}/${r.length}`,J]:void 0}function eI(e,t,n,r,i,s){let{perRow:o,rowsVis:a,height:u}=zr(n,r);YS(e[0],n,i,s),VS(e[1],n,i);let c=e.map((k,N)=>N>=2&&N<2+u?k:void 0),l=Math.floor(i.scroll/Je.height),f=Math.floor((i.scroll+u-1)/Je.height),d=[];for(let k=l;k<=f;k++){let N=2+k*Je.height-i.scroll;for(let R=0;R<o;R++){let H=k*o+R,x=R*Je.pitch,C=i.tiles[H];if(!C)continue;d.push(C);let W=H===i.focus;if(W)zS(c,N,x,Je.height,Je.pitch-1,s);let A=N+1,F=Math.max(A,2),q=Math.min(A+Je.rows,2+u);if(C.thumb&&q>F)t.push({id:C.key,path:C.thumb,row:F,col:x+1,cols:Je.cols,rows:q-F,...q-F<Je.rows?{crop:F-A}:{},z:-1});let Ee=[...i.installed.includes(C.key)?[["✓ ",ho]]:[],...C.page||i.site!=="all"?Ji(String(C.id),W?Ye:"",C.page||void 0,Bi(C.siteAnsi)):[["● ",Bi(C.siteAnsi)],[String(C.id),W?Ye:""]],[" ",""],Bw(C)],be=Je.cols-(C.mates.length>0?1:0);if(c[N+10]?.run(x+1,Af(Ee)>be?Ee.map(([Ae,he,ce])=>[Ae.replace(/^(\S) $/,"$1"),he,ce]):Ee),C.mates.length>0)c[N+10]?.put(x+Je.cols,"≈",s);c[N+11]?.put(x+1,C.artist?AS(C.artist).slice(0,Je.cols-8):"—",J);let Y=[];if(C.score>0)Y.push([`★${C.score}`,J]);if(C.variants>1)Y.push([` ×${C.variants}`,s]);if(Y.length>0)c[N+11]?.right(x+Je.cols+1,Y)}}let h=Math.ceil(i.tiles.length/o)*Je.height;XS(e,n,i,u,h,s);let g=Math.max(2,2+h-i.scroll),b=2+u-g,p=i.searching&&b>=2;if(p)ZS(c,g,b,n-1,i);let m=i.searching&&i.tiles.length===0;if(m&&!i.error){let[k,N]=Rw[Math.floor(mu(i)/FS)%Rw.length];e[r-2]?.run(0,[["Tip ",J],[k,Ye],[` ${N}`,J]])}let $=i.top*o,E=i.tiles.length-(i.top+a)*o,M=[...$>0?[`↑ ${$} above`]:[],...E>0?[`↓ ${E} more`]:[]];if(M.length>0)e[r-2]?.put(0,M.join(" "),J);if(!i.searching&&i.tiles.length===0&&!i.error&&i.tag)e[3]?.put(0,i.preset==="cutouts"?`No transparent cutouts of ${i.tag} on ${Hw(i)} — c searches every post, tab tries ${i.nextSite}`:`No posts of ${i.tag} on ${Hw(i)} — tab tries ${i.nextSite}`,J);let w=DS(i,p,d),S=Cf(i,w);return go(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"]}),p}function tI(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=[Lf(i,o.site,o.siteAnsi),[" ",""],...Ji(String(o.id),Ye,o.page||void 0,Bi(o.siteAnsi)),[" ",""],Bw(o)];if(o.score>0)u.push([` · ★${o.score}`,J]);if(a)u.push([` · ${Ya(a.bytes)}`,J]);if(a)u.push([" ",""],...Jw(a));if(e[0]?.run(0,u),o.mates.length>0)e[0]?.right(n,[["≈ ",s],[o.mates.join(" "),J]]);if(WS(e,1,2,i,s),i.tuning)qS(e,8,2,2+Math.min(n-4,60),i,s);else if(i.details)US(e,5,2,Math.min(n-4,Math.max(48,Math.floor(n*0.55))),r-2,i);else _S(e,7,2,n-4,r-2,i,s);if(i.shown)t.push({id:IS+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:NS});if(i.tuning){go(e[r-1],n,s,{badge:"IMAGE EDIT",lead:Cf(i),keys:[["↑↓","field"],["←→","step"],["=","reset"],["+","reset all"],i.tuning.field===1?["1-9","place"]:["⇧←→","×10"],["enter","keep"]],right:["esc","undo"]});return}let c=Cf(i);go(e[r-1],n,s,{badge:"IMAGE PREVIEW",lead:c,keys:i.installing===void 0?[["←→","browse"],["enter","install"],["t","tune"],["i","details"],...i.details?[]:[["⇧←→","example"]],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var nI=[["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"]],rI={grid:[["Move","←↑↓→ home end pgup pgdn"],["Try on","enter"],["Site",`tab shift+tab all, ${X.map((e)=>e.name).join(", ")}`],["Posts","c cutouts or every post"],["Search","/ a tag, a post URL or an id"],["Your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["Unfold","space a set of ×N"],["Open","o the post page in a browser"],["Settings","s rating, block, posts, solo, order, sets, remove bg"],["Advanced","a or Advanced › in settings min score, min size, sites, hide, hide tags, PNG only"],["Back","esc returns to preview"],["Close","? esc"]],try:[["Browse","←→"],["Install","enter"],["Tune","t size, position and opacity, installed with the picture"],["Details","i characters, series, tags, rating and file, under Post, Source and Artist"],["Example",`⇧←→ ${Gt.map((e)=>e.name.toLowerCase()).join(", ")}`],["Cut out","x the background off or on, on an opaque picture"],["Open","o the post page in a browser"],["Your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["Grid","esc"],["Close","? esc"]]},Wf=6,iI=24;function mo(e){return[...e.settings.flatMap((t,n)=>Boolean(t.advanced)===e.advanced?[n]:[]),e.settings.length]}function sI(e){return e.replace(/^[A-Z](?=[a-z])/,(t)=>t.toLowerCase())}function xw(e){let t=e.settings.filter((n)=>Boolean(n.advanced)!==e.advanced).map((n)=>sI(n.label));return`${e.advanced?"Back to":"More filters:"} ${t.join(", ")} — enter opens the page, or a from any row`}function Vw(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 Jr(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 oI(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 aI(e,t,n,r){let i=`\x1B[7;${30+r}m`,s=t&&n!==void 0;if(e.entry==="text")return[{text:` ${s?`${n}█`:e.value||"none"} `,sgr:s||t&&e.value?i:e.value?"":J}];let o=s?[]:e.value.split(" "),a=(s?e.choices:oI(e)).map((u,c)=>{let l=o.includes(u),f=e.multi&&t&&c===e.cursor?"4;":"";return{text:e.multi?` ${l?"[x]":"[ ]"} ${u} `:` ${u} `,sgr:l?t?`\x1B[${f}7;${30+r}m`:"":f?`\x1B[4m${J}`:J}});return s?[...a,{text:` ${n}█ `,sgr:i}]:a}function Aw(e){if(e.entry==="text")return[{text:" ".repeat(iI),sgr:""}];let t=e.choices.map((n)=>({text:e.multi?` [x] ${n} `:` ${n} `,sgr:""}));return e.entry==="number"?[...t,{text:` ${"0".repeat(Wf)}█ `,sgr:""}]:t}function uI(e){return e.reduce((t,n)=>t+_e(n.text)+1,0)-1}function Lw(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 Cw(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 _w(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 cI(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 lI(e,t,n,r,i){let s=r.panel??0,o=r.settings.length,u=6+Math.max(...r.settings.map((A)=>_e(A.label))),c=Math.max(...r.settings.map((A)=>_e(Cw(A)))),l=u+Math.max(...r.settings.map((A)=>uI(Aw(A))))+c+5,f=Math.min(t-2,Math.max(48,l)),d=f-u-c-5,h=f-7,g=[!1,!0].map((A)=>({advanced:A,rows:mo({settings:r.settings,advanced:A}).slice(0,-1)})),b=r.settings.map((A)=>Lw(Aw(A),d).length),p=Math.max(...g.map((A)=>A.rows.reduce((F,q)=>F+b[q],0))),m=Math.max(...g.map((A)=>Jr(xw({settings:r.settings,advanced:A.advanced}),h).length),...r.settings.map((A)=>Jr(A.about,h).length)),$=`${r.tag}: ${X.map((A)=>`${A.name} 0,000,000`).join(" · ")}`,E=r.tag?Math.max(Jr($,h).length,Jr(_w(r),h).length):0,M=p+m+E+8,w=Math.floor((t-f)/2),S=Math.max(1,Math.floor((n-1-M)/2)),k=`\x1B[7;${30+r.siteAnsi}m`;e[S]?.put(w,`╭─ Settings ${"─".repeat(Math.max(0,f-13))}╮`);for(let A=S+1;A<S+M-1;A++)e[A]?.put(w,`│${" ".repeat(f-2)}│`);let N=S+2;for(let A of mo(r).slice(0,-1)){let F=r.settings[A],q=A===s;if(q)e[N]?.put(w+2,"▶",i);if(e[N]?.put(w+4,F.label,q?Ye:""),F.value!==F.default)e[N]?.right(w+f-3,[[Cw(F),J]]);Lw(aI(F,q,r.typing,r.siteAnsi),d).forEach((Ee,be)=>{let Y=w+u;for(let Ae of Ee)Y=e[N+be].put(Y,Ae.text,Ae.sgr)+1}),N+=b[A]}let R=g.find((A)=>A.advanced!==r.advanced)?.rows??[],H=e[S+3+p];if(s===o)H.put(w+2,"▶",i);let x=H.put(w+3,r.advanced?" ‹ Basic ":" Advanced › ",s===o?k:Ye);if(R.some((A)=>r.settings[A]?.value!==r.settings[A]?.default))H.put(x+1,"•",J);e[S+5+p]?.put(w+2,"─".repeat(f-4),J),Jr(r.settings[s]?.about??xw(r),h).forEach((A,F)=>{e[S+6+p+F]?.put(w+4,A)}),Jr(_w(r),h).forEach((A,F)=>{e[S+6+p+m+F]?.put(w+4,A,J)}),e[S+M-1]?.put(w,`╰${"─".repeat(f-2)}╯`);let{keys:C,right:W}=cI(r,r.settings[s]);go(e[n-1],t,i,{keys:C,right:W})}function fI(e,t,n,r,i){let s=r.tuning?nI:rI[r.mode],o=Math.min(t-2,Math.max(50,...s.map(([,d])=>_e(d)+16))),a=s.map(([d,h])=>({label:d,parts:Jr(h,o-16)})),u=a.reduce((d,{parts:h})=>d+h.length,0)+4,c=Math.floor((t-o)/2),l=Math.max(2,Math.floor((n-u)/2));e[l]?.put(c,`╭─ Help ${"─".repeat(o-9)}╮`);for(let d=l+1;d<l+u-1;d++)e[d]?.put(c,`│${" ".repeat(o-2)}│`);let f=l+2;for(let{label:d,parts:h}of a){e[f]?.put(c+3,d,Ye);for(let g of h)e[f]?.put(c+13,g),f++}e[l+u-1]?.put(c,`╰${"─".repeat(o-2)}╯`),go(e[n-1],t,i,{badge:"HELP",right:["? esc","close"]})}function dI(e,t,n){let r=t.suggest??[],i=r.map((a)=>a.count>0?String(a.count):a.palette??"0"),s=Math.max(...r.map((a)=>_e(a.value))),o=Math.max(7,...i.map(_e));r.forEach((a,u)=>{let c=u===t.pick,l=e[1+u];l?.run(0,[[c?"▸ ":" ",n],[a.value,c?Ye+n:""]]),l?.right(2+s+2+o,[[i[u],J]])})}function Uf(e,t,n){let r=Array.from({length:n},()=>new du(t)),i=[],s=ji(e.colors.cursor);if(xf=!1,t<qr.cols||n<qr.rows)return r[0]?.put(0,"ttheme find",Ye+s),r[1]?.put(0,`Needs ${qr.cols}×${qr.rows} — now ${t}×${n}`),r[2]?.put(0,"esc quits",J),{lines:r.map((a)=>a.render()),images:i,loader:!1,tick:!1};let o=!1;if(e.mode==="try")tI(r,i,t,n,e,s);else o=eI(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 du(t);return dI(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 du(t);if(e.help)fI(r,t,n,e,s);else lI(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:xf}}var jf=5,hI=6,Yw=0.05,gI=[1,2,3,4,5,6,9,10,11,12,13,14],Qw=(e,t)=>(t-e+360)%360<=180?1:-1;function po(e,t,n){let r=t*Math.cos(n*Math.PI/180),i=t*Math.sin(n*Math.PI/180),s=[e+0.3963377774*r+0.2158037573*i,e-0.1055613458*r-0.0638541728*i,e-0.0894841775*r-1.291485548*i].map((l)=>l**3),[o,a,u]=s,c=[4.0767416621*o-3.3077115913*a+0.2309699292*u,-1.2684380046*o+2.6097574011*a-0.3413193965*u,-0.0041960863*o-0.7034186147*a+1.707614701*u];if(c.some((l)=>l<-0.0001||l>1.0001))return;return c.map((l)=>{let f=Math.min(1,Math.max(0,l));return Math.round(255*(f<=0.0031308?12.92*f:1.055*f**0.4166666666666667-0.055))})}function Wt(e,t,n){let r=0,i=t;if(po(e,t,n)===void 0)for(let o=0;o<24;o++){let a=(r+i)/2;if(po(e,a,n)===void 0)i=a;else r=a}else r=t;return`#${(po(e,r,n)??[0,0,0]).map((o)=>o.toString(16).padStart(2,"0")).join("")}`}function mI(e,t){let{l:n,c:r}=Be(e);return Wt(n,r,(t+360)%360)}function pI(e,t,n){let{l:r,c:i,h:s}=Be(e),o=Ve(t)<0.18,a=(l)=>Wt(o?r+(1-r)*l:r*(1-l),i,s);if(Ke(a(1),t)<n+Yw)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+Yw)c=f;else u=f}return a(c)}function bI(e,t){let{l:n,c:r,h:i}=Be(e),s=0,o=n;for(let a=0;a<30;a++){let u=(s+o)/2;if(Ve(Wt(u,r,i))<=t-0.005)s=u;else o=u}return Wt(s,r,i)}function wI(e,t,n){let r=$n[t],[i,s]=[Be(e[t]),Be(e[t+8])],o=(l,f)=>n.has(l)?[f]:Array.from({length:2*r.width+1},(d,h)=>(r.center-r.width+h+360)%360),a=(l,f,d)=>Cn.every((h)=>{let g=(l>8?8:0)+h;if(g===l)return!0;let b=Be(e[g]);return b.c<as||Dt(b.h,f)>=ii+1||Math.abs(b.l-d)>=si}),u,c=Number.POSITIVE_INFINITY;for(let l of o(t,i.h)){if(!n.has(t)&&!a(t,l,i.l))continue;for(let f of o(t+8,s.h)){if(Dt(l,f)>jt-jf||!n.has(t+8)&&!a(t+8,f,s.l))continue;let d=Dt(l,i.h)+Dt(f,s.h);if(d<c)c=d,u=[l,f]}}return u}class Zw{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,mI(this.theme.ansi[e],n))}roles(){let e=new Set(this.theme.signatureSlots);for(let{slot:n,hue:r}of ri(this.theme)){let i=$n[_n(n)];this.rehue(n,"ansi-role",i.center+Qw(i.center,r)*(i.width-jf))}for(let{normal:n,gap:r}of Mr(this.theme)){if(r<=jt)continue;let[i,s]=e.has(`ansi${n+8}`)?[n+8,n]:[n,n+8],o=Be(this.theme.ansi[i]).h,a=Be(this.theme.ansi[s]).h;this.rehue(s,"bright-follows",o+Qw(o,a)*(jt-jf))}let t=oi(this.theme);for(let[n,r]of Sr(this.theme)){let i=_n(t.has(r)?n:r),s=wI(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,pI(this.get(a),o,s))};if(n("foreground",["foreground"],7),n("accents",gI.map((r)=>`ansi${r}`),3),n("light-ansi",["ansi7","ansi15"],7),n("ansi8-visible",["ansi8"],1.6),!e.has("ansi0-dark")&&Ve(this.get("ansi0"))>0.15)this.set("ansi0","ansi0-dark",bI(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 pu(e){let t=new Zw(e);for(let n=0;n<hI;n++)if(t.readability(),t.roles(),Ir(t.theme).length===0)break;return{theme:t.theme,moves:t.net(),left:Ir(t.theme)}}var bo=[{key:"background",label:"Background",min:0,max:0.5,step:0.01,digits:2},{key:"foreground",label:"Foreground",min:0.5,max:1,step:0.01,digits:2},{key:"hue",label:"Hue",min:0,max:360,step:1,digits:0,wraps:!0},{key:"tint",label:"Tint",min:0,max:0.1,step:0.005,digits:3},{key:"lightness",label:"Accent lightness",min:0.4,max:0.95,step:0.01,digits:2},{key:"chroma",label:"Accent chroma",min:0,max:0.3,step:0.005,digits:3},{key:"brights",label:"Brights",min:-0.2,max:0.2,step:0.01,digits:2}],bu={background:0.21,foreground:0.88,hue:265,tint:0.02,lightness:0.72,chroma:0.12,brights:0.06},Xw=(e,t,n)=>Math.min(n,Math.max(t,e));function Dw(e,t,n){let r=e[t.key]+t.step*n,i=t.wraps?(r%t.max+t.max)%t.max:Xw(r,t.min,t.max);return{...e,[t.key]:Math.round(i*1e4)/1e4}}function Vr(e){let t=(r,i,s)=>Wt(Xw(r,0,1),i,s),n=Array.from({length:16},()=>"#000000");n[0]=t(e.background+0.06,e.tint,e.hue),n[8]=t(e.background+0.25,e.tint,e.hue),n[7]=t(e.foreground-0.06,e.tint/2,e.hue),n[15]=t(e.foreground+0.06,e.tint/2,e.hue);for(let r of Cn){let i=$n[r].center;n[r]=t(e.lightness,e.chroma,i),n[r+8]=t(e.lightness+e.brights,e.chroma,i)}return{background:t(e.background,e.tint,e.hue),foreground:t(e.foreground,e.tint/2,e.hue),cursor:t(e.lightness+e.brights,Math.max(e.chroma,0.08),e.hue),selection:t(e.background+0.1,e.tint*2,e.hue),ansi:n}}var ko=["background","foreground","cursor","selection",...Array.from({length:16},(e,t)=>`ansi${t}`)],Pt=["Background","Foreground","Cursor","Selection"],Eu=["Black","Red","Green","Yellow","Blue","Magenta","Cyan","White"],wo=Pt.length+Eu.length,Yr=[{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}],e0=5;function $I(e){let t=e.trim();return/^https?:\/\/\S+$/i.test(t)||Ui(t).length>0}function wu(e){return[e.background,e.foreground,e.cursor,e.selection,...e.ansi]}function Fn(e){let[t,n,r,i,...s]=e;return{background:t,foreground:n,cursor:r,selection:i,ansi:s}}function $u(e){if(e<Pt.length)return{name:Pt[e],about:ko[e]};let t=e-Pt.length,n=Eu[t%8];return t<8?{name:n,about:`ansi ${t}`}:{name:`Bright ${n.toLowerCase()}`,about:`ansi ${t}`}}var ku=(e,t,n)=>Math.min(n,Math.max(t,e));function kI(e){return ku(Math.round(e),0,255).toString(16).padStart(2,"0")}function t0(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)=>kI(Number(s))).join("")}`;let i=/^oklch\(\s*([\d.]+)(%?)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:deg|°)?\s*\)$/.exec(t);if(i){let s=Number(i[1])/(i[2]?100:1);return Wt(ku(s,0,1),Number(i[3]),Number(i[4])%360)}return}function yu(e){let t=bt.find((n)=>n.rule===e);return t?.min??t?.max??0}function $o(e,t,n){let r=Fn(e);return{name:"draft",background:r.background,foreground:r.foreground,selectionBackground:r.selection,ansi:r.ansi,waive:n,signatureSlots:t}}function yI(e,t,n){let r=$o(e,t,n),i=(f)=>!n.includes(f),{background:s,foreground:o,selection:a,ansi:u}=Fn(e),c=new Set,l=(f,d,h,g)=>{if(i(g)&&Ke(d,h)<yu(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")&&Ve(u[0])>yu("ansi0-dark"))c.add(4);if(i("ansi-role"))for(let{slot:f}of ri(r))c.add(4+f);if(i("bright-follows")){for(let{normal:f,gap:d}of Mr(r))if(d>jt)c.add(4+f+8)}if(i("distinct"))for(let[f,d]of Sr(r))c.add(4+f).add(4+d);return c}function On(e,t,n,r,i){let s=Ke(e,t),o=yu(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 n0(e,t,n,r){let i=Fn(e),s=$o(e,t,n);if(r===0){let m=[1,2,3,4,5,6,9,10,11,12,13,14].reduce(($,E)=>Ke(i.ansi[$],i.background)<=Ke(i.ansi[E],i.background)?$:E);return[On(i.foreground,i.background,"foreground","Foreground on it",n),On(i.ansi[m],i.background,"accents",`Weakest, ANSI ${m},`,n),On(i.ansi[8],i.background,"ansi8-visible","ANSI 8 on it",n)]}if(r===1)return[On(i.foreground,i.background,"foreground","On background",n),On(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[On(i.foreground,i.selection,"selection","Foreground on it",n)];let o=r-Pt.length,a=i.ansi[o];if(o===0){let p=Ve(a),m=yu("ansi0-dark");return[n.includes("ansi0-dark")?{ok:void 0,text:`Luminance ${p.toFixed(3)} · waived`}:{ok:p<=m,text:`Luminance ${p.toFixed(3)} · ≤ ${m}`}]}if(o===7||o===15)return[On(a,i.background,"light-ansi","On background",n)];if(o===8)return[On(a,i.background,"ansi8-visible","On background",n)];let u=[On(a,i.background,"accents","On background",n)],c=Be(a),l=_n(o),f=$n[l],d=`${f.name} ${f.center}±${f.width}°`;if(c.c<as)u.push({ok:void 0,text:"Too grey to have a hue"});else if(oi(s).has(o))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · a signature, free of ${d}`});else if(n.includes("ansi-role"))u.push({ok:void 0,text:`Hue ${c.h.toFixed(0)}° · ${d} waived`});else{let p=Dt(c.h,f.center)-f.width;u.push(p>0?{ok:!1,text:`Hue ${c.h.toFixed(0)}° · ${p.toFixed(0)}° outside ${d}`}:{ok:!0,text:`Hue ${c.h.toFixed(0)}° · in ${d}`})}let h=o<8?o+8:o-8,g=Mr(s).find((p)=>p.normal===l);if(g)u.push(n.includes("bright-follows")?{ok:void 0,text:`${g.gap.toFixed(0)}° from ANSI ${h} · waived`}:{ok:g.gap<=jt,text:`${g.gap.toFixed(0)}° from ANSI ${h} · ≤ ${jt}°`});let b=Sr(s).flatMap(([p,m])=>p===o?[m]:m===o?[p]:[]);if(b.length>0&&!n.includes("distinct"))u.push({ok:!1,text:`Reads as ANSI ${b.join(", ")} · within ${ii}° and ${si} lightness`});return u}function r0(e,t,n){let r=Gn($o(e,t,n));return bt.map((i,s)=>{let o=r[s],a=n.includes(i.rule);return{ok:a||Number.isNaN(o)?void 0:(i.min===void 0||o>=i.min)&&(i.max===void 0||o<=i.max),label:i.label,value:Number.isNaN(o)?"—":Number.isInteger(o)?String(o):o.toFixed(2),bound:a?"waived":i.min!==void 0?`≥ ${i.min}`:i.max!==void 0?`≤ ${i.max}`:""}})}var EI=new Set(["reset","hex","paste","fix","open","seeds","tune","sig","follow"]);class Kf{mode;seeds=bu;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=wu(e.colors??Vr(this.seeds)),this.lch=this.list.map(Be),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 Fn(this.list)}edited(){return{colors:this.colors(),signature:[...this.signature]}}shown(){return this.compare?this.start:this.list}slot(){return this.row<Pt.length?this.row:this.row+(this.col===1?8:0)}dirty(){return this.seeded||this.pictures!==this.startPictures||this.list.some((e,t)=>e!==this.start[t])||this.signature.join()!==this.startSignature.join()}misses(){return yI(this.list,this.signature,this.waive)}failing(){return Ir($o(this.list,this.signature,this.waive))}choices(){let e=this.filter.toLowerCase();return(this.options.palettes??[]).filter((t)=>t.name.toLowerCase().includes(e))}paste(e){if(this.notice=void 0,this.overlay==="open"){this.filter+=e.replace(/\s+/g,"").toLowerCase(),this.pick=0;return}if(this.overlay)return;if(e.trim()===""){this.findPictures({clipboard:!0});return}if($I(e)){this.findPictures({paste:e});return}if(this.mode==="seeds")return;let t=t0(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()]=Be(t);else this.set(this.slot(),t,"paste")}press(e){if(this.notice=void 0,e==="ctrl-c"){this.result="cancelled";return}if(this.quitting){if(this.quitting=!1,e==="y"||e==="Y")this.result="cancelled";return}if(this.typing!==void 0){this.type(e);return}if(this.overlay==="keys"){this.overlay=void 0;return}if(this.overlay==="open"){this.openKey(e);return}if(e==="?"){this.overlay="keys";return}if(e==="ctrl-v"||e==="alt-v"){this.findPictures({clipboard:!0});return}if(e==="p"&&this.mode!=="tune"){this.findPictures();return}if(e===" "&&this.mode!=="seeds"){this.compare=!this.compare;return}if(this.compare&&e==="esc"){this.compare=!1;return}if(this.mode==="seeds")this.seedKey(e);else if(this.mode==="tune")this.tuneKey(e);else this.listKey(e)}seedKey(e){let t=bo.length;if(e==="up"||e==="down")this.field=(this.field+(e==="up"?t-1:1))%t;else if(e==="home"||e==="end")this.field=e==="home"?0:t-1;else if(e==="left"||e==="right"||e==="shift-left"||e==="shift-right"){let n=bo[this.field],r=(e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:e0:1);this.seeds=Dw(this.seeds,n,r),this.list=wu(Vr(this.seeds)),this.lch=this.list.map(Be)}else if(e==="enter")this.leaveSeeds();else if(e==="o")this.openPalettes();else if(e==="esc")if(this.seedsBack){let n=this.history.pop();if(n)this.restore(n);this.mode="list",this.seedsBack=!1}else this.result="cancelled"}leaveSeeds(){if(this.fresh&&!this.seeded)this.start=[...this.list];this.seeded=!0,this.seedsBack=!1,this.mode="list"}findPictures(e){if(!this.options.find){this.notice="Pictures need Ghostty, iTerm2 or kitty, outside tmux";return}this.wants=e?{start:e}:{}}openPalettes(){if((this.options.palettes??[]).length>0)this.overlay="open",this.pick=0;else this.notice="No other palettes to take colors from"}listKey(e){if(e==="up"||e==="down")this.row=(this.row+(e==="up"?wo-1:1))%wo,this.lastEdit=void 0;else if(e==="home"||e==="end")this.row=e==="home"?0:wo-1;else if(e==="pgup"||e==="pgdn")this.row=e==="pgup"?0:Pt.length;else if(e==="left"||e==="right")this.col=e==="left"?0:1,this.lastEdit=void 0;else if(e==="tab")this.tune();else if(e==="#")this.typing="";else if(e==="c")this.clip=this.list[this.slot()],this.notice=`Copied ${this.clip}`;else if(e==="v")if(this.clip)this.set(this.slot(),this.clip,"paste");else this.notice="Nothing copied yet — c copies a slot";else if(e==="r")this.set(this.slot(),this.start[this.slot()],"reset");else if(e==="=")this.follow();else if(e==="*")this.mark();else if(e==="f")this.fix();else if(e==="s")this.remember("seeds"),this.mode="seeds",this.seedsBack=!0;else if(e==="o")this.openPalettes();else if(e==="u")this.undo();else if(e==="\x12")this.redo();else if(e==="enter"||e==="\x13")this.save();else if(e==="esc")if(this.dirty())this.quitting=!0;else this.result="cancelled"}tune(){let e=this.slot();this.remember("tune"),this.tuneFrom={hex:this.list[e],lch:this.lch[e]},this.mode="tune"}tuneKey(e){let t=Yr.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=Yr[this.channel];this.step((e.endsWith("left")?-1:1)*(e.startsWith("shift")?n.wraps?10:e0:1))}else if(/^[0-9]$/.test(e)){let n=Yr[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=Yr[this.channel],n=this.lch[this.slot()][t.key];this.put(n+t.step*e)}put(e){let t=this.slot(),n=Yr[this.channel],r=n.wraps?(e%n.max+n.max)%n.max:ku(e,n.min,n.max),i={...this.lch[t],[n.key]:Math.round(r*1e4)/1e4};this.lch[t]=i,this.list[t]=Wt(i.l,i.c,i.h)}type(e){let t=this.typing??"";if(e==="esc")this.typing=void 0;else if(e==="enter"){let n=t0(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()]=Be(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=wu(n.colors),this.lch=this.list.map(Be),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||EI.has(e))this.history.push({list:[...this.list],lch:[...this.lch],signature:[...this.signature]}),this.future=[];this.lastEdit=e}set(e,t,n){if(!Ht(t)||this.list[e]===t)return;this.remember(n),this.list[e]=t,this.lch[e]=Be(t)}follow(){if(this.row<Pt.length){this.notice="= works on an ANSI row — the bright takes its normal";return}let e=this.row,t=this.row+8,n=this.lch[e],r={l:ku(n.l+0.06,0,1),c:n.c,h:n.h};this.remember("follow"),this.lch[t]=r,this.list[t]=Wt(r.l,r.c,r.h),this.col=1,this.notice=`${$u(t).name} follows ${$u(e).name.toLowerCase()}`}mark(){let e=ko[this.slot()];this.remember("sig"),this.signature=this.signature.includes(e)?this.signature.filter((t)=>t!==e):[...this.signature,e].slice(-3),this.notice=this.signature.length===3?`Signature: ${this.signature.join(", ")}`:`The signature needs three slots — ${this.signature.length} marked`}fix(){let e=$o(this.list,this.signature,this.waive),{theme:t,moves:n,left:r}=pu({...e,selectionBackground:e.selectionBackground,signatureSlots:this.signature});if(n.length===0){this.notice=Ir(e).length===0?"Already passes the gate":"No color change fixes it";return}this.remember("fix");let i=wu({...this.colors(),foreground:t.foreground,selection:t.selectionBackground,ansi:t.ansi});this.lch=i.map((s,o)=>s===this.list[o]?this.lch[o]:Be(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 Jf=80,qf=24,vu=48,Bf=11;function vI(e){return{color:e,dim:(t)=>e?`\x1B[2m${t}\x1B[22m`:t,bold:(t)=>e?`\x1B[1m${t}\x1B[22m`:t,fg:(t)=>e?Xt(t):"",bg:(t)=>e?`\x1B[48;2;${ve(t).join(";")}m`:""}}function MI(e){return Ve(e)>0.35?"#000000":"#ffffff"}function s0(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(MI(a))}●\x1B[39;49m`;return s?`${e.fg(s)}█`:`${e.fg(r?"#777777":"#555555")}░`}).join("").concat("\x1B[39m")}function SI(e,t,n){return Array.from({length:n},(r,i)=>{let s=t.min+(t.max-t.min)*i/(n-1),o={...e,[t.key]:s};return po(o.l,o.c,o.h)?Wt(o.l,o.c,o.h):void 0})}function o0(e,t,n,r){return Math.round((e-t)/(n-t)*(r-1))}var i0={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 a0(e,t){return t===void 0?e.dim("·"):t?e.dim("✓"):e.bold("✗")}function u0(e,t,n){let r=r0(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=vu-4;return[s,...r.slice(0,Math.max(0,n-1)).map((a)=>{let u=`${a.value} ${a.bound}`;return` ${a0(e,a.ok)} ${bn(a.ok===!1?a.label:e.dim(a.label),e.dim(u),o-2)}`})]}function II(e,t,n){let r=t.misses(),i=Fn(t.list),s=t.slot(),o=(l)=>e.color?`${e.bg(i.selection)}${e.fg(i.foreground)}${l}\x1B[39;49m`:`[${l}]`,a=(l)=>{let f=t.list[l],d=l===s,h=t.signature.includes(ko[l])?"◆":e.color?"■":" ",g=l===0?void 0:l===3?Ke(i.foreground,i.selection):Ke(f,i.background),b=g===void 0?"":g.toFixed(1),p=r.has(l)?"✗":" ",$=`${e.color?`${e.fg(f)}${h}${d?e.fg(i.foreground):"\x1B[39m"} `:`${h} `}${f} ${b.padStart(4)}${p}`;return d?o(` ${$} `):` ${$} `},u=(l)=>l?e.color?`${e.fg(i.cursor)}▌\x1B[39m `:"▌ ":" ",c=[` ${e.dim("Base")}`];for(let l=0;l<Pt.length;l++){let f=l===t.row,d=Pt[l].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}`)}c.push("",` ${e.dim(`${"ANSI".padEnd(10)} Normal${" ".repeat(11)}Bright`)}`);for(let l=Pt.length;l<wo;l++){let f=l===t.row,d=Eu[l-Pt.length].padEnd(10);c.push(`${u(f)}${f?e.bold(d):d}${a(l)}${a(l+8)}`)}return c.push(""),[...c,...u0(e,t,n-c.length)]}function NI(e,t,n){let r=Fn(t.list),i=[` ${e.dim("Seeds")}`];bo.forEach((s,o)=>{let a=o===t.field,u=t.seeds[s.key],c=Array.from({length:Bf},(b,p)=>{let m=s.min+(s.max-s.min)*p/(Bf-1);return i0[s.key](Vr({...t.seeds,[s.key]:m}))}),l=s0(e,c,o0(u,s.min,s.max,Bf),a),f=`${u.toFixed(s.digits)}${s.wraps?"°":""}`.padStart(6),d=i0[s.key](r),h=a?e.color?`${e.fg(r.cursor)}▌\x1B[39m `:"▌ ":" ",g=s.label.padEnd(17);i.push(`${h}${a?e.bold(g):g}${l} ${f} ${e.color?`${e.fg(d)}■\x1B[39m `:""}${e.dim(d)}`)}),i.push("");for(let s of Qe("Seven seeds grow all twenty colors, each accent on the hue its ANSI role reads as — whatever the seeds, they pass the gate. enter moves on to tune each slot.",vu-4))i.push(` ${e.dim(s)}`);return i.push(""),[...i,...u0(e,t,n-i.length)]}function c0(e,t,n){let r=(f)=>e.fg(t.ansi[f]),i=e.fg(t.foreground),s=`${e.bg(t.background)}${i}`,o=(f)=>e.color?`\x1B[1m${f}\x1B[22m`:f,a=`${r(2)}❯${i} `,u=Math.max(2,Math.min(4,Math.floor((n-9)/8)));return[Array.from({length:8},(f,d)=>`${e.fg(t.ansi[d])}${e.bg(t.ansi[d+8])}${(e.color?"▀":"#").repeat(u)}${s} `).join(""),"",`${o(`${r(4)}~/code/demo`)}${i} on ${r(5)}main${r(2)} +2${r(3)} ~1${i}`,`${a}git status -sb`,`## ${r(2)}main${i}...${r(1)}origin/main${r(3)} [ahead 1]${i}`,`${r(1)} M${i} src/main.rs ${r(1)}??${i} notes.md`,`${a}git diff`,`${r(6)}@@ -12,2 +12,2 @@${i}`,`${r(1)}- let size = 12;${i}`,`${r(2)}+ let size = 14;${i}`,`${a}cargo test`,`${r(2)} ✓${i} parses config`,`${r(1)} ✗${i} renders frame ${r(8)}expected 3, received 2${i}`,`${r(11)} ⚠ 1 warning${i} ${r(12)}ℹ 2 notes${i} ${r(13)}λ${i} ${r(14)}~${i} ${r(9)}✗${i} ${r(10)}✓${i}`,`${a}ls`,`${o(`${r(4)}docs`)} ${o(`${r(4)}src`)} ${r(2)}run.sh${i} ${r(6)}link${i} Cargo.toml`,`${a}echo ${e.bg(t.selection)}selected text${s} ${e.bg(t.cursor)} ${s}`,`${r(7)}ansi 7 text${i} ${r(15)}ansi 15 text${i} ${r(8)}# ansi 8 comment${i}`].map((f)=>`${s} ${rt(f,n-2)} ${e.color?"\x1B[0m":""}`)}function PI(e,t,n,r){let i=t.slot(),s=t.list[i],o=t.lch[i],a=Be(s),u=t.start[i],{name:c,about:l}=$u(i),f=t.signature.includes(ko[i]),d=[bn(`${e.bold(c)} ${e.dim(l)}`,f?e.dim("◆ signature"):"",n),""],h=e.color?`${e.fg(s)}${"█".repeat(8)}\x1B[39m `:"",g=t.typing!==void 0?`${e.bold(`${t.typing}▏`)}`:void 0,[b,p,m]=ve(s),$=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 ${b} ${p} ${m}`)}`),d.push(`${h}${e.dim(`oklch ${a.l.toFixed(3)} ${a.c.toFixed(3)} ${a.h.toFixed(0)}°`)}`),d.push("");let E=Math.max(8,Math.min(64,n-12));Yr.forEach((S,k)=>{let N=t.mode==="tune"&&k===t.channel,R=o[S.key],H=`${R.toFixed(S.digits)}${S.wraps?"°":""}`.padStart(6),x=s0(e,SI(o,S,E),o0(R,S.min,S.max,E),N),C=S.key.toUpperCase();d.push(`${N?e.bold(`▸${C}`):e.dim(` ${C}`)} ${x} ${N?e.bold(H):e.dim(H)}`)}),d.push("");let M=n0(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)Qe(S.text,n-2).forEach((k,N)=>{d.push(`${N===0?a0(e,S.ok):" "} ${S.ok===!1?k:e.dim(k)}`)});let w=r-d.length-1;if(w>=3)d.push("",...c0(e,Fn(t.shown()),n).slice(0,w));return d}function RI(e,t,n,r){return[bn(`${e.bold("Specimen")} ${e.dim("what the seeds grow")}`,"",n),"",...c0(e,Fn(t.list),n).slice(0,r-2)]}var OI=[["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 FI(e,t,n){let r=[` ${e.bold("Help")}`,""];for(let[i,s]of OI.filter(([o])=>o!=="Pictures"||t.options.find))Qe(s,n-16).forEach((o,a)=>{r.push(` ${e.bold((a===0?i:"").padEnd(11))} ${o}`)});return r}function TI(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=[bn(` ${e.bold("Take colors from")} ${o}`,e.dim(`${i.length}/${s}`),n),""],u=r-2,c=Math.max(0,Math.min(t.pick-Math.floor(u/2),i.length-u)),l=Math.min(40,Math.max(12,...i.map((f)=>$e(f.name))));if(i.slice(c,c+u).forEach((f,d)=>{let h=c+d===t.pick,g=f.colors,b=e.color?`${e.bg(g.background)} ${[...g.ansi].map(($)=>`${e.fg($)}■`).join("")} ${e.fg(g.foreground)}Aa \x1B[0m`:"",p=h?"▌ ":" ",m=f.name.padEnd(l);a.push(`${p}${h?e.bold(m):m} ${b}`)}),i.length===0)a.push(` ${e.dim(`No palettes match '${t.filter}'`)}`);return a}function HI(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?bn(f,c,n):rt(f,n);o=[...o.slice(0,-2),...o.slice(-1)]}}function xI(e,t,n,r){let i=vI(r);if(t<Jf||n<qf){let g=[i.bold("ttheme palette editor"),`Needs ${Jf}×${qf} — now ${t}×${n}`,i.dim("esc cancels")];return Array.from({length:n},(b,p)=>rt(g[p]??"",t))}let s=e.failing().length,o=s===0?"✓ Passes the gate":`✗ ${s} ${s===1?"miss":"misses"} in the gate`,a=e.pictures>0?i.dim(`▣ ${e.pictures} ${e.pictures===1?"picture":"pictures"} `):"",u=`${e.dirty()?`${i.color?"\x1B[33m●\x1B[39m":"●"} unsaved `:""}${a}${i.dim(o)}`,l=`${i.fg(e.list[2])}◆${i.color?"\x1B[39m":""} ${i.bold(e.options.title)} ${i.dim(`· ${e.options.name}`)}`,f=n-4,d;if(e.overlay==="keys")d=FI(i,e,t);else if(e.overlay==="open")d=TI(i,e,t,f);else{let g=t-vu-2,b=e.mode==="seeds"?NI(i,e,f):II(i,e,f),p=e.mode==="seeds"?RI(i,e,g,f):PI(i,e,g,f);d=Array.from({length:f},(m,$)=>`${rt(b[$]??"",vu)}${i.dim("│")} ${rt(p[$]??"",g)}`)}let h=[bn(l,u,t),""];for(let g=0;g<f;g++)h.push(rt(d[g]??"",t));return h.push("",HI(i,e,t)),h}async function l0(e,t){let n=new Kf(e),{stdin:r,stdout:i}=process,s=i.columns||Jf,o=i.rows||qf,a=[],u=[],c="",l="",f,d=(M)=>i.write(M),h=()=>{if(f=void 0,t.look){let w=n.shown();if(w.join(" ")!==c)c=w.join(" "),t.look(w);return}let M="";if(n.shown().forEach((w,S)=>{if(u[S]!==w&&t.only?.includes(S))M+=yl(S,w),u[S]=w}),M)d(M)},g=()=>{let M=xI(n,s,o,t.color),w="";if(M.forEach((S,k)=>{if(a[k]!==S)w+=`\x1B[${k+1};1H\x1B[0m\x1B[2K${S}`}),a=M,w)d(`\x1B[?2026h${w}\x1B[0m\x1B[?2026l`);if(t.only||t.look)f??=setTimeout(h,33)},b,p,m=!1,$=()=>{d(`\x1B[?1049h\x1B[?25l\x1B[?7l\x1B[?2004h${Ri}`),r.setRawMode(!0),r.resume()},E=(M)=>{if(b&&p)r[M?"on":"off"]("data",b),i[M?"on":"off"]("resize",p)};$();try{return await new Promise((M)=>{let w=async(S)=>{let k=e.find;if(!k)return;m=!0,E(!1),clearTimeout(f),f=void 0;try{n.found(await k(n.edited(),S))}catch(N){n.notice=N instanceof Error?N.message:String(N)}m=!1,$(),E(!0),s=i.columns||s,o=i.rows||o,a=[],u.length=0,c="",g()};p=()=>{s=i.columns||s,o=i.rows||o,a=[],d(Ri),g()},b=(S)=>{l+=S.toString("utf8");let k=fu(l);l=k.pending;for(let R of k.events)if(R.kind==="paste")n.paste(R.text);if(k.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(k.keys)&&n.typing===void 0)n.paste(k.keys);else for(let R of gu(k.keys))if(n.press(R),n.result||n.wants)break;if(n.result){M(n.result==="saved"?n.edited():void 0);return}let N=n.wants;if(N&&!m){n.wants=void 0,w(N.start);return}g()},E(!0),g()})}finally{clearTimeout(f),E(!1),r.setRawMode(!1),r.pause(),d("\x1B[?2004l\x1B[?7h\x1B[?25h\x1B[?1049l")}}import{spawn as DI}from"node:child_process";import{createHash as F0}from"node:crypto";import{existsSync as qi,mkdirSync as eN,mkdtempSync as tN,readFileSync as T0,rmSync as yo,statSync as nN}from"node:fs";import{homedir as rN,tmpdir as iN}from"node:os";import{dirname as sN,join as Qt}from"node:path";import{pathToFileURL as k0}from"node:url";var AI=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),LI=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),CI=0.04,_I=0.1,GI=0.05,WI=4096;function UI(e){return new Set(e.cutouts.split(/\s+/).map((t)=>t.replace(/^~/,"")).filter(Boolean))}function jI(e,t,n,r=0){let{site:i,post:s}=e,o=new Set(s.tags),a=[...UI(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)+([...AI].some((l)=>o.has(l))?-3:0)+([...LI].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 Mu(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:jI(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 d0(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 zf(e){let t=e/255;return t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}function f0(e,t,n){let[r,i,s]=[zf(e),zf(t),zf(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 h0(e,t){let n=t.map((o)=>f0(...ve(o))).filter(([,o,a])=>Math.hypot(o,a)>=CI);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(e.width*e.height/WI))),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]=f0(e.data[u],e.data[u+1],e.data[u+2]);n.forEach(([d,h,g],b)=>{if(Math.hypot(c-d,l-h,f-g)<_I)i[b]=i[b]+1})}if(s===0)return 0;return i.reduce((o,a)=>o+Math.min(1,a/s/GI),0)/n.length}import{mkdirSync as qI,readFileSync as Yf,writeFileSync as w0}from"node:fs";import{dirname as zI}from"node:path";import{isMainThread as VI,parentPort as $0,Worker as YI}from"node:worker_threads";var KI=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,BI=[[/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 Vf(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 g0(e,t){let n=KI.exec(t.source)?.[1]?.toLowerCase();return[`post:${e.key}:${t.id}`,...t.md5?[`md5:${t.md5}`]:[],...n&&n!==t.md5?[`md5:${n}`]:[],...BI.flatMap(([r,i])=>{let s=r.exec(t.source)?.[1];return s?[`post:${i}:${Number(s)}`]:[]}),...t.family?[`family:${e.key}:${t.family}`]:[]]}function m0(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 p0(e){let r=[];for(let s=0;s<8;s++){let o=Math.floor(s*e.height/8),a=Math.max(o+1,Math.floor((s+1)*e.height/8));for(let u=0;u<9;u++){let c=Math.floor(u*e.width/9),l=Math.max(c+1,Math.floor((u+1)*e.width/9)),f=0;for(let d=o;d<a;d++)for(let h=c;h<l;h++){let g=(d*e.width+h)*4,b=e.data[g+3]/255,p=0.299*e.data[g]+0.587*e.data[g+1]+0.114*e.data[g+2];f+=p*b+255*(1-b)}r.push(f/((l-c)*(a-o)))}}let i=0n;for(let s=0;s<8;s++)for(let o=0;o<8;o++)i=i<<1n|(r[s*9+o]>r[s*9+o+1]?1n:0n);return i.toString(16).padStart(16,"0")}function JI(e,t){let n=BigInt(`0x${e}`)^BigInt(`0x${t}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function b0(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&&JI(e.hash,t.hash)<=2}var QI={thumb:"tile",band:"band",match:"tile",show:"view",backdrop:"view",redraw:"view"},Su;async function ZI(e){if(e.job==="redraw")return Da(e.home,e.name,e.key,e.paint,e.blur,e.aligns,e.user);if(e.job==="show"){if(Su?.from!==e.from){let o=Kn(new Uint8Array(Yf(e.from)),$t);Su={from:e.from,clear:kn(o),inked:Zc(o)}}let{image:r,fill:i,opacity:s}=Cm(Su.inked,e.colors,e.tone,e.width,e.height,e.blur,e.tune,e.coloring);return qI(zI(e.to),{recursive:!0}),w0(e.to,Bn(r)),{clear:Su.clear,fill:i,opacity:s}}let t=Kn(new Uint8Array(Yf(e.from)),$t);if(e.job==="backdrop"){pa(e.home,e.colors,e.tone,t,{...e.origin,bytes:new Uint8Array(Yf(e.source)),cut:e.from!==e.source},e,e.blur,e.coloring);let r=e.tune&&_t(e.home,e.colors.name).find((i)=>i.key===ft(e.origin));if(e.tune&&r)Fs(Se(e.home),r,e.tune,e.aligns??!0,e.user??e.home);return 0}if(e.job==="match")return{match:h0(t,e.colors),hash:p0(t)};if(e.job==="thumb")return K(e.to,Bn(Ng(t,e.width,e.height))),0;let n=t.data.subarray(e.y*t.width*4,(e.y+e.height)*t.width*4);return w0(e.to,Bn({width:t.width,height:e.height,data:n})),0}function XI(e){e.on("message",async(t)=>{try{e.postMessage({id:t.id,value:await ZI(t)})}catch(n){e.postMessage({id:t.id,error:n instanceof Error?n.message:String(n)})}})}class Qf{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 YI(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 Zf{lines=new Map;run(e){let t=QI[e.job],n=this.lines.get(t);if(!n)n=new Qf,this.lines.set(t,n);return n.send(e)}close(){for(let e of this.lines.values())e.close();this.lines.clear()}}class Xf{lines;constructor(e){this.lines=Array.from({length:Math.max(1,e)},()=>new Qf)}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(!VI&&$0)XI($0);var Qr=[{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:hi,multi:{read:Or}},{name:"TTHEME_FIND_BLOCK",label:"Block",about:"Posts tagged with nudity or underwear are left out — space unticks one",choices:Pr,multi:{read:mi,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"Posts",about:"Every post of the character, or only the transparent cutouts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"Solo",about:"When on, only the posts known to show the character alone — checked as posts arrive, so the counts below leave it out",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"Order",about:"How posts are ranked: fit, by how well each makes a backdrop; newest; or score",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"Sets",about:"One picture posted over and over, or held by another site too: fold it into one tile, or show each",choices:["fold","show"]},...xi()?[{name:"TTHEME_FIND_REMOVE_BG",label:"Remove bg",about:"Cut the character out of an opaque picture you try on, with macOS Vision",choices:["on","off"]}]:[],{name:"TTHEME_FIND_MIN_SCORE",label:"Min score",about:"Posts scored at least this — danbooru, konachan and yande.re; zerochan keeps no score. ←→ steps, or type any number",choices:Vg,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:Yg,entry:"number",advanced:!0},{name:"TTHEME_FIND_SITES",label:"Sites",about:"The sites the all tab mixes — each keeps its own tab. Space ticks one, and one stays ticked",choices:X.map((e)=>e.name),multi:{read:$s},advanced:!0},{name:"TTHEME_FIND_HIDE",label:"Hide",about:"Comics, monochrome, sketches or chibi, told by tag in every site's spelling — checked as posts arrive",choices:Hc,multi:{read:Xo,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 y0(e,t){if(e.multi)return e.multi.read(t).join(" ")||e.multi.none;if(e.entry==="number")return/^\d+$/.test(t??"")&&Number(t)>0?String(Number(t)):"off";if(e.entry==="text")return ks(t).join(" ");return e.choices.find((n)=>n===t)??e.choices[0]}var oN=["fit","newest","score"];function Df(e){return oN.find((t)=>t===e)??"fit"}var aN={left:-1,right:1,"shift-left":-10,"shift-right":10};function uN(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 ed=uN(process.env.TTHEME_BG_MARGIN);function cN(e,t,n){if(t<0){if(e!=="fill")return Math.max(I0,e+t);if(!n)return e;return Math.max(I0,Math.max(100,n)+t+1)}return e==="fill"||e+t>n?"fill":e+t}function H0(e,t){return e.size===t.size&&e.at===t.at&&e.opacity===t.opacity}function lN(e,t){if(H0(e,t))return;return{...e.size!=="fill"?{size:e.size}:{},...e.at!==t.at?{position:kt[e.at-1]}:{},...e.opacity!==t.opacity?{opacity:e.opacity}:{}}}function fN(e){return e.length>=2&&!/^\d+$/.test(e)&&!e.includes("://")&&!/^[\w.]+:\d+$/.test(e)}var E0=12,dN=4,hN=150,gN=300,v0=12,mN=2,pN=150,bN=30,wN=4000,$N=8000,M0=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,kN=process.platform==="win32"?"alt+v":"ctrl+v",S0=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",yN=1280,EN=16,vN=kt.indexOf("top-right")+1,I0=20,zi=2147483645,Eo=2147483646,N0=-1073741827,MN=-1073741828,P0=2,SN=80,IN=16,NN=0.4,PN=3221225472,RN=256,ON=3,FN=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 vo(e){if(!(e instanceof Error))return String(e);if(e instanceof AggregateError&&e.errors[0])return vo(e.errors[0]);if(e.cause)return vo(e.cause);let t=e.code;if(typeof t==="string")return t;let n=(e.message||e.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function td(e,t){return`${e}: ${vo(t)}`}function R0(e){return e.width*e.height}function O0(e,t){return`${e}-${F0("sha1").update(t).digest("hex").slice(0,8)}`}function TN(e){let t=e.lastIndexOf("\x1B");return t!==-1&&/^\[?[0-9;]*$/.test(e.slice(t+1))}function HN(e,t){try{return JSON.parse(T0(Qt(rn(e),t),"utf8"))}catch{return{}}}function xN(e,t,n){K(Qt(rn(e),t),`${JSON.stringify(n)}
507
+ `)}class nd{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(Qr.map((e)=>[e.name,y0(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 Zf;sent=new Map;placed=new Map;screen=[];ticking;gliding;showing;thumbless=new Set;bands=Op(process.env);files=Fp(process.env);moves=Hp(process.env);layers=Tp(process.env);bandFiles=new Map;nextBand=PN;current;fetch;settle;partial;suggestTimer;suggesting;countTimer;counting;input="";typed="";grabber=new Hf((e)=>this.write(e),(e)=>void this.got(e));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;scratch=tN(Qt(iN(),"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=yi(n,n.signatureSlots),this.blurring=Cr(e),this.coloring=Ra(e);let s={size:"fill",at:vN,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:Df(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Or(this.setting("TTHEME_FIND_RATING")),block:mi(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",narrow:this.narrowed(),enabled:$s(this.setting("TTHEME_FIND_SITES")),hide:Xo(this.setting("TTHEME_FIND_HIDE")),hideTags:ks(this.setting("TTHEME_FIND_HIDE_TAGS")),advanced:!1,settings:Qr.map((o)=>({label:o.label,choices:[...o.choices],value:this.setting(o.name),default:y0(o,Us(o.name)),multi:o.multi&&{none:o.multi.none},about:o.about,entry:o.entry,advanced:o.advanced,cursor:0})),colors:{cursor:n.cursor,selection:n.selection,background:n.background,foreground:n.foreground,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",stage:"fetch",sites:[],focus:0,top:0,scroll:0,beat:0,mode:"grid",help:!1,scene:Math.max(0,Gt.findIndex((o)=>o.name.toLowerCase()===process.env.TTHEME_SCENE)),details:!1,tune:{...s},untuned:s,editing:r===""?"":void 0},this.board=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??dN}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 Ac(this.setting("TTHEME_FIND_MIN_SCORE"),this.setting("TTHEME_FIND_MIN_SIZE"),this.setting("TTHEME_FIND_PNG"))}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(e,t,n){return Qt(rn(e),"orig",`${t}.${n}`)}previewPath(e){let{url:t}=ea(e.site,e.post);return Qt(rn(e.site),"thumb",`${O0(e.post.id,t)}.${Yn(t)}`)}tileOf(e,t){let{site:n,post:r}=e,i=Ct(n,r.id),s=nn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:s.width,height:s.height,reduced:s!==r,page:n===Br?"":n.pageUrl(r.id),artist:n===Br?yw(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${Ri}`);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\\${Ri}`),e.setRawMode(!1),e.pause(),this.saveKept(),this.renders.close(),yo(this.scratch,{recursive:!0,force:!0}),um(),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(Gw)})}onData=(e)=>{this.input+=e.toString("utf8");for(let n=_f(this.input);n;n=_f(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let t=fu(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),TN(this.typed)){this.partial=setTimeout(this.flushKeys,bN);return}this.flushKeys()};flushKeys=()=>{let e=gu(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!Do(t,this.site??X[0]);return Ui(t).length>0}async got(e){if(e.kind==="error"){this.notice(e.message);return}if(e.kind==="text"){if(e.text.trim()===""){this.notice(`No picture on the clipboard — ${S0}`);return}this.pasted(e.text);return}await this.bring(()=>cu(e.bytes,e.source))}notice(e,t=wN){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 Iw()}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 · ${kN} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{e.hint=void 0,this.draw()},$N),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 Sw(Qt(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`Could not read the clipboard: ${vo(r)}`);return}if(clearTimeout(this.peekTimer),e.hint=void 0,"image"in t){await this.bring(async(r)=>({...await Ff(t.image,r),source:"clipboard"}));return}let n=t.text.trim();if(!n){this.notice(`No picture on the clipboard — ${S0}`);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=Do(t,this.site??X[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Ui(t).sort((i,s)=>Number(!M0.test(i))-Number(!M0.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)=>Ff(n,i),r.length)}async bring(e,t=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="Reading the picture…",this.draw();let i;try{i=await e(AbortSignal.any([r.signal,this.signal]))}catch(d){if(!r.signal.aborted)n.note=void 0,this.notice(vo(d),8000);return}if(r.signal.aborted)return;n.note=t>0?`The first picture of ${t+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let s=vw(i.bytes);Ew(s,i.source);let o=this.origPath(Br,s,i.ext);K(o,i.bytes);let a=k0(o).href,u={id:s,file:a,width:i.width,height:i.height,ext:i.ext,preview:a,owner:"",score:0,rating:"s",md5:F0("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],named:{artist:[],character:[],copyright:[]},solo:void 0,family:0,smaller:[]},c={site:Br,post:u},l=this.previewPath(c);K(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(Ct(t.site,t.post.id),t),e.groups=[{posts:[t],open:!1}],e.checked=1,e.total=1,this.thumbQueue.push(t),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let e=this.sites.reduce((r,i)=>Vn(i)>Vn(r)?i:r),t=Math.ceil((Vn(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<qr.cols||this.rows<qr.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}=zr(this.cols,this.rows),s={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-t.focus,end:t.tiles.length}[e];if(s!==void 0){this.focus(t.focus+s);return}if(e==="enter"&&t.tiles[t.focus]){t.mode="try",t.error=void 0,this.select();return}if(e==="v"){this.fromClipboard();return}if(e==="c"){t.preset=t.preset==="cutouts"?"all":"cutouts",this.turn();return}if(e==="tab"||e==="shift-tab"){let o=X.length+1;this.tab=(this.tab+(e==="tab"?1:o-1))%o,this.syncSite(),this.turn();return}if(e==="/"){t.editing="",this.draw();return}if(e===" "){this.unfold();return}if(e==="o"){this.openPage();return}if(e==="s"){t.panel=0,t.advanced=!1,this.recount(),this.draw();return}if(e==="esc")this.finish(2)}panelKey(e){let t=this.view,n=t.panel??0,r=t.settings[n];if(t.typing!==void 0&&r){this.typeKey(r,e);return}let i=mo(t);if(e==="up"||e==="down"){let s=i.indexOf(n)+(e==="up"?-1:1);t.panel=i[(s+i.length)%i.length]??n,this.draw();return}if(e==="a"||e==="enter"&&n===t.settings.length){t.advanced=!t.advanced,t.panel=mo(t)[0]??0,this.draw();return}if(r?.entry&&(e==="enter"||r.entry==="number"&&/^[0-9]$/.test(e))){t.typing=e==="enter"?r.entry==="text"?r.value:"":e,this.draw();return}if((e==="left"||e==="right")&&r&&r.entry!=="text"){let s=e==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+s+r.choices.length)%r.choices.length;else r.value=Vw(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(Qr[o]?.name??"")}),t.panel=void 0,t.advanced=!1,this.quietCount(),this.draw();return}if(e==="enter"||e==="s"||e==="alt-c")t.panel=void 0,t.advanced=!1,this.quietCount(),this.adopt()}typeKey(e,t){let n=this.view,r=n.typing??"";if(t==="esc"){n.typing=void 0,this.draw();return}if(t==="enter"||t==="up"||t==="down"){if(e.value=e.entry==="number"?Number(r)>0?String(Number(r)):"off":ks(r).join(" "),n.typing=void 0,this.recount(),t==="enter"){this.draw();return}this.panelKey(t);return}if(t==="backspace"){n.typing=r.slice(0,-1),this.draw();return}if(e.entry==="number"?/^[0-9]$/.test(t)&&r.length<Wf:/^[\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),gN)}pending(){let e=(t)=>this.view.settings[Qr.findIndex((n)=>n.name===t)]?.value??this.setting(t);return{tag:this.view.tag,preset:e("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Df(e("TTHEME_FIND_ORDER")),rating:Or(e("TTHEME_FIND_RATING")),narrow:Ac(e("TTHEME_FIND_MIN_SCORE"),e("TTHEME_FIND_MIN_SIZE"),e("TTHEME_FIND_PNG")),enabled:$s(e("TTHEME_FIND_SITES"))}}async countPending(e){let t=this.pending(),n=this.site?[this.site]:X.filter((s)=>t.enabled.includes(s.name)),r=AbortSignal.any([this.signal,e.signal]),i=await Promise.all(n.map(async(s)=>{let o=this.query(s,t);if(!o)return{site:s.name,count:0};if(s.counts&&!s.counts(o.tags))return{site:s.name};try{let a=await 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=Qr.map((r)=>this.setting(r.name));e.settings.forEach((r,i)=>{let s=Qr[i];if(s)this.values.set(s.name,r.value)});let n=Qr.filter((r,i)=>this.setting(r.name)!==t[i]);if(n.length===0){this.draw();return}this.save(n),e.rating=Or(this.setting("TTHEME_FIND_RATING")),e.block=mi(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=Df(this.setting("TTHEME_FIND_ORDER")),e.solo=this.setting("TTHEME_FIND_SOLO")==="on",e.narrow=this.narrowed(),e.enabled=$s(this.setting("TTHEME_FIND_SITES")),e.hide=Xo(this.setting("TTHEME_FIND_HIDE")),e.hideTags=ks(this.setting("TTHEME_FIND_HIDE_TAGS")),this.boards.clear(),this.current=void 0,e.shown=void 0,e.mode="grid",this.search()}save(e){this.store(e.map((t)=>[t.name,this.setting(t.name)]))}store(e){let t=Qt(this.home,"ttheme","config.zsh");try{let n=qi(t)?T0(t,"utf8"):"";return K(t,e.reduce((r,[i,s])=>_p(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(!fN(t)){e.suggest=void 0;return}let n=[...new Map(pp(this.catalog.palettes,this.entry,t).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,ON);e.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await lm(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,FN),e.pick=e.pick!==void 0&&e.pick<n.length?e.pick:void 0,this.draw()}}catch{}},hN)}async commit(e){let t=Do(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 ys(e,t,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${e.name} has no post ${t}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:e,post:i})}catch(i){this.fail(n,i,e)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let e=this.boards.get(this.boardKey);if(!e){await this.search();return}this.gen++,this.board=e,this.view.error=e.error,this.show(),this.draw(),await this.pump()}unfold(){let e=this.view,t=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(e.focus<t+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=t;for(let i of n.posts)if(!this.thumbPath.has(Ct(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.glide(),this.draw();return}t+=r}}openPage(){let e=this.view.tiles[this.view.focus],t=e&&this.posts.get(e.key);if(!t)return;let n=process.platform==="darwin"?"open":"xdg-open";try{DI(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=aN[e];if(i!==void 0){if(n.field===0)r.size=cN(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=om(t,n),s=new Set([...r.artist,...r.character,...r.copyright]),o=Es(n.source),a=/^https?:\/\//i.test(o)?o:t===Br&&o.startsWith("/")?k0(o).href:void 0;return{page:t===Br?"":t.pageUrl(n.id),source:o,...a?{link:a}:{},artists:r.artist,characters:r.character,series:r.copyright,tags:n.tags.filter((u)=>!s.has(u)),...i?{rating:i}:{},...n.posted?{posted:n.posted}:{},ext:(nn(n)??n).ext,uploader:n.owner}}focus(e){let t=this.view;if(t.tiles.length===0)return;let n=Math.max(0,Math.min(t.tiles.length-1,e));if(n===t.focus)return;if(t.focus=n,this.board.focus=n,this.scroll(),this.glide(),this.pump(),t.mode==="try")this.select();this.draw()}scroll(){let e=this.view,{perRow:t,rowsVis:n}=zr(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=zr(this.cols,this.rows).height,t=()=>{let n=this.view,r=n.top*Je.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)*NN)),this.draw(),this.gliding=setTimeout(t,IN)};t()}snap(){clearTimeout(this.gliding),this.gliding=void 0,this.view.scroll=this.view.top*Je.height}prebake(){let e=this.view;for(let t of Uf({...e,scroll:e.top*Je.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?bp(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(_c([...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=_c(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=td(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,td(t.name,n)].filter(Boolean).join(" · ")}wants(){let{perRow:e,rowsVis:t}=zr(this.cols,this.rows);return this.view.tiles.length<(this.board.top+t+P0)*e}need(){let{perRow:e,rowsVis:t}=zr(this.cols,this.rows);return(t+P0)*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=cm(e,t,n,this.signal).then((s)=>this.borrow(e,s)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(e,t){let n=e===Lt?[]:t.filter((r)=>r.md5!=="");if(n.length>0)try{oa(n,await aa(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<zn;let c=e.last.get(a);for(let l of u){let f=c&&m0(c.post,l)?c.set:`set:${a.site.key}:${l.id}`;c={post:l,set:f};let d=Ct(a.site,l.id);if(e.seen.has(d))continue;e.seen.add(d);let h={site:a.site,post:l};if(this.eligible(h))e.kin.set(h,[f,...g0(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?d0(i):i;else{let a=Mu(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=[...Mu(u,this.frame(),this.matched),...a.slice(u.length)]}e.stage="check",this.staged(e);for(let a of o)e.roundOf.set(a,s);e.queue.push(...o),this.ahead(e)}ahead(e){if(this.aheading||this.view.order!=="fit"||!this.live(e))return;let t=e.queue.slice(0,this.need()).filter((n)=>!this.looking.has(Ct(n.site,n.post.id)));if(t.length===0)return;this.aheading=!0,this.looks(t).then(()=>{this.aheading=!1;for(let n of new Set(t.map((r)=>e.roundOf.get(r)??0)))this.resort(e,n);this.ahead(e)})}resort(e,t){let n=e.queue.flatMap((i,s)=>e.roundOf.get(i)===t?[s]:[]),r=Mu(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=Vf(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++,R0(r.post)<=R0(s.post))continue;for(let a of[...i,...Vf(s.post)])e.same.set(a,r);let o=n.indexOf(s);if(o>=0){n[o]=r;continue}this.replace(e,s,r)}return n}replace(e,t,n){e.roundOf.set(n,e.roundOf.get(t)??0);let r=e.queue.indexOf(t);if(r>=0){e.queue[r]=n;return}for(let i of e.groups){let s=i.posts.indexOf(t);if(s>=0){i.posts[s]=n,this.posts.set(Ct(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(e,t){let n=0;await Promise.all(Array.from({length:v0},async()=>{while(n<e.length)await this.look(e[n++]),t?.()}))}look(e){let t=Ct(e.site,e.post.id),n=this.looking.get(t);if(!n)n=(async()=>{let r=this.previewPath(e),i=ea(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<E0&&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<E0&&t.sources.some((o)=>!o.done)&&this.wants()){let o=this.round(t).then(()=>{if(r===o)r=void 0});o.catch(()=>{}),r=o}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let s=await i.passed;if(e!==this.gen)return;if(t.checked++,s)this.admit(i.pick);this.show(),this.draw()}if(e===this.gen)t.searching=!1,this.show(),this.draw()}catch(i){this.fail(e,i)}finally{if(this.saveKept(),this.pumping===e)this.pumping=0}}eligible({site:e,post:t}){let n=nn(t);if(!na(e,t,this.view.rating)||ta(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"||sm(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=HN(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 ua(e,t,this.signal),s=pi(e,t),o=(i===void 0?await fm(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)xN(r,n,this.keep(r,n))}this.unsaved.clear()}admit(e){let{site:t,post:n}=e,r=this.board,i=Ct(t,n.id);this.posts.set(i,e);let s=r.kin.get(e)??[],o=this.looked.get(i),a=o&&{hash:o.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,s,a):void 0;if(u){if(u.posts.push(e),this.register(r,u,s,a),u.open)this.thumbQueue.push(e),this.thumbs();return}let c={posts:[e],open:!1};r.groups.push(c),this.register(r,c,s,a),this.thumbQueue.push(e),this.thumbs()}kindred(e,t,n){for(let r of t){let i=e.kindred.get(r);if(i)return i}return n&&e.shapes.find((r)=>b0(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(!sa(n,r))return Promise.resolve();let i=Ct(n,r.id),s=this.crediting.get(i);if(!s)s=this.credits(e,t).finally(()=>this.crediting.delete(i)),this.crediting.set(i,s);return s}async credits({site:e,post:t},n){let r=this.keep(e,"credits.json"),i=r[t.id];if(!i){try{i=await ia(e,t.id,n)}catch{return}if(!i?.owner)return;r[t.id]=i,this.unsaved.add(`${e.key}/credits.json`)}vs(t,i),this.show(),this.inform(),this.draw()}async mateOwners(e){let t=this.owners.get(e.key);if(t)return t;let n=Jm(this.home),r=this.keep(e,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let c=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&c?.site===e.key?[{name:u.name,id:c.id}]:[]}),s=await Promise.all(i.map(async(u)=>{let c=r[u.id];if(c!==void 0)return{...u,owner:c};try{return{...u,owner:(await ys(e,u.id,this.signal))?.owner??""}}catch{return}})),o=new Map;for(let u of s)if(u)r[u.id]=u.owner,o.set(u.name,u.owner);this.unsaved.add(`${e.key}/owners.json`);let a=am(o);return this.owners.set(e.key,a),a}async cached(e,t,n,r){if(qi(t))return nN(t).size;let i=this.inflight.get(t);if(i)return i;let s=(async()=>{let o=await ca(e,n,this.signal,r);return K(t,o),o.length})();this.inflight.set(t,s);try{return await s}finally{this.inflight.delete(t)}}thumbs(){while(!this.signal.aborted&&this.thumbing<v0&&this.thumbQueue.length>0){let e=this.thumbQueue.shift();this.thumbing++,this.thumb(e).catch(()=>{this.thumbless.add(Ct(e.site,e.post.id)),this.show(),this.draw()}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(e){let{site:t,post:n}=e,r=Je.cols*this.cell.w,i=Je.rows*this.cell.h,s=ea(t,n),o=Qt(rn(t),"tile",`${O0(n.id,s.url)}-${r}x${i}.png`);if(!qi(o)){let a=this.previewPath(e);if(await this.cached(s.site,a,s.url),this.signal.aborted)return;await this.renders.run({job:"thumb",from:a,to:o,width:r,height:i})}this.thumbPath.set(Ct(t,n.id),o),this.show(),this.draw()}select(){let e=this.view,t=e.tiles[e.focus];if(this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,this.inform(),!t)return;if(this.current?.key===t.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(t),pN),this.draw()}async load(e){let t=this.view,n=this.posts.get(e.key);if(!n)return;let r=new AbortController;if(this.fetch=r,this.credit(n,r.signal),!nn(n.post))return;let{site:i}=n,s=this.board;try{await ua(i,n.post,r.signal);let o=nn(n.post),a=this.origPath(i,e.id,o.ext);if(!qi(a))t.fetching={id:e.key,got:0,size:0},this.draw();let u=pi(i,n.post,o),c=await this.cached(u.site,a,u.url,(d,h)=>{if(t.fetching?.id===e.key)t.fetching={id:e.key,got:d,size:h},this.draw()});if(r.signal.aborted)return;if(t.fetching=void 0,s!==this.board)return;let l={site:i,id:e.id,key:e.key,path:a,ext:o.ext,size:c,using:"plain",failed:!1};t.preparing=e.key,this.flush();let f=await this.render(l,"plain");if(r.signal.aborted||s!==this.board)return;if(f.clear===0&&xi()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(t.preparing=void 0,t.cutting=e.key,this.flush(),l.cut=await this.cutOut(i,e.id,a,r.signal),r.signal.aborted||s!==this.board)return;if(t.cutting=void 0,l.cut){t.preparing=e.key,this.flush();let d=await this.render(l,"cut").catch(()=>{return});if(r.signal.aborted||s!==this.board)return;if(d&&Za(d.clear))l.using="cut";else yo(l.cut,{force:!0}),l.cut=void 0,l.failed=!0}else l.failed=!0}if(this.current=l,t.tiles[t.focus]?.key===e.key)await this.present();this.preload()}catch(o){if(!r.signal.aborted&&!this.signal.aborted)t.error=td(i.name,o)}finally{if(t.fetching?.id===e.key)t.fetching=void 0;if(t.preparing===e.key)t.preparing=void 0;if(t.cutting===e.key)t.cutting=void 0;this.draw()}}async cutOut(e,t,n,r){let i=Qt(rn(e),"cut",`${t}.png`);if(qi(i))return i;try{return eN(sN(i),{recursive:!0}),await Zs(n,i,r),i}catch{yo(i,{force:!0});return}}swap(){let e=this.current;if(!e?.cut||this.view.shown?.id!==e.key)return;e.using=e.using==="cut"?"plain":"cut",this.reveal()}preload(){let e=this.view;if(e.mode!=="try")return;for(let t of[e.focus+this.direction,e.focus-this.direction]){let n=e.tiles[t],r=n&&this.posts.get(n.key);if(r)this.credit(r,this.signal);if(this.prefetching>=mN||!r||!nn(r.post))continue;let{site:i,post:s}=r;this.prefetching++,ua(i,s,this.signal).then(async()=>{let o=nn(s),a=this.origPath(i,s.id,o.ext),u=pi(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,yN),s=Math.max(1,Math.round(r*i/n)),o={...this.view.tune},a=!H0(o,this.view.untuned),u=o.opacity!==this.view.untuned.opacity,c=a?`-${o.size}-${o.at}${u?`-${Math.round(o.opacity*100)}`:""}`:"",l=Qt(this.scratch,`${e.site.key}-${e.id}${t==="cut"?"c":""}-${i}x${s}${c}.png`),f=`${e.site.key}:${e.id}:${t}:${i}x${s}`,d=this.clarity.get(f);if(d&&qi(l))return e.fill=d.fill,{clear:d.clear,path:l,opacity:d.opacity,touched:u};let h=await this.renders.run({job:"show",from:t==="cut"?e.cut:e.path,to:l,width:i,height:s,colors:this.entry,tone:this.tone,blur:this.blurring*i/Yc(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>EN){let t=this.tunedFiles.findIndex((n)=>n!==this.view.shown?.path&&n!==e);if(t===-1)return;yo(this.tunedFiles.splice(t,1)[0],{force:!0})}}async present(){let e=this.current;if(!e)return;let t=e.using,n=this.view.tune.opacity,{clear:r,path:i,opacity:s,touched:o}=await this.render(e,t);if(this.current!==e||e.using!==t)return;if(!o&&this.view.tune.opacity===n)this.view.untuned.opacity=s,this.view.tune.opacity=s;if(this.view.tuning&&e.fill)this.view.tuning.fill=e.fill;this.view.shown={id:e.key,clear:r,bytes:e.size,path:i,cut:e.cut?t==="cut"?"on":"off":e.failed?"failed":"none"}}reveal(){let e=this.view;if(this.presenting){this.again=!0;return}this.presenting=!0,e.preparing=this.current?.key,this.flush(),this.present().catch((t)=>{e.error=t instanceof Error?t.message:String(t)}).finally(()=>{if(this.presenting=!1,this.again){this.again=!1,this.reveal();return}if(e.preparing===this.current?.key)e.preparing=void 0;this.draw()})}async install(){let e=this.view,t=e.tiles[e.focus],n=this.current;if(!t||n?.key!==t.key||e.preparing!==void 0||e.shown?.id!==t.key)return;e.installing=t.key,e.error=void 0,this.flush();let r=lN(e.tune,e.untuned),i=this.posts.get(n.key)?.post;try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`,artist:i?.named.artist??[],source:Es(i?.source??"")},width:this.cols*this.cell.w,height:this.rows*this.cell.h,blur:this.blurring,coloring:this.coloring,...r?{tune:r,aligns:Ur(ne(this.home).terminals),user:rN()}:{}}),this.keep(n.site,"owners.json")[n.id]=i?.owner??"",this.unsaved.add(`${n.site.key}/owners.json`),Nt(this.home);let{size:s,at:o,opacity:a}=e.tune,u=r?` · ${s==="fill"?"fill":`${s}%`} · ${kt[o-1]} · ${a.toFixed(2)}`:"",c=i?.named.artist.length?`${i.named.artist.join(", ")} · `:"";e.saved={text:`Background · ${this.entry.name} ← ${c}${n.site.name} ${n.id}${u}`,key:t.key},e.installed.push(t.key),this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid"}catch(s){e.error=s instanceof Error?s.message:String(s)}e.installing=void 0,this.draw()}draw(){if(this.dirty||this.signal.aborted)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){if(this.signal.aborted)return;let e=Uf(this.view,this.cols,this.rows);this.view.loaderFrom=e.loader?this.view.loaderFrom??this.view.beat:void 0;let t="";e.lines.forEach((i,s)=>{if(this.screen[s]!==i)t+=`\x1B[${s+1};1H\x1B[K${i}`,this.screen[s]=i});let n=new Set;for(let i of e.images){let s=this.bands?this.banded(i):i;if(!s)continue;if(n.add(s.id),this.sent.get(s.id)!==s.path){let a=Ww(s,this.files);if(a===void 0)continue;t+=a,this.sent.set(s.id,s.path),this.placed.delete(s.id)}let o=`${s.row};${s.col};${s.cols};${s.rows};${s.crop};${s.z}`;if(this.placed.get(s.id)!==o){if(!this.moves&&this.placed.has(s.id))t+=Gf(s.id);t+=Uw(s,this.cell),this.placed.set(s.id,o)}}for(let i of this.sent.keys())if(!n.has(i))t+=jw(i),this.sent.delete(i),this.placed.delete(i);t+=this.cover();let r=this.view.mode==="grid"&&this.view.editing!==void 0?this.caret():"";if(t||r)this.write(`\x1B[?2026h${t}${r}\x1B[?2026l`);this.pace(e.tick)}cover(){let e=`${this.cols};${this.rows}`;if(!this.layers||this.covered===e)return"";let t="";if(!this.covered){let n=Buffer.from(ve(this.entry.background)).toString("base64");if(t+=`\x1B_Ga=t,f=24,s=1,v=1,i=${zi},q=2;${n}\x1B\\`,ed)t+=`\x1B_Ga=t,f=32,s=1,v=1,i=${Eo},q=2;AAAAAA==\x1B\\\x1B[H\x1B_Ga=p,i=${Eo},p=${Eo},c=1,r=1,C=1,z=${MN},q=2\x1B\\`}else if(!this.moves)t+=Gf(zi);if(this.covered=e,ed){let{x:n,y:r}=ed;return`${t}\x1B_Ga=p,i=${zi},p=${zi},P=${Eo},Q=${Eo},H=${-n},V=${-r},c=${this.cols+2*n},r=${this.rows+2*r},C=1,z=${N0},q=2\x1B\\`}return`${t}\x1B[H\x1B_Ga=p,i=${zi},p=${zi},c=${this.cols},r=${this.rows},C=1,z=${N0},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()},SN);else if(this.ticking)clearInterval(this.ticking),this.ticking=void 0}banded(e){if(e.crop===void 0)return e;let t=this.band(e.path,e.crop,e.rows,!this.gliding);return t?.ready?{...e,id:t.id,path:t.path,crop:void 0}:void 0}band(e,t,n,r=!0){let i=`${e}|${t}|${n}`,s=this.bandFiles.get(i);if(s||!r)return s;let o=this.nextBand++,a={id:o,path:Qt(this.scratch,`band-${o}.png`),ready:!1};return this.bandFiles.set(i,a),this.renders.run({job:"band",from:e,to:a.path,y:t*this.cell.h,height:n*this.cell.h}).then(()=>{a.ready=!0,this.draw()}).catch(()=>{}),this.trimBands(),a}trimBands(){for(let[e,t]of this.bandFiles){if(this.bandFiles.size<=RN)return;if(t.ready&&!this.sent.has(t.id))this.bandFiles.delete(e),yo(t.path,{force:!0})}}}async function x0(e,t,n){let r=new nd(e,ln(e),t,t.booru??"",n);return await r.run(),{saved:r.saved,installs:r.installs}}async function A0(e){let t=ue(),n=ln(t),r=Ar(n.palettes,e);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new nd(t,n,r,r.booru??""),s=await i.run();if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
508
+ `),0;return s}import{existsSync as Pu,readdirSync as AN,readFileSync as rd,rmSync as L0,statSync as C0}from"node:fs";import{homedir as LN}from"node:os";import{join as Mo}from"node:path";var CN=150,_N=260;function Nu(e){return e?.includes(`path = "${_("")}`)===!0}function GN(e){try{return ne(e).terminals.includes("warp")}catch{return!1}}function WN(e,t){let n=_(t);if(!Pu(e))return;return AN(e).filter((i)=>i.startsWith(`${n}.`)&&/^[0-9a-f]{8}\.yaml$/.test(i.slice(n.length+1))).map((i)=>({file:i,at:C0(Mo(e,i)).mtimeMs})).sort((i,s)=>s.at-i.at)[0]?.file??(Pu(Mo(e,`${n}.yaml`))?`${n}.yaml`:void 0)}function kr(e,t,n,r=LN()){if(!t||gt(e)||e.TMUX||Mt(e)!=="warp")return;let i=mr(r,n);if(!Pu(i)||!GN(n))return;let s=Gr(r),o=Ua(n),a=[],u,c,l=(g)=>{let b=rd(i,"utf8"),p=pr(b);if(p===g)return;if(Nu(g)&&!Nu(p)&&!Pu(o))K(o,p??"");if(en(i,ja(b,g)),!Nu(g))L0(o,{force:!0})},f=(g)=>{for(let b of a.splice(0))if(b===g)a.push(b);else L0(Mo(s,b),{force:!0})},d=()=>{clearTimeout(u),clearTimeout(c)},h=(g,b)=>{d(),u=setTimeout(()=>{let p=b;if(!p)p=`${_(g.name)}.view-${process.pid}-${a.length+1}.yaml`,K(Mo(s,p),Ks(g)),a.push(p);let m=p,$=Date.now()-C0(Mo(s,m)).mtimeMs;c=setTimeout(()=>{l(zl(g.name,m)),f(m)},Math.max(0,_N-$))},CN)};return{slots:[],paint:(g)=>{return h(g,WN(s,g.name)),""},look:(g,b)=>{let[p="",m="",$="",,...E]=b;h({name:g,background:p,foreground:m,cursor:$,ansi:E})},wear:(g,b)=>b.includes("warp")?"":void 0,saved:async()=>new Map([["theme",pr(rd(i,"utf8"))??""]]),restore:(g)=>{d();let b=g.get("theme");if(b)l(b);else if(Nu(pr(rd(i,"utf8"))))l(Wa);return f(),""}}}function _0(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function G0(e,t){if(e.includes("/"))return e;let n=xr(t,!1),r=n.filter((s)=>ir(s.dir).some((o)=>o.slug===e)),[i]=r.length===1?r:n.length===1?n:[];return i?`${i.id}/${e}`:e}function KN(e,t,n){let r=ne(e),i=n.filter((s)=>!r.palettes.includes(s));if(i.length>0)gn(e,t,r,{...r,palettes:[...r.palettes,...i]});else if(n.some((s)=>r.palettes.includes(s)))mt(e,t,r);return{state:r,fresh:i}}function BN(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 W0(e,t,n){let r=up(t),i=Jt(vt(r.name,ll(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 ${Me(i.name)??"the ttheme catalog"} and differs — \`ttheme add ${i.name}\` wears that one`);if(!s)Ma(e,[...In(e),i]);return i.name}var JN=["background","foreground","cursor"];function U0(e){try{e();return}catch(t){return t.message}}function j0(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 K0(e,t){let n=new Set(_t(e,t).map((r)=>r.key));return{count:()=>_t(e,t).length,added:()=>_t(e,t).filter((r)=>!n.has(r.key)).length,fresh:()=>(Xa(e,t)??[]).filter((r)=>!n.has(ft(r))),discard:()=>{let r=_t(e,t).filter((i)=>!n.has(i.key));for(let i of r)vi(e,t,i.key),ma(e,t);if(r.length>0)Nt(e)}}}function qN(...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 B0(e,t,n,r){if(!Rp(process.env))return;return async(i,s)=>{let o=Jt(vt(t,r(i),n.palettes)),{saved:a}=await x0(e,o,s);return{...a?{note:a}:{},count:_t(e,t).length}}}async function J0(e){let t=process.stdout.isTTY===!0,n=cr(process.env,t)??kr(process.env,t,ue()),r=n?await n.saved():new Map,i=n?.look?{look:(s)=>n.look?.(e.name,s)}:n?{only:n.slots}:{};try{return await l0(e,{color:!gt(),...i})}finally{if(n)process.stdout.write(n.restore(r))}}async function q0(e,t,n){let r=ue(),i=We(r),s=await aw(r,n),o=e.includes("/")?e:`${s.id}/${e}`,a=on(o);if(a)throw Error(`${o} ${a}`);if(Me(o)!==s.id)throw Error(`palettes in ${s.dir} are named ${s.id}/<palette> — ${o} belongs elsewhere`);let u=ul(r,o);if(So(u))throw Error(`${o} already exists — \`ttheme edit ${o}\` changes it`);let c=t?Ar(je(r,i).palettes,t):void 0;if(!_0())throw Error("new opens the palette editor — run it in a terminal");let l=c&&(Me(c.name)?c.base:c.default?void 0:c.name),f=c?cl(c,o,`kept from ${c.name}`):void 0,d=c?Xa(r,c.name)??c.pictures:void 0,{base:h,ansiSource:g,group:b,...p}=f??{name:o,signature:JN,...Vr(bu)},m=K0(r,o),$=({colors:w,signature:S})=>{let k=qN(d,m.fresh());return ll({...p,...w,signature:S,...l?{base:l}:{},...k?{pictures:k}:{}})},E=await J0({title:"New palette",name:o,...f?{colors:f}:{},signature:p.signature,...p.waive?{waive:p.waive}:{},palettes:j0(r,i,o),pictures:m.count(),find:B0(r,o,i,$),check:(w)=>U0(()=>vt(o,$(w),i.palettes))});if(!E){m.discard(),console.log("Nothing made");return}UN(jN(u),{recursive:!0}),K(u,$(E));let{state:M}=KN(r,i,[o]);console.log(` + ${o}${c?` from ${c.name}`:""}
509
509
  ${u}`),await Pn(r,je(r,i).palettes.filter((w)=>w.name===o),M.terminals),console.log(`
510
- \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function KN(e,t,n){let r=Bt(vt(e,t,n.palettes));return Cs(r).length>0?As(r).filter((i)=>i.startsWith(" ✗")):[]}async function J0(e){let t=le(),n=We(t),r=se(t),i=je(t,n,!1),s=C0(e,t),o=Nu(t,s),a=o&&Mo(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=Nu(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(!L0())throw Error("edit opens the palette editor — run it in a terminal");let c=nd(u,"utf8"),l;try{l=vt(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let f=U0(t,a),d=new Set((l.pictures??[]).map((m)=>ft(m))),h=({colors:m,signature:$})=>tp(op(cl(c,m),$),f.fresh().filter((E)=>!d.has(ft(E)))),g=await K0({title:"Edit palette",name:a,colors:ul(l),signature:l.signatureSlots,waive:l.waive,palettes:W0(t,n,a),pictures:f.count(),find:j0(t,a,n,h),check:(m)=>G0(()=>vt(a,h(m),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let b=h(g);if(b===c){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(K(u,b),r.palettes.includes(a))mt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let p=KN(a,b,n);if(p.length>0)console.log(`
510
+ \`ttheme use ${o}\` wears it · \`ttheme edit ${o}\` opens it again`)}function zN(e,t,n){let r=Jt(vt(e,t,n.palettes));return Cs(r).length>0?As(r).filter((i)=>i.startsWith(" ✗")):[]}async function z0(e){let t=ue(),n=We(t),r=ne(t),i=je(t,n,!1),s=G0(e,t),o=Ru(t,s),a=o&&So(o)?s:i.palettes.some((m)=>m.name===e)?e:s,u=Ru(t,a);if(!u||!So(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(!_0())throw Error("edit opens the palette editor — run it in a terminal");let c=id(u,"utf8"),l;try{l=vt(a,c,n.palettes)}catch(m){throw Error(`${u} cannot be read — ${m.message}`)}let f=K0(t,a),d=new Set((l.pictures??[]).map((m)=>ft(m))),h=({colors:m,signature:$})=>ip(cp(dl(c,m),$),f.fresh().filter((E)=>!d.has(ft(E)))),g=await J0({title:"Edit palette",name:a,colors:fl(l),signature:l.signatureSlots,waive:l.waive,palettes:j0(t,n,a),pictures:f.count(),find:B0(t,a,n,h),check:(m)=>U0(()=>vt(a,h(m),n.palettes))});if(!g){f.discard(),console.log("Nothing changed");return}let b=h(g);if(b===c){console.log(f.added()>0?`Kept the pictures you added to ${a}`:"Nothing changed");return}if(K(u,b),r.palettes.includes(a))mt(t,n,r);console.log(`Saved ${a}${r.palettes.includes(a)?" — new tabs and `ttheme use` wear it":` — \`ttheme add ${a}\` installs it`}`);let p=zN(a,b,n);if(p.length>0)console.log(`
511
511
  It misses the contrast gate:
512
512
  ${p.join(`
513
513
  `)}
514
- \`ttheme check --fix ${a}\` suggests colors that pass`)}function q0(e,t,n){return Ar(e.palettes,e.palettes.some((r)=>r.name===t)?t:C0(t,n))}function z0(e,t=!1){let n=le(),r=We(n),i=se(n),s=q0(je(n,r),e,n);if(console.log(`${s.name} · ${s.group}
514
+ \`ttheme check --fix ${a}\` suggests colors that pass`)}function V0(e,t,n){return Ar(e.palettes,e.palettes.some((r)=>r.name===t)?t:G0(t,n))}function Y0(e,t=!1){let n=ue(),r=We(n),i=ne(n),s=V0(je(n,r),e,n);if(console.log(`${s.name} · ${s.group}
515
515
  `),console.log(As(s).join(`
516
516
  `)),Cs(s).length===0)return console.log(`
517
- Passes the gate`),0;let{theme:a,moves:u,left:c}=gu(Mn(s));if(u.length===0)return console.log(`
517
+ Passes the gate`),0;let{theme:a,moves:u,left:c}=pu(Mn(s));if(u.length===0)return console.log(`
518
518
  No color change fixes it — waive the rule in [contrast] with a reason, or pick other colors`),1;console.log(`
519
519
  ${c.length===0?"These colors pass":"These colors come closer"}:
520
- ${WN(u).join(`
521
- `)}`);let l=Nu(n,s.name);if(!l||!Mo(l))return console.log(`
520
+ ${BN(u).join(`
521
+ `)}`);let l=Ru(n,s.name);if(!l||!So(l))return console.log(`
522
522
  \`ttheme new <name> --from ${s.name}\` makes a copy you can fix`),1;if(!t)return console.log(`
523
- \`ttheme check --fix ${s.name}\` writes them`),1;if(K(l,cl(nd(l,"utf8"),ul(a))),i.palettes.includes(s.name))mt(n,r,i);return console.log(`
524
- Wrote ${l}`),c.length===0?0:1}function Nu(e,t){let n=Me(t);return n&&xr(e,!1).some((r)=>r.id===n)?sl(e,t):void 0}function BN(e,t){let n=Nu(e,t.name),r=n&&Mo(n)?vt(t.name,nd(n,"utf8"),[t]).waiveReason:void 0,i=Va(e,t.name)??t.pictures,{pictures:s,...o}=ol(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Y0(e){let t=le(),n=ip(BN(t,q0(je(t,We(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
525
- Anyone with ttheme wears it with: ttheme add ${Sn}…`)}function Pu(e){console.log(`
526
- ${e} palettes installed — open a new tab, or reload your terminal config`)}function qN(e,t){return e.map((n)=>{if(n.startsWith(Sn))return n;let r=Me(n);if(r===void 0)return t===ee?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function Q0(e,t){let n=le(),r=t?qN(e,(await lf(n,t)).id):e,i=We(n),s=[...new Set(r.map((l)=>l.startsWith(Sn)?_0(n,l,i):l))],o=se(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){mt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};gn(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Pn(n,je(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Pu(c.palettes.length)}function V0(e){let t=le(),n=We(t),r=se(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};gn(t,n,r,o),qa(t,n,r.terminals,i);for(let a of i)console.log(` - ${a}`);if(Pu(o.palettes.length),s.length>0)return console.error(`ttheme remove: not installed: ${s.join(", ")}`),1;return 0}function Z0(e){let t=le(),n=We(t),r=se(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=gn(t,n,r,{...s,startup:e},!0);console.log(e$(e,r.terminals,o).join(`
527
- `))}function X0(){let e=le(),t=se(e),n=Wr(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=gn(e,We(e),t,i);console.log(e$(n,i.terminals,s).join(`
528
- `))}function D0(){let e=le(),t=se(e);if(t.off){console.log("Already off");return}let n=gn(e,We(e),t,{...t,off:!0}),r=Wr(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 e$(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 t$(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of ka(e,t.palettes,!1))n.set(r.name,"mine");return n}function n$(e,t=!1){let n=le(),r=We(n),i=new Set(se(n).palettes),s=t$(n,r),o=Xe(je(n,r).palettes),a=Hr(e?dp(o,e):o),u=(f)=>s.get(f)??"kept";if(t){let f=a.map((d)=>({name:d.name,group:d.group,...d.catalog?{catalog:d.catalog}:{},installed:i.has(d.name),source:u(d.name)}));console.log(JSON.stringify(f,null,2));return}let c=Math.max(...a.map((f)=>f.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let f of a){let d=f.catalog?`${f.group} / ${f.catalog}`:f.group;console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(c)} ${d}${l[u(f.name)]}`)}if(process.stdout.isTTY){let f=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
529
- ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function r$(){let e=le(),t=Si(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(d,h)=>`${ye(d)}: ${h.message} — kept the copy from the last update`;for(let d of t.filter(xe))try{console.log(` ${uw(e,d)}`)}catch(h){console.log(` ${n(d,h)}`)}let r=t.filter((d)=>!xe(d)),i=new Set(r),s=wr(),o=()=>s.set(`Updating ${[...i].map(ye).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(o(),await Promise.all(r.map(async(d)=>{let h;try{h=rf(await Ds(e,d))}catch(g){h=n(d,g)}if(i.delete(d),i.size>0)o();else s.done();s.say(` ${h}`)})),s.done(),!JN(tr(e)))return;let a=We(e),u=se(e),c=t$(e,a),l=u.palettes.filter((d)=>!c.has(d)),f=new Map(In(e).map((d)=>[d.name,d.pictures]));mt(e,a,u);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await Pn(e,je(e,a,!1).palettes.filter((d)=>u.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Ci(d,f.get(d.name))),u.terminals)}async function rd(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Hr(e.palettes),s=process.stdout.isTTY===!0,o=cr(process.env,s)??kr(process.env,s,le()),a=o?await o.saved():new Map,u=new Ef({entries:i,scope:n,installed:t,required:r,color:!gt(),fx:nu(process.env.TTHEME_FX),onFocus:o?(l)=>process.stdout.write(o.paint(l)):void 0}),c=await u.prompt();if(o)process.stdout.write(o.restore(a));if(ht(c))return;return e.palettes.filter((l)=>u.picked.has(l.name)).map((l)=>l.name)}function id(e,t,n,r){let i;try{i=Wi(e,n)}catch{i=yt(n)?er(n):ye(n)}let s=[];if(xe(n))try{s=sr(n,i,Gi(e,ee),!1)}catch{s=[]}else s=Gi(e,n);return{source:n,id:i,shown:ye(n),entries:s,auto:nr(n,t.updates),status:hf(e,n,r)}}function Ou(e){return e instanceof Error?e.message:String(e)}function YN(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=Zs(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${eo(u.at)}: ${u.error}`});if(o===ee)try{cn(i$(qt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ye(qt(e))}: ${Ou(l)}`})}else if(yt(o))if(!zN(Jt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{or(e,o)}catch(l){s.push({where:a,source:o,message:`${ye(Jt(e,o))}: ${Ou(l)}`})}else try{let l=Et(un(o)),f=new Map;for(let d of ir(o))try{let h=xs(d,f);if(h)throw Error(h);f.set(d.slug,d),vt(`${l}/${d.slug}`,i$(d.path,"utf8"),Gi(e,ee))}catch(h){s.push({where:ye(d.path),message:Ou(h)})}}catch(l){s.push({where:a,message:Ou(l)})}}return s}function QN(e,t,n,r){return{refresh:async(i)=>{if(xe(i)){let o=id(e,t,i,On());return{market:o,refreshed:{source:i,id:o.id,count:Xe(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await Ds(e,i,tf);return{market:id(e,t,i,On()),refreshed:s}},fetch:async(i)=>{if(xe(i)){let o=Et(un(i));return{source:i,id:o,shown:ye(i),entries:sr(i,o,Gi(e,ee),!1),auto:!1,status:"read in place"}}let s=await Xs(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ye(i),entries:s.entries,auto:nr(i,{}),status:"not added yet"}},search:(i)=>mf(i,r)}}function VN(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==ee&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${dt(Xe(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${ye(i)}`);let o=n.filter((a)=>(Me(a)??ee)===s);if(o.length>0)r.push(df(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 ZN(e,t,n,r,i){let s=se(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($)_i(e,$)}for(let m of r.removes)ff(e,m);let a=[...it(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=to(s,a,{...s.updates,...r.auto});if(o)hn(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 Xa(e,s,t,r.refreshed),console.log("Nothing changed");return}let h={...u,palettes:l};gn(e,c,s,h),qa(e,c,s.terminals,f);for(let m of VN(r,n,l))console.log(m);for(let m of d)console.log(` + ${m}`);for(let m of f)console.log(` - ${m}`);let g=new Map(t.map((m)=>[m.name,m.pictures])),b=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),p=je(e,c,!1).palettes;if(await Pn(e,[...p.filter((m)=>d.includes(m.name)),...p.filter((m)=>l.includes(m.name)&&!d.includes(m.name)&&b.has(m.name)&&g.has(m.name)).map((m)=>Ci(m,g.get(m.name)))],h.terminals),d.length>0||f.length>0)Pu(h.palettes.length)}async function s$(){let e=le(),t=se(e),n=In(e),r=On(),i=it(t.markets).map((p)=>id(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((m)=>m.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0,l=cr(process.env,c)??kr(process.env,c,e),f=l?await l.saved():new Map,d=Qt(t),h=new Sf({markets:i,kept:o,installed:t.palettes,...d?{startup:d}:{},problems:YN(e,t,r,i),due:nf(e,t),io:QN(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Hr},color:!gt(),fx:nu(process.env.TTHEME_FX),...l?{onFocus:(p)=>process.stdout.write(l.paint(p))}:{}}),g=await h.prompt();if(l)process.stdout.write(l.restore(f));u.abort(),await h.idle();let b=h.result();for(let p of b.refreshed){let m=sf(p);if(m)console.log(m)}if(ht(g)){await Xa(e,se(e),n,b.refreshed),console.log("Nothing changed");return}await ZN(e,n,i,b,a)}import{rmSync as o$}from"node:fs";import{basename as XN,join as So}from"node:path";var a$=So(import.meta.dirname,".."),DN=So(a$,"themes"),sd=So(a$,"dist"),Ru=Mt.map((e)=>br[e].emitter),eP=[Nl,el],D8=Ru.map((e)=>e.id);async function Fu({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?Ru.filter((s)=>e.includes(s.id)):Ru,n=pm(DN),r=hh(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===Ru.length)o$(sd,{recursive:!0,force:!0});else for(let s of t)o$(So(sd,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...eP]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(So(sd,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>XN(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
530
- ${n.length} themes (${bm(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{readFileSync as f$}from"node:fs";import{availableParallelism as tP,homedir as u$}from"node:os";var nP=4;async function Hu(e,t,n=u$()){let r=ct(Se(e)),i=Cr(e),s=new Map(ln(e).palettes.map((f)=>[f.name,Ps(f)])),o=Object.entries(r.palettes).flatMap(([f,d])=>{let h=s.get(f);return h?d.pictures.filter((g)=>Os(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=Ur(se(e).terminals),u=new Vf(Math.min(nP,tP()-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})}),Dc(e,l),It(e,n),l.length}async function c$(e,t,n,r,i=u$()){let s=ct(Se(e)).palettes[t],o=s?.pictures.find((l)=>l.key===(r??s.active));if(!s||!o)throw Error(`${t} has no picture ${r??"shown"}`);if(Dn(o)===n)return{key:o.key,changed:!1};let a=ln(e).palettes.find((l)=>l.name===t);if(!a)throw Error(`no palette called ${t}`);let u=Ur(se(e).terminals),c=await Za(e,t,o.key,Ps(a),Cr(e),u,i,n);if(!c)throw Error(`${t} ${o.key} has no original to draw it from`);return Dc(e,[{name:t,picture:c}]),It(e,i),{key:o.key,changed:!0}}async function l$(){return await Hu(le(),(e)=>process.stderr.write(`${e}
531
- `)),0}async function d$(e,t,n){let r=le();if(Ar(ln(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=vi(r,e,n);return It(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
532
- `),0}if(t==="drop"){let{key:i,left:s}=ga(r,e,n);return It(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
533
- `),0}if(t==="tone"||t==="original"){let i=await c$(r,e,t,n);return process.stderr.write(`Background · ${e} ${i.key} ${t==="tone"?"tinted":"in its own colors"}
534
- `),0}if(t==="tuned")return It(r),0;throw Error(`unknown image action ${t} — show, drop, tone, original or tuned`)}function h$(e,t){let n=/^(\d+)x(\d+)$/.exec(e),r=/^(\d+)x(\d+)([+-]\d+)([+-]\d+)$/.exec(t);if(!n||!r)throw Error("a canvas is <width>x<height> and a place <width>x<height>+<x>+<y>");let[i,s]=n.slice(1).map(Number),[o,a,u,c]=r.slice(1).map(Number);return{width:i,height:s,at:{x:u,y:c,w:o,h:a}}}function rP(e,t,n){let r=h$(t,n),i=Math.min(1,e.width/r.at.w);if(i===1)return r;return{width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*i)),at:{x:Math.round(r.at.x*i),y:Math.round(r.at.y*i),w:e.width,h:e.height}}}function g$(e,t,n,r){let i=xt(new Uint8Array(f$(e)));return K(t,Rg(Eg(i,h$(n,r)))),0}function m$(e,t,n,r,i,s){let o=Number(r);if(!Ht(n)||!Number.isFinite(o))throw Error("flatten needs a #rrggbb background and an opacity from 0 to 1");let a=xt(new Uint8Array(f$(e))),u=i===void 0?void 0:rP(a,i,s??"");return K(t,qo(Jo(a,n,Math.max(0,Math.min(1,o)),u))),0}import{execFileSync as iP,spawnSync as sP}from"node:child_process";import{chmodSync as oP,copyFileSync as aP,existsSync as Zr,mkdirSync as p$,readdirSync as uP,readFileSync as Au,rmSync as b$}from"node:fs";import{homedir as cP}from"node:os";import{dirname as Yi,join as ze}from"node:path";function lP(e,t,n){for(let r of uP(t))e.push({from:ze(t,r),to:ze(n,r)})}function cd(e){return JSON.parse(Au(ze(e,"dist","manifest.json"),"utf8"))}function xu(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}];lP(r,ze(t.root,"shell","adapters"),ze(n,"adapters"));let i=[{file:ze(t.zdotdir,".zshrc"),block:Tp(n)}],s=ze(n,"config.zsh"),o=Cp(Zr(s)?Au(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=Hb(t.configHome,u,t.home);return{home:t.home,copies:r,edits:i,settings:a,catalog:cd(t.root),installed:u,notes:c}}function $$(e){try{return se(e)}catch{return}}function k$(e){try{return je(e,We(e),!1).palettes}catch{return[]}}function fP(e,t){let n=cd(t.root),r=it(e.markets).includes(ee)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=k$(t.configHome).filter((o)=>!i.has(o.name)&&(Me(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function y$(e,t){let n=Wr(e);return n&&t.includes(n)?n:void 0}function dP(e,t,n){let r=xu(t,n),i=y$(e,t.palettes),s=new Set(["terminals","palettes","off","startup",...Mt.flatMap((a)=>Object.keys(br[a].installs?.(n)??{}))]),o=Object.fromEntries(Object.entries(e).filter(([a])=>!s.has(a)));return{...r,installed:{...o,...r.installed,...i?{startup:i}:{}}}}function hP(e,t){let n=xu({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...k$(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 gP(e){try{return iP(process.execPath,[ze(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E$(e){let t=Qt(e);return[Ce(e.terminals).map((n)=>n.name).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function od(e,t=_r()){for(let o of e.copies)if(p$(Yi(o.to),{recursive:!0}),b$(o.to,{force:!0}),b$(`${o.to}.zwc`,{force:!0}),aP(o.from,o.to),o.executable)oP(o.to,493);K(e.settings.file,e.settings.content);let n=Yi(Yi(e.settings.file)),r=$$(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=Xl(n,{...e.installed,...i},t,e.home);if(it(s.markets).includes(ee))ya(n,e.catalog);hn(n,s),mt(n,We(n),s,e.home);for(let o of e.edits){p$(Yi(o.file),{recursive:!0});let a=Zr(o.file)?Au(o.file,"utf8"):"";en(o.file,lr(a,o.block))}return Qs(n,s,!0,t,e.home)}class yr extends Error{}function Tu(e){if(ht(e))throw ni("Nothing changed"),new yr;return e}function ad(e,t){return Mt.filter((n)=>br[n].offered(e,t))}async function mP(e,t,n,r){return Tu(await rh({message:"Wire which terminals?",options:ad(n,r).map((i)=>({value:i,label:br[i].name,hint:i===e?"detected":void 0})),initialValues:t,required:!0}))}function ud(e){let t=[...e.copies.filter((n)=>!Zr(n.to)).map((n)=>n.to),...Zr(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!Au(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
523
+ \`ttheme check --fix ${s.name}\` writes them`),1;if(K(l,dl(id(l,"utf8"),fl(a))),i.palettes.includes(s.name))mt(n,r,i);return console.log(`
524
+ Wrote ${l}`),c.length===0?0:1}function Ru(e,t){let n=Me(t);return n&&xr(e,!1).some((r)=>r.id===n)?ul(e,t):void 0}function VN(e,t){let n=Ru(e,t.name),r=n&&So(n)?vt(t.name,id(n,"utf8"),[t]).waiveReason:void 0,i=Xa(e,t.name)??t.pictures,{pictures:s,...o}=cl(t,t.name,r);return{...o,...i?{pictures:i}:{}}}function Q0(e){let t=ue(),n=ap(VN(t,V0(je(t,We(t)),e,t)));if(console.log(n),process.stdout.isTTY)console.error(`
525
+ Anyone with ttheme wears it with: ttheme add ${Sn}…`)}function Ou(e){console.log(`
526
+ ${e} palettes installed — open a new tab, or reload your terminal config`)}function QN(e,t){return e.map((n)=>{if(n.startsWith(Sn))return n;let r=Me(n);if(r===void 0)return t===ee?n:`${t}/${n}`;if(r!==t)throw Error(`${n} is not in ${t} — give its bare name, or leave --market out`);return n})}async function Z0(e,t){let n=ue(),r=t?QN(e,(await df(n,t)).id):e,i=We(n),s=[...new Set(r.map((l)=>l.startsWith(Sn)?W0(n,l,i):l))],o=ne(n),a=s.filter((l)=>o.palettes.includes(l)),u=s.filter((l)=>!o.palettes.includes(l));if(u.length===0){mt(n,i,o),console.log(`Already installed: ${a.join(", ")}`);return}let c={...o,palettes:[...o.palettes,...u]};gn(n,i,o,c);for(let l of u)console.log(` + ${l}`);await Pn(n,je(n,i,!1).palettes.filter((l)=>u.includes(l.name)),c.terminals),Ou(c.palettes.length)}function X0(e){let t=ue(),n=We(t),r=ne(t),i=e.filter((a)=>r.palettes.includes(a)),s=e.filter((a)=>!r.palettes.includes(a));if(i.length===0)throw Error(`not installed: ${s.join(", ")} — \`ttheme list\` marks what is`);let o={...r,palettes:r.palettes.filter((a)=>!i.includes(a))};gn(t,n,r,o),Va(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 D0(e){let t=ue(),n=We(t),r=ne(t);if(!r.palettes.includes(e))throw Error(`${e} is not installed — \`ttheme add ${e}\` first`);let{off:i,...s}=r,o=gn(t,n,r,{...s,startup:e},!0);console.log(n$(e,r.terminals,o).join(`
527
+ `))}function e$(){let e=ue(),t=ne(e),n=Wr(t);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!t.off){console.log(`Already on · ${n}`);return}let{off:r,...i}=t,s=gn(e,We(e),t,i);console.log(n$(n,i.terminals,s).join(`
528
+ `))}function t$(){let e=ue(),t=ne(e);if(t.off){console.log("Already off");return}let n=gn(e,We(e),t,{...t,off:!0}),r=Wr(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 n$(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 r$(e,t){let n=new Map(t.palettes.map((r)=>[r.name,"market"]));for(let r of ya(e,t.palettes,!1))n.set(r.name,"mine");return n}function i$(e,t=!1){let n=ue(),r=We(n),i=new Set(ne(n).palettes),s=r$(n,r),o=Xe(je(n,r).palettes),a=Tr(e?mp(o,e):o),u=(f)=>s.get(f)??"kept";if(t){let f=a.map((d)=>({name:d.name,group:d.group,...d.catalog?{catalog:d.catalog}:{},installed:i.has(d.name),source:u(d.name)}));console.log(JSON.stringify(f,null,2));return}let c=Math.max(...a.map((f)=>f.name.length),0),l={market:"",mine:" · yours",kept:" · in no market you added"};for(let f of a){let d=f.catalog?`${f.group} / ${f.catalog}`:f.group;console.log(` ${i.has(f.name)?"●":"○"} ${f.name.padEnd(c)} ${d}${l[u(f.name)]}`)}if(process.stdout.isTTY){let f=e?`${a.length} of ${o.length}`:`${o.length}`;console.log(`
529
+ ${f} palettes — ${a.filter((d)=>i.has(d.name)).length} installed`)}}async function s$(){let e=ue(),t=Si(e);if(t.length===0)console.log("No markets to update — `ttheme market add official` brings the ttheme catalog back");let n=(d,h)=>`${ye(d)}: ${h.message} — kept the copy from the last update`;for(let d of t.filter(xe))try{console.log(` ${lw(e,d)}`)}catch(h){console.log(` ${n(d,h)}`)}let r=t.filter((d)=>!xe(d)),i=new Set(r),s=wr(),o=()=>s.set(`Updating ${[...i].map(ye).join(", ")}${r.length>1?` · ${r.length-i.size}/${r.length}`:""}`);if(o(),await Promise.all(r.map(async(d)=>{let h;try{h=of(await eo(e,d))}catch(g){h=n(d,g)}if(i.delete(d),i.size>0)o();else s.done();s.say(` ${h}`)})),s.done(),!YN(tr(e)))return;let a=We(e),u=ne(e),c=r$(e,a),l=u.palettes.filter((d)=>!c.has(d)),f=new Map(In(e).map((d)=>[d.name,d.pictures]));mt(e,a,u);for(let d of l)console.log(` ${d} left its market — ttheme keeps the copy you have`);await Pn(e,je(e,a,!1).palettes.filter((d)=>u.palettes.includes(d.name)&&f.has(d.name)).map((d)=>Ci(d,f.get(d.name))),u.terminals)}async function sd(e,t,n,r=!1){let i=process.env.TTHEME_SORT==="series"?e.palettes:Tr(e.palettes),s=process.stdout.isTTY===!0,o=cr(process.env,s)??kr(process.env,s,ue()),a=o?await o.saved():new Map,u=new Mf({entries:i,scope:n,installed:t,required:r,color:!gt(),fx:iu(process.env.TTHEME_FX),onFocus:o?(l)=>process.stdout.write(o.paint(l)):void 0}),c=await u.prompt();if(o)process.stdout.write(o.restore(a));if(ht(c))return;return e.palettes.filter((l)=>u.picked.has(l.name)).map((l)=>l.name)}function od(e,t,n,r){let i;try{i=Wi(e,n)}catch{i=yt(n)?er(n):ye(n)}let s=[];if(xe(n))try{s=sr(n,i,Gi(e,ee),!1)}catch{s=[]}else s=Gi(e,n);return{source:n,id:i,shown:ye(n),entries:s,auto:nr(n,t.updates),status:mf(e,n,r)}}function Fu(e){return e instanceof Error?e.message:String(e)}function XN(e,t,n,r){let i=new Map(r.map((o)=>[o.source,o.id])),s=[];for(let o of st(t.markets)){let a=i.get(o)??ye(o),u=n[o],c=Xs(e,o);if(u&&(c===void 0||u.at>c))s.push({where:a,source:o,update:!0,message:`Update failed ${to(u.at)}: ${u.error}`});if(o===ee)try{cn(o$(zt(e),"utf8"))}catch(l){s.push({where:a,source:o,message:`${ye(zt(e))}: ${Fu(l)}`})}else if(yt(o))if(!ZN(qt(e,o)))s.push({where:a,source:o,message:"No copy of its index yet — `ttheme update` fetches it"});else try{or(e,o)}catch(l){s.push({where:a,source:o,message:`${ye(qt(e,o))}: ${Fu(l)}`})}else try{let l=Et(un(o)),f=new Map;for(let d of ir(o))try{let h=xs(d,f);if(h)throw Error(h);f.set(d.slug,d),vt(`${l}/${d.slug}`,o$(d.path,"utf8"),Gi(e,ee))}catch(h){s.push({where:ye(d.path),message:Fu(h)})}}catch(l){s.push({where:a,message:Fu(l)})}}return s}function DN(e,t,n,r){return{refresh:async(i)=>{if(xe(i)){let o=od(e,t,i,Rn());return{market:o,refreshed:{source:i,id:o.id,count:Xe(o.entries).length,change:{added:[],changed:[],gone:[]}}}}let s=await eo(e,i,rf);return{market:od(e,t,i,Rn()),refreshed:s}},fetch:async(i)=>{if(xe(i)){let o=Et(un(i));return{source:i,id:o,shown:ye(i),entries:sr(i,o,Gi(e,ee),!1),auto:!1,status:"read in place"}}let s=await Ds(i,void 0,r);return n.set(i,s),{source:i,id:s.id,shown:ye(i),entries:s.entries,auto:nr(i,{}),status:"not added yet"}},search:(i)=>bf(i,r)}}function eP(e,t,n){let r=[];for(let i of e.adds){let s=i.source!==ee&&(e.auto[i.source]??i.auto);r.push(`Added ${i.id} · ${i.shown} — ${dt(Xe(i.entries).length)}${s?", updating on its own":""}`)}for(let i of e.removes){let s=t.find((a)=>a.source===i)?.id??i;r.push(`Removed ${s} · ${ye(i)}`);let o=n.filter((a)=>(Me(a)??ee)===s);if(o.length>0)r.push(gf(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 tP(e,t,n,r,i){let s=ne(e),o=r.adds.length+r.removes.length+Object.keys(r.auto).length>0;for(let m of r.adds){let $=i.get(m.source);if($)_i(e,$)}for(let m of r.removes)hf(e,m);let a=[...st(s.markets).filter((m)=>!r.removes.includes(m)),...r.adds.map((m)=>m.source)],u=no(s,a,{...s.updates,...r.auto});if(o)hn(e,u);let c=We(e,!1),l=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 eu(e,s,t,r.refreshed),console.log("Nothing changed");return}let h={...u,palettes:l};gn(e,c,s,h),Va(e,c,s.terminals,f);for(let m of eP(r,n,l))console.log(m);for(let m of d)console.log(` + ${m}`);for(let m of f)console.log(` - ${m}`);let g=new Map(t.map((m)=>[m.name,m.pictures])),b=new Set(r.refreshed.flatMap((m)=>[...m.change.changed,...m.change.gone])),p=je(e,c,!1).palettes;if(await Pn(e,[...p.filter((m)=>d.includes(m.name)),...p.filter((m)=>l.includes(m.name)&&!d.includes(m.name)&&b.has(m.name)&&g.has(m.name)).map((m)=>Ci(m,g.get(m.name)))],h.terminals),d.length>0||f.length>0)Ou(h.palettes.length)}async function a$(){let e=ue(),t=ne(e),n=In(e),r=Rn(),i=st(t.markets).map((p)=>od(e,t,p,r)),s=new Set(i.flatMap((p)=>p.entries.map((m)=>m.name))),o=n.filter((p)=>t.palettes.includes(p.name)&&!s.has(p.name)),a=new Map,u=new AbortController,c=process.stdout.isTTY===!0,l=cr(process.env,c)??kr(process.env,c,e),f=l?await l.saved():new Map,d=Yt(t),h=new Nf({markets:i,kept:o,installed:t.palettes,...d?{startup:d}:{},problems:XN(e,t,r,i),due:sf(e,t),io:DN(e,t,a,u.signal),...process.env.TTHEME_SORT==="series"?{}:{order:Tr},color:!gt(),fx:iu(process.env.TTHEME_FX),...l?{onFocus:(p)=>process.stdout.write(l.paint(p))}:{}}),g=await h.prompt();if(l)process.stdout.write(l.restore(f));u.abort(),await h.idle();let b=h.result();for(let p of b.refreshed){let m=af(p);if(m)console.log(m)}if(ht(g)){await eu(e,ne(e),n,b.refreshed),console.log("Nothing changed");return}await tP(e,n,i,b,a)}import{rmSync as u$}from"node:fs";import{basename as nP,join as Io}from"node:path";var c$=Io(import.meta.dirname,".."),rP=Io(c$,"themes"),ad=Io(c$,"dist"),Tu=St.map((e)=>br[e].emitter),iP=[Rl,rl],m8=Tu.map((e)=>e.id);async function Hu({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?Tu.filter((s)=>e.includes(s.id)):Tu,n=$m(rP),r=ph(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===Tu.length)u$(ad,{recursive:!0,force:!0});else for(let s of t)u$(Io(ad,s.id),{recursive:!0,force:!0});let i=0;for(let s of[...t,...iP]){let o=n.flatMap((c)=>s.emit?.(c)??[]),a=s.emitShared?.(n)??[];for(let c of[...o,...a])await Bun.write(Io(ad,c.path),c.content),i++;let u=o.length>0?`${n.length} themes${s.limits?` (${s.limits})`:""}`:a.map((c)=>nP(c.path)).join(" ");console.log(` ${s.id.padEnd(16)} ${u}`)}console.log(`
530
+ ${n.length} themes (${km(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{readFileSync as h$}from"node:fs";import{availableParallelism as sP,homedir as l$}from"node:os";var oP=4;async function xu(e,t,n=l$()){let r=ct(Se(e)),i=Cr(e),s=new Map(ln(e).palettes.map((f)=>[f.name,Ps(f)])),o=Object.entries(r.palettes).flatMap(([f,d])=>{let h=s.get(f);return h?d.pictures.filter((g)=>Rs(g)||(g.blur??0)!==i).map((g)=>({name:f,key:g.key,paint:h})):[]});if(o.length===0)return 0;t(`Drawing ${o.length} background picture${o.length===1?"":"s"} again${i?` · blur ${i}px`:""}`);let a=Ur(ne(e).terminals),u=new Xf(Math.min(oP,sP()-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})}),nl(e,l),Nt(e,n),l.length}async function f$(e,t,n,r,i=l$()){let s=ct(Se(e)).palettes[t],o=s?.pictures.find((l)=>l.key===(r??s.active));if(!s||!o)throw Error(`${t} has no picture ${r??"shown"}`);if(Dn(o)===n)return{key:o.key,changed:!1};let a=ln(e).palettes.find((l)=>l.name===t);if(!a)throw Error(`no palette called ${t}`);let u=Ur(ne(e).terminals),c=await Da(e,t,o.key,Ps(a),Cr(e),u,i,n);if(!c)throw Error(`${t} ${o.key} has no original to draw it from`);return nl(e,[{name:t,picture:c}]),Nt(e,i),{key:o.key,changed:!0}}async function d$(){return await xu(ue(),(e)=>process.stderr.write(`${e}
531
+ `)),0}async function g$(e,t,n){let r=ue();if(Ar(ln(r).palettes,e),t==="show"){if(!n)throw Error("image show needs the picture to show");let{at:i,of:s}=vi(r,e,n);return Nt(r),process.stderr.write(`Background · ${e} ${i}/${s} ${n}
532
+ `),0}if(t==="drop"){let{key:i,left:s}=ma(r,e,n);return Nt(r),process.stderr.write(`Background · ${e} removed ${i} · ${s} left
533
+ `),0}if(t==="tone"||t==="original"){let i=await f$(r,e,t,n);return process.stderr.write(`Background · ${e} ${i.key} ${t==="tone"?"tinted":"in its own colors"}
534
+ `),0}if(t==="tuned")return Nt(r),0;throw Error(`unknown image action ${t} — show, drop, tone, original or tuned`)}function m$(e,t){let n=/^(\d+)x(\d+)$/.exec(e),r=/^(\d+)x(\d+)([+-]\d+)([+-]\d+)$/.exec(t);if(!n||!r)throw Error("a canvas is <width>x<height> and a place <width>x<height>+<x>+<y>");let[i,s]=n.slice(1).map(Number),[o,a,u,c]=r.slice(1).map(Number);return{width:i,height:s,at:{x:u,y:c,w:o,h:a}}}function aP(e,t,n){let r=m$(t,n),i=Math.min(1,e.width/r.at.w);if(i===1)return r;return{width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*i)),at:{x:Math.round(r.at.x*i),y:Math.round(r.at.y*i),w:e.width,h:e.height}}}function p$(e,t,n,r){let i=At(new Uint8Array(h$(e)));return K(t,Hg(Sg(i,m$(n,r)))),0}function b$(e,t,n,r,i,s){let o=Number(r);if(!Ht(n)||!Number.isFinite(o))throw Error("flatten needs a #rrggbb background and an opacity from 0 to 1");let a=At(new Uint8Array(h$(e))),u=i===void 0?void 0:aP(a,i,s??"");return K(t,zo(qo(a,n,Math.max(0,Math.min(1,o)),u))),0}import{execFileSync as uP}from"node:child_process";import{readFileSync as cP}from"node:fs";import{arch as lP,platform as Au,release as ud}from"node:os";var fP={ghostty:"ghostty",iterm2:"iTerm.app",wezterm:"WezTerm","terminal-app":"Apple_Terminal",warp:"WarpTerminal"};function dP(e,t){if(e==="konsole"){let r=/^(\d{2})(\d{2})(\d{2})$/.exec(t.KONSOLE_VERSION??"");return r?`${r[1]}.${r[2]}.${Number(r[3])}`:t.KONSOLE_VERSION}let n=fP[e];return n!==void 0&&t.TERM_PROGRAM===n?t.TERM_PROGRAM_VERSION:void 0}function hP(e){let t=Mt(e),n=e.TERM_PROGRAM&&e.TERM_PROGRAM!=="tmux"?e.TERM_PROGRAM:void 0,r=t==="unknown"?`unknown${n?` (TERM_PROGRAM=${n})`:""}`:`${t} ${dP(t,e)??"(version unknown)"}`,i=e.TERM_PROGRAM==="tmux"?e.TERM_PROGRAM_VERSION:void 0;return[r,e.TMUX?`tmux ${i??"yes"}`:"tmux no",e.SSH_CONNECTION||e.SSH_TTY?"ssh yes":"ssh no"].join(" · ")}function w$(e,t){try{return uP(e,t,{encoding:"utf8",timeout:2000,stdio:["ignore","pipe","ignore"]}).trim()}catch{return}}function gP(){let e=lP();if(Au()==="darwin")return`macOS ${w$("sw_vers",["-productVersion"])??`(Darwin ${ud()})`} · ${e}`;if(Au()==="linux"){let t="";try{t=cP("/etc/os-release","utf8")}catch{}return`${/^PRETTY_NAME="?([^"\n]*)"?$/m.exec(t)?.[1]??"Linux"} · linux ${ud()} · ${e}`}return`${Au()==="win32"?"Windows":Au()} ${ud()} · ${e}`}function mP(e){if(e.TTHEME_ZSH)return`zsh ${e.TTHEME_ZSH}`;return(e.SHELL?w$(e.SHELL,["--version"])?.split(`
535
+ `)[0]:void 0)??e.SHELL??"unknown"}function pP(e){try{let{terminals:t}=ne(e);return t.length>0?t.join(", "):"none"}catch{return"installed.json missing or unreadable"}}function bP(e){let t=Pa.flatMap((n)=>{let r=e[n];return r===void 0||r===Us(n)?[]:[`${n}=${/\s/.test(r)?JSON.stringify(r):r}`]});return t.length>0?t.join(" "):void 0}function $$(){let e=process.env,n=[["ttheme",et.version],["OS",gP()],["Shell",mP(e)],["Terminal",hP(e)],["Wired",pP(ue())],["Settings",bP(e)]].filter((i)=>i[1]!==void 0),r=Math.max(...n.map(([i])=>i.length));for(let[i,s]of n)console.log(`${i.padEnd(r)} ${s}`)}import{execFileSync as wP,spawnSync as $P}from"node:child_process";import{chmodSync as kP,copyFileSync as yP,existsSync as Zr,mkdirSync as k$,readdirSync as EP,readFileSync as _u,rmSync as y$}from"node:fs";import{homedir as vP}from"node:os";import{dirname as Vi,join as ze}from"node:path";function MP(e,t,n){for(let r of EP(t))e.push({from:ze(t,r),to:ze(n,r)})}function dd(e){return JSON.parse(_u(ze(e,"dist","manifest.json"),"utf8"))}function Cu(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}];MP(r,ze(t.root,"shell","adapters"),ze(n,"adapters"));let i=[{file:ze(t.zdotdir,".zshrc"),block:Lp(n)}],s=ze(n,"config.zsh"),o=Gp(Zr(s)?_u(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=xb(t.configHome,u,t.home);return{home:t.home,copies:r,edits:i,settings:a,catalog:dd(t.root),installed:u,notes:c}}function v$(e){try{return ne(e)}catch{return}}function M$(e){try{return je(e,We(e),!1).palettes}catch{return[]}}function SP(e,t){let n=dd(t.root),r=st(e.markets).includes(ee)?n.palettes:[],i=new Set(r.map((o)=>o.name)),s=M$(t.configHome).filter((o)=>!i.has(o.name)&&(Me(o.name)!==void 0||e.palettes.includes(o.name)));return{...n,palettes:[...r,...s]}}function S$(e,t){let n=Wr(e);return n&&t.includes(n)?n:void 0}function IP(e,t,n){let r=Cu(t,n),i=S$(e,t.palettes),s=new Set(["terminals","palettes","off","startup",...St.flatMap((a)=>Object.keys(br[a].installs?.(n)??{}))]),o=Object.fromEntries(Object.entries(e).filter(([a])=>!s.has(a)));return{...r,installed:{...o,...r.installed,...i?{startup:i}:{}}}}function NP(e,t){let n=Cu({terminals:e.terminals,palettes:e.palettes,off:e.off},t),r=new Set([...n.catalog.palettes,...M$(t.configHome)].map((l)=>l.name)),i=e.palettes.filter((l)=>r.has(l)),s=e.palettes.filter((l)=>!r.has(l)),{startup:o,...a}=e,u={...a,palettes:i,...o&&i.includes(o)?{startup:o}:{}},c=s.length>0?[`Dropped ${s.join(", ")} — no longer in the catalog`,...n.notes]:n.notes;return{...n,installed:u,notes:c}}function PP(e){try{return wP(process.execPath,[ze(e,"ttheme","ttheme.js"),"--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function I$(e){let t=Yt(e);return[Ce(e.terminals).map((n)=>n.name).join(", "),`${e.palettes.length} palettes`,t?`default ${t}`:"no default — ttheme is off"].join(" · ")}function cd(e,t=_r()){for(let o of e.copies)if(k$(Vi(o.to),{recursive:!0}),y$(o.to,{force:!0}),y$(`${o.to}.zwc`,{force:!0}),yP(o.from,o.to),o.executable)kP(o.to,493);K(e.settings.file,e.settings.content);let n=Vi(Vi(e.settings.file)),r=v$(n),i=Object.fromEntries(Ce(e.installed.terminals).flatMap((o)=>{let a=o.defaults?.key,u=a?r?.[a]:void 0;return a&&u?[[a,u]]:[]})),s=ef(n,{...e.installed,...i},t,e.home);if(st(s.markets).includes(ee))Ea(n,e.catalog);hn(n,s),mt(n,We(n),s,e.home);for(let o of e.edits){k$(Vi(o.file),{recursive:!0});let a=Zr(o.file)?_u(o.file,"utf8"):"";en(o.file,lr(a,o.block))}return Qs(n,s,!0,t,e.home)}class yr extends Error{}function Lu(e){if(ht(e))throw ni("Nothing changed"),new yr;return e}function ld(e,t){return St.filter((n)=>br[n].offered(e,t))}async function RP(e,t,n,r){return Lu(await oh({message:"Wire which terminals?",options:ld(n,r).map((i)=>({value:i,label:br[i].name,hint:i===e?"detected":void 0})),initialValues:t,required:!0}))}function fd(e){let t=[...e.copies.filter((n)=>!Zr(n.to)).map((n)=>n.to),...Zr(e.settings.file)?[]:[e.settings.file],...e.edits.filter((n)=>!_u(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(t.length>0)throw Error(`init left gaps:
535
536
  ${t.join(`
536
- `)}`)}function v$(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function pP(e,t,n){let r=e.palettes.find((o)=>o.name===Qt(t)),i=process.stdout.isTTY===!0,s=r&&(cr(process.env,i)??kr(process.env,i,n))?.wear(r,t.terminals);if(s===void 0)return!1;return process.stdout.write(s),!0}function bP(e,t){let n=Qt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Wr(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function wP(e){sP("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ze(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function $P(e,t,n,r){let i=v$(e.catalog,t.palettes);vr([`${i.join(", ")} (${t.palettes.length})`,...bP(e.installed,n)].join(`
537
- `),`Installed ${t.palettes.length} palettes`),vr(["exec zsh The ttheme command in this tab",...ld(e,r)].join(`
538
- `),"Next"),Xu("Done")}function ld(e,t){return[...Tb(Yi(Yi(e.settings.file)),e.installed,t,e.home),...e.notes]}function M$(e){return e?(t)=>Tn.step(t):(t)=>console.log(t)}async function w$(e,t,n,r){let i=hP(e,t),s=od(i,n);ud(i),await Hu(t.configHome,M$(r),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...ld(i,s)],a=`Updated to ${ot.version} — kept ${E$(i.installed)}`;if(!r){console.log([a,...o].join(`
537
+ `)}`)}function N$(e,t){return[...new Set(e.palettes.filter((n)=>t.includes(n.name)).map((n)=>n.group))]}function OP(e,t,n){let r=e.palettes.find((o)=>o.name===Yt(t)),i=process.stdout.isTTY===!0,s=r&&(cr(process.env,i)??kr(process.env,i,n))?.wear(r,t.terminals);if(s===void 0)return!1;return process.stdout.write(s),!0}function FP(e,t){let n=Yt(e);if(!n)return["Default none — new tabs keep the terminal colors",`Turn on \`ttheme on\` wears ${Wr(e)}`];return[`Default ${n}${t?" — this tab wears it already":""}`,"Change it `ttheme preview`, enter on a palette, then default"]}function TP(e){$P("zsh",["-c",'source "$1" && __tt_preview init',"zsh",ze(e,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function HP(e,t,n,r){let i=N$(e.catalog,t.palettes);vr([`${i.join(", ")} (${t.palettes.length})`,...FP(e.installed,n)].join(`
538
+ `),`Installed ${t.palettes.length} palettes`),vr(["exec zsh The ttheme command in this tab",...hd(e,r)].join(`
539
+ `),"Next"),tc("Done")}function hd(e,t){return[...Ab(Vi(Vi(e.settings.file)),e.installed,t,e.home),...e.notes]}function P$(e){return e?(t)=>Hn.step(t):(t)=>console.log(t)}async function E$(e,t,n,r){let i=NP(e,t),s=cd(i,n);fd(i),await xu(t.configHome,P$(r),t.home);let o=["exec zsh Open tabs run the new layer — new tabs already do",...hd(i,s)],a=`Updated to ${et.version} — kept ${I$(i.installed)}`;if(!r){console.log([a,...o].join(`
539
540
  `));return}vr(o.join(`
540
- `),a),Xu("Done")}function kP(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}`),...ld(e,t),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
541
- `))}async function S$(e={}){let t=ze(import.meta.dirname,"..");if(!Zr(ze(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Zr(ze(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Fu()}let n=cP(),r=le(),i=process.env.ZDOTDIR??n,s=_r(),o=Sb(s),a=process.env.WT_PROFILE_ID,u={root:t,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...a?{wtProfile:a}:{}},c=zt(process.env),l=ad(u,s).filter((S)=>S===c||br[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=$$(r);if(e.yes&&f){await w$(f,u,s,!1);return}if(e.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${Ce(ad(u,s)).map((O)=>O.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let k=xu({terminals:l,palettes:[]},u),N=od(k,s);ud(k),kP(k,N);return}if(_o("ttheme init"),f){let S=gP(r);if(Tu(await An({message:`ttheme${S?` ${S}`:""} is installed — ${E$(f)}
542
- ${S===ot.version?"Reinstall":"Update to"} ${ot.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await w$(f,u,s,!0);return}}let d=await mP(c,f?.terminals??l,u,s),h=f?fP(f,u):cd(t),g=f?await rd(h,f.palettes,"palette",!0):await rd(h,[],"series",!0);if(!g)throw ni("Nothing changed"),new yr;let b=(f&&y$(f,g))??g[0],p=g.length>1&&(Yt[c].paints||c==="warp"&&d.includes("warp")&&Zr(mr(n,r))),m=Tu(await An({message:p?"Pick a default palette in ttheme preview once installed?":`Wear ${b} in every tab?`,initialValue:f?!f.off:!0})),$={terminals:d,palettes:g,off:!m},E=f?dP(f,$,u):xu($,u);if(vr([`Install ${g.length} palettes — ${v$(h,g).join(", ")}`,`Copy ${E.copies.length} files under ${r}`,`Write ${E.settings.file}`,...E.edits.map((S)=>`Edit ${S.file} — a ttheme block: source ttheme.zsh`),...Fb(r,E.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",m?p?`Open ttheme preview — every tab wears the palette picked there, ${b} until then`:`Paint every tab with ${b}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...m&&b?Ce(d).flatMap((S)=>S.defaults?[`Make "${S.defaults.profile(b)}" the ${S.name} default profile`]:[]):[]].join(`
543
- `),`Wiring ${Ce(d).map((S)=>S.name).join(", ")}`),!Tu(await An({message:"Apply these changes?"})))throw ni("Nothing changed"),new yr;let M=od(E,s);if(ud(E),await Hu(r,M$(!0),n),m&&p)wP(r);let w=se(r);$P({...E,catalog:h,installed:w},$,pP(h,w,r),M)}import{existsSync as I$,rmSync as yP,utimesSync as EP}from"node:fs";import{homedir as vP}from"node:os";import{join as Io}from"node:path";function MP(e){try{return se(e)}catch{return}}function SP(e){let{home:t,configHome:n}=e,r=MP(n),i={configHome:n,home:t},s=Ce(Mt),o=s.map((u)=>u.unwire(i,r)),a=[Io(n,"ttheme"),e.cacheDir,e.stateDir];return{edits:[...fn(Io(e.zdotdir,".zshrc"),fr),...o.flatMap((u)=>u.edits)],removals:[...s.flatMap((u)=>u.shelf?Oa(u.shelf.dir(i)):[]),...o.flatMap((u)=>u.removals),...a.filter((u)=>I$(u))],touches:o.flatMap((u)=>u.touches),...r?{state:r}:{}}}function IP(e,t,n=_r()){let r=[];for(let{file:s,content:o}of e.edits){let a=ph(s,o);r.push(a==="removed"?`Removed ${s} — ttheme had created it`:a==="restored"?`Took ttheme out of ${s}`:`Took ttheme out of ${s} — kept ${s}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state){let s=Qs(t.configHome,{...e.state,off:!0,palettes:[]},!1,n,t.home);for(let o of Ce(e.state.terminals))if(s.has(o.id))r.push(`Gave ${o.name} its own default profile back — it takes it at its next start`)}for(let s of e.removals)yP(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)EP(s,i,i);return r}function NP(){let e=vP();return{home:e,configHome:le(),zdotdir:process.env.ZDOTDIR??e,cacheDir:bi(),stateDir:Io(process.env.XDG_STATE_HOME??Io(e,".local","state"),"ttheme")}}async function N$(e=!1){let t=NP(),n=SP(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=Io(t.configHome,"ttheme");_o("ttheme uninstall"),vr([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${I$(wa(t.configHome))?`, and your markets under ${wa(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
544
- `),"Uninstall");let i=await An({message:"Remove ttheme?"});if(ht(i)||!i)throw ni("Nothing changed"),new yr}for(let r of IP(n,t))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var OP=new Set(["add","remove","market","default","on","off"]),RP={default:([e])=>Z0(e),on:()=>X0(),off:()=>D0(),browse:()=>s$(),list:([e],{json:t})=>n$(e,t),add:(e,{market:t})=>Q0(e,t),remove:(e)=>V0(e),update:()=>r$(),market:([e,t])=>aw(e,t),new:([e],{from:t,in:n})=>B0(e,t,n),edit:([e])=>J0(e),check:([e],{fix:t})=>z0(e,t),share:([e])=>Y0(e),init:(e,{yes:t})=>S$({yes:t}),uninstall:(e,{yes:t})=>N$(t),build:(e,{only:t})=>Fu({only:t}),find:([e])=>T0(e),image:([e,t,n])=>d$(e,t,n),redraw:()=>l$(),flatten:([e,t,n,r,i,s])=>m$(e,t,n,r,i,s),bake:([e,t,n,r])=>g$(e,t,n,r)},FP=Gs.map((e)=>({...e,run:RP[e.name]}));class Xr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function P$(e){let t=FP.find((n)=>n.name===e);if(!t)throw new Xr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function HP(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 PP({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Xr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function TP(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:P$(n[0]),code:0}}let r=P$(t),i=HP(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 Xr(`--${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 Xr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new Xr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function O$(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function fd(e,t=!1){if(!e)return Ws(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${_s(e)}`,"",e.about,...e.actions?["","Actions:",...O$(e.actions)]:[],...n.length>0?["","Options:",...O$(n)]:[]].join(`
545
- `)}async function R$(e){let t;try{let n=TP(e);if(n.kind==="version")return console.log(ot.version),0;if(n.kind==="help"){if(n.code===0)console.log(fd(n.verb,n.all));else console.error(fd(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(OP.has(n.verb.name))await Jb();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Xr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
541
+ `),a),tc("Done")}function xP(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}`),...hd(e,t),"No palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"];console.log(n.join(`
542
+ `))}async function R$(e={}){let t=ze(import.meta.dirname,"..");if(!Zr(ze(t,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Zr(ze(t,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await Hu()}let n=vP(),r=ue(),i=process.env.ZDOTDIR??n,s=_r(),o=Nb(s),a=process.env.WT_PROFILE_ID,u={root:t,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...a?{wtProfile:a}:{}},c=Mt(process.env),l=ld(u,s).filter((S)=>S===c||br[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=v$(r);if(e.yes&&f){await E$(f,u,s,!1);return}if(e.yes){if(l.length===0)throw Error(`no supported terminal detected — run this inside ${Ce(ld(u,s)).map((R)=>R.name.toLowerCase()).join(", ").replace(/, ([^,]*)$/," or $1")}`);let k=Cu({terminals:l,palettes:[]},u),N=cd(k,s);fd(k),xP(k,N);return}if(Go("ttheme init"),f){let S=PP(r);if(Lu(await An({message:`ttheme${S?` ${S}`:""} is installed — ${I$(f)}
543
+ ${S===et.version?"Reinstall":"Update to"} ${et.version} and keep all of it?`,active:"Yes",inactive:"No, set it up again",initialValue:!0}))){await E$(f,u,s,!0);return}}let d=await RP(c,f?.terminals??l,u,s),h=f?SP(f,u):dd(t),g=f?await sd(h,f.palettes,"palette",!0):await sd(h,[],"series",!0);if(!g)throw ni("Nothing changed"),new yr;let b=(f&&S$(f,g))??g[0],p=g.length>1&&(Vt[c].paints||c==="warp"&&d.includes("warp")&&Zr(mr(n,r))),m=Lu(await An({message:p?"Pick a default palette in ttheme preview once installed?":`Wear ${b} in every tab?`,initialValue:f?!f.off:!0})),$={terminals:d,palettes:g,off:!m},E=f?IP(f,$,u):Cu($,u);if(vr([`Install ${g.length} palettes — ${N$(h,g).join(", ")}`,`Copy ${E.copies.length} files under ${r}`,`Write ${E.settings.file}`,...E.edits.map((S)=>`Edit ${S.file} — a ttheme block: source ttheme.zsh`),...Hb(r,E.installed,n),"Each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",m?p?`Open ttheme preview — every tab wears the palette picked there, ${b} until then`:`Paint every tab with ${b}, this one now`:"Leave the terminal colors as they are — `ttheme on` wears a palette later",...m&&b?Ce(d).flatMap((S)=>S.defaults?[`Make "${S.defaults.profile(b)}" the ${S.name} default profile`]:[]):[]].join(`
544
+ `),`Wiring ${Ce(d).map((S)=>S.name).join(", ")}`),!Lu(await An({message:"Apply these changes?"})))throw ni("Nothing changed"),new yr;let M=cd(E,s);if(fd(E),await xu(r,P$(!0),n),m&&p)TP(r);let w=ne(r);HP({...E,catalog:h,installed:w},$,OP(h,w,r),M)}import{existsSync as O$,rmSync as AP,utimesSync as LP}from"node:fs";import{homedir as CP}from"node:os";import{join as No}from"node:path";function _P(e){try{return ne(e)}catch{return}}function GP(e){let{home:t,configHome:n}=e,r=_P(n),i={configHome:n,home:t},s=Ce(St),o=s.map((u)=>u.unwire(i,r)),a=[No(n,"ttheme"),e.cacheDir,e.stateDir];return{edits:[...fn(No(e.zdotdir,".zshrc"),fr),...o.flatMap((u)=>u.edits)],removals:[...s.flatMap((u)=>u.shelf?Fa(u.shelf.dir(i)):[]),...o.flatMap((u)=>u.removals),...a.filter((u)=>O$(u))],touches:o.flatMap((u)=>u.touches),...r?{state:r}:{}}}function WP(e,t,n=_r()){let r=[];for(let{file:s,content:o}of e.edits){let a=$h(s,o);r.push(a==="removed"?`Removed ${s} — ttheme had created it`:a==="restored"?`Took ttheme out of ${s}`:`Took ttheme out of ${s} — kept ${s}.ttheme.bak, since the file changed after ttheme's first edit`)}if(e.state){let s=Qs(t.configHome,{...e.state,off:!0,palettes:[]},!1,n,t.home);for(let o of Ce(e.state.terminals))if(s.has(o.id))r.push(`Gave ${o.name} its own default profile back — it takes it at its next start`)}for(let s of e.removals)AP(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)LP(s,i,i);return r}function UP(){let e=CP();return{home:e,configHome:ue(),zdotdir:process.env.ZDOTDIR??e,cacheDir:bi(),stateDir:No(process.env.XDG_STATE_HOME??No(e,".local","state"),"ttheme")}}async function F$(e=!1){let t=UP(),n=GP(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=No(t.configHome,"ttheme");Go("ttheme uninstall"),vr([...n.edits.map((s)=>`Take ttheme out of ${s.file}`),...n.removals.map((s)=>s===r?`Delete ${s} — settings, pins, every installed picture${O$($a(t.configHome))?`, and your markets under ${$a(t.configHome)} (push them to GitHub first to keep them)`:""}`:`Delete ${s}`)].join(`
545
+ `),"Uninstall");let i=await An({message:"Remove ttheme?"});if(ht(i)||!i)throw ni("Nothing changed"),new yr}for(let r of WP(n,t))console.log(r);console.log("Open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var KP=new Set(["add","remove","market","default","on","off"]),BP={default:([e])=>D0(e),on:()=>e$(),off:()=>t$(),browse:()=>a$(),list:([e],{json:t})=>i$(e,t),add:(e,{market:t})=>Z0(e,t),remove:(e)=>X0(e),update:()=>s$(),market:([e,t])=>cw(e,t),new:([e],{from:t,in:n})=>q0(e,t,n),edit:([e])=>z0(e),check:([e],{fix:t})=>Y0(e,t),share:([e])=>Q0(e),init:(e,{yes:t})=>R$({yes:t}),uninstall:(e,{yes:t})=>F$(t),info:()=>$$(),build:(e,{only:t})=>Hu({only:t}),find:([e])=>A0(e),image:([e,t,n])=>g$(e,t,n),redraw:()=>d$(),flatten:([e,t,n,r,i,s])=>b$(e,t,n,r,i,s),bake:([e,t,n,r])=>p$(e,t,n,r)},JP=Gs.map((e)=>({...e,run:BP[e.name]}));class Xr extends Error{verb;constructor(e,t){super(e);this.verb=t}}function T$(e){let t=JP.find((n)=>n.name===e);if(!t)throw new Xr(e.startsWith("-")?`unknown option '${e}'`:`unknown command '${e}'`);return t}function qP(e,t){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:s,multiple:o}]of Object.entries(e.flags??{}))n[r]={type:i,multiple:o===!0,...s?{short:s}:{}};try{return jP({args:t,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Xr(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,e)}}function zP(e){let[t,...n]=e;if(t===void 0)return{kind:"help",code:1};if(t==="-h"||t==="--help")return{kind:"help",code:0};if(t==="-V"||t==="--version")return{kind:"version"};if(t==="help"){if(n[0]===void 0||n[0]==="all")return{kind:"help",all:n[0]==="all",code:0};return{kind:"help",verb:T$(n[0]),code:0}}let r=T$(t),i=qP(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 Xr(`--${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 Xr(`missing ${r.args[s.length]}`,r);if(s.length>a)throw new Xr(`too many arguments: ${s.slice(a).join(" ")}`,r);let{help:u,...c}=i.values;return{kind:"run",verb:r,args:s,flags:c}}function H$(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>` ${n.padEnd(t)} ${r}`)}function gd(e,t=!1){if(!e)return Ws(t);let n=Object.entries(e.flags??{}).map(([r,{short:i,value:s,about:o}])=>[`${i?`-${i}, `:""}--${r}${s?` ${s}`:""}`,o]);return[`Usage: ttheme ${_s(e)}`,"",e.about,...e.actions?["","Actions:",...H$(e.actions)]:[],...n.length>0?["","Options:",...H$(n)]:[]].join(`
546
+ `)}var VP=[TypeError,RangeError,ReferenceError,SyntaxError];function YP(e){return VP.some((t)=>e instanceof t)||e instanceof Error&&"code"in e}async function x$(e){let t;try{let n=zP(e);if(n.kind==="version")return console.log(et.version),0;if(n.kind==="help"){if(n.code===0)console.log(gd(n.verb,n.all));else console.error(gd(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(KP.has(n.verb.name))await zb();let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Xr)return console.error(n.verb?`ttheme ${n.verb.name}: ${n.message}
546
547
 
547
- ${fd(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof yr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
548
- ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(AP)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=xP(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await R$(process.argv.slice(2));
548
+ ${gd(n.verb)}`:`ttheme: ${n.message} — see \`ttheme help\``),1;if(n instanceof yr)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
549
+ ttheme${t?` ${t.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}${YP(n)?"\nReport a bug with the output of `ttheme info`":""}`),1}}if(ZP)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let e=QP(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=e.status??1}else process.exitCode=await x$(process.argv.slice(2));
549
550
 
550
- //# debugId=079D476914565EBC64756E2164756E21
551
+ //# debugId=A9DB7320F495A89064756E2164756E21
551
552
  //# sourceMappingURL=ttheme.js.map