@kecan0406/ttheme 1.0.35 → 1.0.37
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/README.md +103 -616
- package/bin/ttheme.js +116 -116
- package/bin/ttheme.js.map +1 -1
- package/dist/manifest.json +1324 -856
- package/package.json +1 -1
- package/shell/launch-tab.zsh +3 -1
- package/shell/ttheme.zsh +7 -4
package/bin/ttheme.js
CHANGED
|
@@ -1,65 +1,65 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as Zf}from"node:module";var Tf=Object.create;var{getPrototypeOf:Uf,defineProperty:us,getOwnPropertyNames:Kf}=Object;var Af=Object.prototype.hasOwnProperty;function Jf(t){return this[t]}var Wf,Qf,vr=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var i=e?Wf??=new WeakMap:Qf??=new WeakMap,o=i.get(t);if(o)return o}n=t!=null?Tf(Uf(t)):{};let s=e||!t||!t.__esModule?us(n,"default",{value:t,enumerable:!0}):n;for(let c of Kf(t))if(!Af.call(s,c))us(s,c,{get:Jf.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var bt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Pt=Zf(import.meta.url);var vs=bt((Hw,Fr)=>{var ys=ys||function(t){return Buffer.from(t).toString("base64")};function Vf(t){var e=this,n=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,a,f,l=Array(65535),m=Array(65535),b=Array(64),g=Array(64),$=[],y=0,F=7,E=Array(64),M=Array(64),p=Array(64),R=Array(256),k=Array(2048),j,H=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],P=[0,1,2,3,4,5,6,7,8,9,10,11],X=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],K=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Et=[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 dt(d){var G=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var J=0;J<64;J++){var U=r((G[J]*d+50)/100);if(U<1)U=1;else if(U>255)U=255;i[H[J]]=U}var q=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var x=0;x<64;x++){var rt=r((q[x]*d+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[H[x]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var wt=0;wt<8;wt++)for(var v=0;v<8;v++)s[St]=1/(i[H[St]]*it[wt]*it[v]*8),c[St]=1/(o[H[St]]*it[wt]*it[v]*8),St++}function B(d,G){var J=0,U=0,q=[];for(var x=1;x<=16;x++){for(var rt=1;rt<=d[x];rt++)q[G[U]]=[],q[G[U]][0]=J,q[G[U]][1]=x,U++,J++;J*=2}return q}function Nt(){u=B(L,P),h=B(Ft,A),a=B(X,K),f=B(z,Et)}function ot(){var d=1,G=2;for(var J=1;J<=15;J++){for(var U=d;U<G;U++)m[32767+U]=J,l[32767+U]=[],l[32767+U][1]=J,l[32767+U][0]=U;for(var q=-(G-1);q<=-d;q++)m[32767+q]=J,l[32767+q]=[],l[32767+q][1]=J,l[32767+q][0]=G-1+q;d<<=1,G<<=1}}function tt(){for(var d=0;d<256;d++)k[d]=19595*d,k[d+256>>0]=38470*d,k[d+512>>0]=7471*d+32768,k[d+768>>0]=-11059*d,k[d+1024>>0]=-21709*d,k[d+1280>>0]=32768*d+8421375,k[d+1536>>0]=-27439*d,k[d+1792>>0]=-5329*d}function C(d){var G=d[0],J=d[1]-1;while(J>=0){if(G&1<<J)y|=1<<F;if(J--,F--,F<0){if(y==255)w(255),w(0);else w(y);F=7,y=0}}}function w(d){$.push(d)}function T(d){w(d>>8&255),w(d&255)}function ht(d,G){var J,U,q,x,rt,it,St,wt,v=0,O,Z=8,yt=64;for(O=0;O<Z;++O){J=d[v],U=d[v+1],q=d[v+2],x=d[v+3],rt=d[v+4],it=d[v+5],St=d[v+6],wt=d[v+7];var _=J+wt,D=J-wt,ft=U+St,W=U-St,st=q+it,jt=q-it,kt=x+rt,_t=x-rt,ne=_+kt,He=_-kt,qe=ft+st,xe=ft-st;d[v]=ne+qe,d[v+4]=ne-qe;var $n=(xe+He)*0.707106781;d[v+2]=He+$n,d[v+6]=He-$n,ne=_t+jt,qe=jt+W,xe=W+D;var kn=(ne-xe)*0.382683433,$r=0.5411961*ne+kn,En=1.306562965*xe+kn,yn=qe*0.707106781,vn=D+yn,Mn=D-yn;d[v+5]=Mn+$r,d[v+3]=Mn-$r,d[v+1]=vn+En,d[v+7]=vn-En,v+=8}v=0;for(O=0;O<Z;++O){J=d[v],U=d[v+8],q=d[v+16],x=d[v+24],rt=d[v+32],it=d[v+40],St=d[v+48],wt=d[v+56];var Vo=J+wt,pi=J-wt,Yo=U+St,zo=U-St,Bo=q+it,Do=q-it,ts=x+rt,Lf=x-rt,Sn=Vo+ts,wi=Vo-ts,kr=Yo+Bo,Er=Yo-Bo;d[v]=Sn+kr,d[v+32]=Sn-kr;var es=(Er+wi)*0.707106781;d[v+16]=wi+es,d[v+48]=wi-es,Sn=Lf+Do,kr=Do+zo,Er=zo+pi;var ns=(Sn-Er)*0.382683433,rs=0.5411961*Sn+ns,is=1.306562965*Er+ns,os=kr*0.707106781,ss=pi+os,cs=pi-os;d[v+40]=cs+rs,d[v+24]=cs-rs,d[v+8]=ss+is,d[v+56]=ss-is,v++}var yr;for(O=0;O<yt;++O)yr=d[O]*G[O],b[O]=yr>0?yr+0.5|0:yr-0.5|0;return b}function at(){T(65504),T(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),T(1),T(1),w(0),w(0)}function et(d){if(!d)return;if(T(65505),d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102)T(d.length+2);else T(d.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var G=0;G<d.length;G++)w(d[G])}function nt(d,G){T(65472),T(17),w(8),T(G),T(d),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function V(){T(65499),T(132),w(0);for(var d=0;d<64;d++)w(i[d]);w(1);for(var G=0;G<64;G++)w(o[G])}function N(){T(65476),T(418),w(0);for(var d=0;d<16;d++)w(L[d+1]);for(var G=0;G<=11;G++)w(P[G]);w(16);for(var J=0;J<16;J++)w(X[J+1]);for(var U=0;U<=161;U++)w(K[U]);w(1);for(var q=0;q<16;q++)w(Ft[q+1]);for(var x=0;x<=11;x++)w(A[x]);w(17);for(var rt=0;rt<16;rt++)w(z[rt+1]);for(var it=0;it<=161;it++)w(Et[it])}function I(d){if(typeof d>"u"||d.constructor!==Array)return;d.forEach((G)=>{if(typeof G!=="string")return;T(65534);var J=G.length;T(J+2);var U;for(U=0;U<J;U++)w(G.charCodeAt(U))})}function pt(){T(65498),T(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function Q(d,G,J,U,q){var x=q[0],rt=q[240],it,St=16,wt=63,v=64,O=ht(d,G);for(var Z=0;Z<v;++Z)g[H[Z]]=O[Z];var yt=g[0]-J;if(J=g[0],yt==0)C(U[0]);else it=32767+yt,C(U[m[it]]),C(l[it]);var _=63;for(;_>0&&g[_]==0;_--);if(_==0)return C(x),J;var D=1,ft;while(D<=_){var W=D;for(;g[D]==0&&D<=_;++D);var st=D-W;if(st>=St){ft=st>>4;for(var jt=1;jt<=ft;++jt)C(rt);st=st&15}it=32767+g[D],C(q[(st<<4)+m[it]]),C(l[it]),D++}if(_!=wt)C(x);return J}function Y(){var d=String.fromCharCode;for(var G=0;G<256;G++)R[G]=d(G)}this.encode=function(d,G){var J=new Date().getTime();if(G)xt(G);$=[],y=0,F=7,T(65496),at(),I(d.comments),et(d.exifBuffer),V(),nt(d.width,d.height),N(),pt();var U=0,q=0,x=0;y=0,F=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=d,wt=it*4,v=it*3,O,Z=0,yt,_,D,ft,W,st,jt,kt;while(Z<St){O=0;while(O<wt){ft=wt*Z+O,W=ft,st=-1,jt=0;for(kt=0;kt<64;kt++){if(jt=kt>>3,st=(kt&7)*4,W=ft+jt*wt+st,Z+jt>=St)W-=wt*(Z+1+jt-St);if(O+st>=wt)W-=O+st-wt+4;yt=rt[W++],_=rt[W++],D=rt[W++],E[kt]=(k[yt]+k[_+256>>0]+k[D+512>>0]>>16)-128,M[kt]=(k[yt+768>>0]+k[_+1024>>0]+k[D+1280>>0]>>16)-128,p[kt]=(k[yt+1280>>0]+k[_+1536>>0]+k[D+1792>>0]>>16)-128}U=Q(E,s,U,u,a),q=Q(M,c,q,h,f),x=Q(p,c,x,h,f),O+=32}Z+=8}if(F>=0){var _t=[];_t[1]=F+1,_t[0]=(1<<F+1)-1,C(_t)}if(T(65497),typeof Fr>"u")return new Uint8Array($);return Buffer.from($);var ne,He};function xt(d){if(d<=0)d=1;if(d>100)d=100;if(j==d)return;var G=0;if(d<50)G=Math.floor(5000/d);else G=Math.floor(200-d*2);dt(G),j=d}function Yt(){var d=new Date().getTime();if(!t)t=50;Y(),Nt(),ot(),tt(),xt(t);var G=new Date().getTime()-d}Yt()}if(typeof Fr<"u")Fr.exports=Es;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Es;function Es(t,e){if(typeof e>"u")e=50;var n=new Vf(e),r=n.encode(t,e);return{data:r,width:t.width,height:t.height}}});var Ss=bt((Ow,yi)=>{var Ei=function(){var e=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function a(){}function f(F,E){var M=0,p=[],R,k,j=16;while(j>0&&!F[j-1])j--;p.push({children:[],index:0});var H=p[0],L;for(R=0;R<j;R++){for(k=0;k<F[R];k++){H=p.pop(),H.children[H.index]=E[M];while(H.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");H=p.pop()}H.index++,p.push(H);while(p.length<=R)p.push(L={children:[],index:0}),H.children[H.index]=L.children,H=L;M++}if(R+1<j)p.push(L={children:[],index:0}),H.children[H.index]=L.children,H=L}return p[0].children}function l(F,E,M,p,R,k,j,H,L,P){var{precision:X,samplesPerLine:K,scanLines:Ft,mcusPerLine:A,progressive:z,maxH:Et,maxV:dt}=M,B=E,Nt=0,ot=0;function tt(){if(ot>0)return ot--,Nt>>ot&1;if(Nt=F[E++],Nt==255){var v=F[E++];if(v)throw Error("unexpected marker: "+(Nt<<8|v).toString(16))}return ot=7,Nt>>>7}function C(v){var O=v,Z;while((Z=tt())!==null){if(O=O[Z],typeof O==="number")return O;if(typeof O!=="object")throw Error("invalid huffman sequence")}return null}function w(v){var O=0;while(v>0){var Z=tt();if(Z===null)return;O=O<<1|Z,v--}return O}function T(v){var O=w(v);if(O>=1<<v-1)return O;return O+(-1<<v)+1}function ht(v,O){var Z=C(v.huffmanTableDC),yt=Z===0?0:T(Z);O[0]=v.pred+=yt;var _=1;while(_<64){var D=C(v.huffmanTableAC),ft=D&15,W=D>>4;if(ft===0){if(W<15)break;_+=16;continue}_+=W;var st=e[_];O[st]=T(ft),_++}}function at(v,O){var Z=C(v.huffmanTableDC),yt=Z===0?0:T(Z)<<L;O[0]=v.pred+=yt}function et(v,O){O[0]|=tt()<<L}var nt=0;function V(v,O){if(nt>0){nt--;return}var Z=k,yt=j;while(Z<=yt){var _=C(v.huffmanTableAC),D=_&15,ft=_>>4;if(D===0){if(ft<15){nt=w(ft)+(1<<ft)-1;break}Z+=16;continue}Z+=ft;var W=e[Z];O[W]=T(D)*(1<<L),Z++}}var N=0,I;function pt(v,O){var Z=k,yt=j,_=0;while(Z<=yt){var D=e[Z],ft=O[D]<0?-1:1;switch(N){case 0:var W=C(v.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)nt=w(_)+(1<<_),N=4;else _=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");I=T(st),N=_?2:3}continue;case 1:case 2:if(O[D])O[D]+=(tt()<<L)*ft;else if(_--,_===0)N=N==2?3:0;break;case 3:if(O[D])O[D]+=(tt()<<L)*ft;else O[D]=I<<L,N=0;break;case 4:if(O[D])O[D]+=(tt()<<L)*ft;break}Z++}if(N===4){if(nt--,nt===0)N=0}}function Q(v,O,Z,yt,_){var D=Z/A|0,ft=Z%A,W=D*v.v+yt,st=ft*v.h+_;if(v.blocks[W]===void 0&&P.tolerantDecoding)return;O(v,v.blocks[W][st])}function Y(v,O,Z){var yt=Z/v.blocksPerLine|0,_=Z%v.blocksPerLine;if(v.blocks[yt]===void 0&&P.tolerantDecoding)return;O(v,v.blocks[yt][_])}var xt=p.length,Yt,d,G,J,U,q;if(z)if(k===0)q=H===0?at:et;else q=H===0?V:pt;else q=ht;var x=0,rt,it;if(xt==1)it=p[0].blocksPerLine*p[0].blocksPerColumn;else it=A*M.mcusPerColumn;if(!R)R=it;var St,wt;while(x<it){for(d=0;d<xt;d++)p[d].pred=0;if(nt=0,xt==1){Yt=p[0];for(U=0;U<R;U++)Y(Yt,q,x),x++}else for(U=0;U<R;U++){for(d=0;d<xt;d++){Yt=p[d],St=Yt.h,wt=Yt.v;for(G=0;G<wt;G++)for(J=0;J<St;J++)Q(Yt,q,x,G,J)}if(x++,x===it)break}if(x===it)do{if(F[E]===255){if(F[E+1]!==0)break}E+=1}while(E<F.length-2);if(ot=0,rt=F[E]<<8|F[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function m(F,E){var M=[],p=E.blocksPerLine,R=E.blocksPerColumn,k=p<<3,j=new Int32Array(64),H=new Uint8Array(64);function L(B,Nt,ot){var tt=E.quantizationTable,C,w,T,ht,at,et,nt,V,N,I=ot,pt;for(pt=0;pt<64;pt++)I[pt]=B[pt]*tt[pt];for(pt=0;pt<8;++pt){var Q=8*pt;if(I[1+Q]==0&&I[2+Q]==0&&I[3+Q]==0&&I[4+Q]==0&&I[5+Q]==0&&I[6+Q]==0&&I[7+Q]==0){N=u*I[0+Q]+512>>10,I[0+Q]=N,I[1+Q]=N,I[2+Q]=N,I[3+Q]=N,I[4+Q]=N,I[5+Q]=N,I[6+Q]=N,I[7+Q]=N;continue}C=u*I[0+Q]+128>>8,w=u*I[4+Q]+128>>8,T=I[2+Q],ht=I[6+Q],at=h*(I[1+Q]-I[7+Q])+128>>8,V=h*(I[1+Q]+I[7+Q])+128>>8,et=I[3+Q]<<4,nt=I[5+Q]<<4,N=C-w+1>>1,C=C+w+1>>1,w=N,N=T*c+ht*s+128>>8,T=T*s-ht*c+128>>8,ht=N,N=at-nt+1>>1,at=at+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=C-ht+1>>1,C=C+ht+1>>1,ht=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=at*o+V*i+2048>>12,at=at*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+Q]=C+V,I[7+Q]=C-V,I[1+Q]=w+nt,I[6+Q]=w-nt,I[2+Q]=T+et,I[5+Q]=T-et,I[3+Q]=ht+at,I[4+Q]=ht-at}for(pt=0;pt<8;++pt){var Y=pt;if(I[8+Y]==0&&I[16+Y]==0&&I[24+Y]==0&&I[32+Y]==0&&I[40+Y]==0&&I[48+Y]==0&&I[56+Y]==0){N=u*ot[pt+0]+8192>>14,I[0+Y]=N,I[8+Y]=N,I[16+Y]=N,I[24+Y]=N,I[32+Y]=N,I[40+Y]=N,I[48+Y]=N,I[56+Y]=N;continue}C=u*I[0+Y]+2048>>12,w=u*I[32+Y]+2048>>12,T=I[16+Y],ht=I[48+Y],at=h*(I[8+Y]-I[56+Y])+2048>>12,V=h*(I[8+Y]+I[56+Y])+2048>>12,et=I[24+Y],nt=I[40+Y],N=C-w+1>>1,C=C+w+1>>1,w=N,N=T*c+ht*s+2048>>12,T=T*s-ht*c+2048>>12,ht=N,N=at-nt+1>>1,at=at+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=C-ht+1>>1,C=C+ht+1>>1,ht=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=at*o+V*i+2048>>12,at=at*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+Y]=C+V,I[56+Y]=C-V,I[8+Y]=w+nt,I[48+Y]=w-nt,I[16+Y]=T+et,I[40+Y]=T-et,I[24+Y]=ht+at,I[32+Y]=ht-at}for(pt=0;pt<64;++pt){var xt=128+(I[pt]+8>>4);Nt[pt]=xt<0?0:xt>255?255:xt}}y(k*R*8);var P,X;for(var K=0;K<R;K++){var Ft=K<<3;for(P=0;P<8;P++)M.push(new Uint8Array(k));for(var A=0;A<p;A++){L(E.blocks[K][A],H,j);var z=0,Et=A<<3;for(X=0;X<8;X++){var dt=M[Ft+X];for(P=0;P<8;P++)dt[Et+P]=H[z++]}}}return M}function b(F){return F<0?0:F>255?255:F}a.prototype={load:function(E){var M=new XMLHttpRequest;M.open("GET",E,!0),M.responseType="arraybuffer",M.onload=function(){var p=new Uint8Array(M.response||M.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),M.send(null)},parse:function(E){var M=this.opts.maxResolutionInMP*1000*1000,p=0,R=E.length;function k(){var W=E[p]<<8|E[p+1];return p+=2,W}function j(){var W=k(),st=E.subarray(p,p+W-2);return p+=st.length,st}function H(W){var st=1,jt=1,kt,_t;for(_t in W.components)if(W.components.hasOwnProperty(_t)){if(kt=W.components[_t],st<kt.h)st=kt.h;if(jt<kt.v)jt=kt.v}var ne=Math.ceil(W.samplesPerLine/8/st),He=Math.ceil(W.scanLines/8/jt);for(_t in W.components)if(W.components.hasOwnProperty(_t)){kt=W.components[_t];var qe=Math.ceil(Math.ceil(W.samplesPerLine/8)*kt.h/st),xe=Math.ceil(Math.ceil(W.scanLines/8)*kt.v/jt),$n=ne*kt.h,kn=He*kt.v,$r=kn*$n,En=[];y($r*256);for(var yn=0;yn<kn;yn++){var vn=[];for(var Mn=0;Mn<$n;Mn++)vn.push(new Int32Array(64));En.push(vn)}kt.blocksPerLine=qe,kt.blocksPerColumn=xe,kt.blocks=En}W.maxH=st,W.maxV=jt,W.mcusPerLine=ne,W.mcusPerColumn=He}var L=null,P=null,X=null,K,Ft,A=[],z=[],Et=[],dt=[],B=k(),Nt=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=k();while(B!=65497){var ot,tt,C;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=j();if(B===65534){var T=String.fromCharCode.apply(null,w);this.comments.push(T)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)L={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)P={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ht=k(),at=ht+p-2;while(p<at){var et=E[p++];y(256);var nt=new Int32Array(64);if(et>>4===0)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=E[p++]}else if(et>>4===1)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=k()}else throw Error("DQT: invalid table spec");A[et&15]=nt}break;case 65472:case 65473:case 65474:k(),K={},K.extended=B===65473,K.progressive=B===65474,K.precision=E[p++],K.scanLines=k(),K.samplesPerLine=k(),K.components={},K.componentsOrder=[];var N=K.scanLines*K.samplesPerLine;if(N>M){var I=Math.ceil((N-M)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var pt=E[p++],Q,Y=0,xt=0;for(ot=0;ot<pt;ot++){Q=E[p];var Yt=E[p+1]>>4,d=E[p+1]&15,G=E[p+2];if(Yt<=0||d<=0)throw Error("Invalid sampling factor, expected values above 0");K.componentsOrder.push(Q),K.components[Q]={h:Yt,v:d,quantizationIdx:G},p+=3}H(K),z.push(K);break;case 65476:var J=k();for(ot=2;ot<J;){var U=E[p++],q=new Uint8Array(16),x=0;for(tt=0;tt<16;tt++,p++)x+=q[tt]=E[p];y(16+x);var rt=new Uint8Array(x);for(tt=0;tt<x;tt++,p++)rt[tt]=E[p];ot+=17+x,(U>>4===0?dt:Et)[U&15]=f(q,rt)}break;case 65501:k(),Ft=k();break;case 65500:k(),k();break;case 65498:var it=k(),St=E[p++],wt=[],v;for(ot=0;ot<St;ot++){v=K.components[E[p++]];var O=E[p++];v.huffmanTableDC=dt[O>>4],v.huffmanTableAC=Et[O&15],wt.push(v)}var Z=E[p++],yt=E[p++],_=E[p++],D=l(E,p,K,wt,Ft,Z,yt,_>>4,_&15,this.opts);p+=D;break;case 65535:if(E[p]!==255)p--;break;default:if(E[p-3]==255&&E[p-2]>=192&&E[p-2]<=254){p-=3;break}else if(B===224||B==225){if(Nt!==-1)throw Error(`first unknown JPEG marker at offset ${Nt.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${(p-1).toString(16)}`);Nt=p-1;let W=k();if(E[p+W-2]===255){p+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=k()}if(z.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<z.length;ot++){var ft=z[ot].components;for(var tt in ft)ft[tt].quantizationTable=A[ft[tt].quantizationIdx],delete ft[tt].quantizationIdx}this.width=K.samplesPerLine,this.height=K.scanLines,this.jfif=L,this.adobe=P,this.components=[];for(var ot=0;ot<K.componentsOrder.length;ot++){var v=K.components[K.componentsOrder[ot]];this.components.push({lines:m(K,v),scaleX:v.h/K.maxH,scaleY:v.v/K.maxV})}},getData:function(E,M){var p=this.width/E,R=this.height/M,k,j,H,L,P,X,K,Ft,A,z,Et=0,dt,B,Nt,ot,tt,C,w,T,ht,at,et,nt=E*M*this.components.length;y(nt);var V=new Uint8Array(nt);switch(this.components.length){case 1:k=this.components[0];for(z=0;z<M;z++){P=k.lines[0|z*k.scaleY*R];for(A=0;A<E;A++)dt=P[0|A*k.scaleX*p],V[Et++]=dt}break;case 2:k=this.components[0],j=this.components[1];for(z=0;z<M;z++){P=k.lines[0|z*k.scaleY*R],X=j.lines[0|z*j.scaleY*R];for(A=0;A<E;A++)dt=P[0|A*k.scaleX*p],V[Et++]=dt,dt=X[0|A*j.scaleX*p],V[Et++]=dt}break;case 3:if(et=!0,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],j=this.components[1],H=this.components[2];for(z=0;z<M;z++){P=k.lines[0|z*k.scaleY*R],X=j.lines[0|z*j.scaleY*R],K=H.lines[0|z*H.scaleY*R];for(A=0;A<E;A++){if(!et)T=P[0|A*k.scaleX*p],ht=X[0|A*j.scaleX*p],at=K[0|A*H.scaleX*p];else dt=P[0|A*k.scaleX*p],B=X[0|A*j.scaleX*p],Nt=K[0|A*H.scaleX*p],T=b(dt+1.402*(Nt-128)),ht=b(dt-0.3441363*(B-128)-0.71413636*(Nt-128)),at=b(dt+1.772*(B-128));V[Et++]=T,V[Et++]=ht,V[Et++]=at}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(et=!1,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],j=this.components[1],H=this.components[2],L=this.components[3];for(z=0;z<M;z++){P=k.lines[0|z*k.scaleY*R],X=j.lines[0|z*j.scaleY*R],K=H.lines[0|z*H.scaleY*R],Ft=L.lines[0|z*L.scaleY*R];for(A=0;A<E;A++){if(!et)tt=P[0|A*k.scaleX*p],C=X[0|A*j.scaleX*p],w=K[0|A*H.scaleX*p],ot=Ft[0|A*L.scaleX*p];else dt=P[0|A*k.scaleX*p],B=X[0|A*j.scaleX*p],Nt=K[0|A*H.scaleX*p],ot=Ft[0|A*L.scaleX*p],tt=255-b(dt+1.402*(Nt-128)),C=255-b(dt-0.3441363*(B-128)-0.71413636*(Nt-128)),w=255-b(dt+1.772*(B-128));V[Et++]=255-tt,V[Et++]=255-C,V[Et++]=255-w,V[Et++]=255-ot}}break;default:throw Error("Unsupported color mode")}return V},copyToImageData:function(E,M){var{width:p,height:R,data:k}=E,j=this.getData(p,R),H=0,L=0,P,X,K,Ft,A,z,Et,dt,B;switch(this.components.length){case 1:for(X=0;X<R;X++)for(P=0;P<p;P++)if(K=j[H++],k[L++]=K,k[L++]=K,k[L++]=K,M)k[L++]=255;break;case 3:for(X=0;X<R;X++)for(P=0;P<p;P++)if(Et=j[H++],dt=j[H++],B=j[H++],k[L++]=Et,k[L++]=dt,k[L++]=B,M)k[L++]=255;break;case 4:for(X=0;X<R;X++)for(P=0;P<p;P++)if(A=j[H++],z=j[H++],K=j[H++],Ft=j[H++],Et=255-b(A*(1-Ft/255)+Ft),dt=255-b(z*(1-Ft/255)+Ft),B=255-b(K*(1-Ft/255)+Ft),k[L++]=Et,k[L++]=dt,k[L++]=B,M)k[L++]=255;break;default:throw Error("Unsupported color mode")}}};var g=0,$=0;function y(F=0){var E=g+F;if(E>$){var M=Math.ceil((E-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${M}MB`)}g=E}return a.resetMaxMemoryUsage=function(F){g=0,$=F},a.getBytesAllocated=function(){return g},a.requestMemoryAllocation=y,a}();if(typeof yi<"u")yi.exports=Ms;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Ms;function Ms(t,e={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...e},i=new Uint8Array(t),o=new Ei;o.opts=r,Ei.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{Ei.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var Fs=bt((jw,Is)=>{var Yf=vs(),zf=Ss();Is.exports={encode:Yf,decode:zf}});var vi=bt((Rw,Hs)=>{var Bf=Pt("util"),Ns=Pt("stream"),Bt=Hs.exports=function(){Ns.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Bf.inherits(Bt,Ns);Bt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Bt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(t))n=t;else n=Buffer.from(t,e||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Bt.prototype.end=function(t,e){if(t)this.write(t,e);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Bt.prototype.destroySoon=Bt.prototype.end;Bt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Bt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Bt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];if(e.length>t.length)this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length));else this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e)};Bt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);while(e<t.length){let i=this._buffers[n++],o=Math.min(i.length,t.length-e);if(i.copy(r,e,0,o),e+=o,o!==i.length)this._buffers[--n]=i.slice(o)}if(n>0)this._buffers.splice(0,n);this._buffered-=t.length,t.func.call(this,r)};Bt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var Mi=bt((Df)=>{var be=[{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]}];Df.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,o=(t-r)/8,s=(e-i)/8;for(let c=0;c<be.length;c++){let u=be[c],h=o*u.x.length,a=s*u.y.length;for(let f=0;f<u.x.length;f++)if(u.x[f]<r)h++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)a++;else break;if(h>0&&a>0)n.push({width:h,height:a,index:c})}return n};Df.getInterlaceIterator=function(t){return function(e,n,r){let i=e%be[r].x.length,o=(e-i)/be[r].x.length*8+be[r].x[i],s=n%be[r].y.length,c=(n-s)/be[r].y.length*8+be[r].y[s];return o*4+c*t*4}}});var Si=bt((Gw,Os)=>{Os.exports=function(e,n,r){let i=e+n-r,o=Math.abs(i-e),s=Math.abs(i-n),c=Math.abs(i-r);if(o<=s&&o<=c)return e;if(s<=c)return n;return r}});var Ii=bt((Lw,Rs)=>{var nl=Mi(),rl=Si();function js(t,e,n){let r=t*e;if(n!==8)r=Math.ceil(r/(8/n));return r}var Xe=Rs.exports=function(t,e){let{width:n,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let c=nl.getImagePasses(n,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:js(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:js(n,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Xe.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Xe.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let o=0;o<n;o++){let s=t[1+o],c=o>i?e[o-r]:0;e[o]=s+c}};Xe.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let o=t[1+i],s=r?r[i]:0;e[i]=o+s}};Xe.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=Math.floor((h+u)/2);e[s]=c+a}};Xe.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=s>i&&o?o[s-r]:0,f=rl(h,u,a);e[s]=c+f}};Xe.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw Error("Unrecognised filter type - "+e)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ls=bt((Tw,Gs)=>{var il=Pt("util"),Ps=vi(),ol=Ii(),sl=Gs.exports=function(t){Ps.call(this);let e=[],n=this;this._filter=new ol(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};il.inherits(sl,Ps)});var Ce=bt((Uw,Ts)=>{Ts.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 Hi=bt((Kw,Us)=>{var Fi=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)if(e&1)e=3988292384^e>>>1;else e=e>>>1;Fi[t]=e}})();var Ni=Us.exports=function(){this._crc=-1};Ni.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Fi[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ni.prototype.crc32=function(){return this._crc^-1};Ni.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Fi[(e^t[n])&255]^e>>>8;return e^-1}});var Oi=bt((Aw,Ks)=>{var Ht=Ce(),cl=Hi(),Ot=Ks.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Ht.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Ht.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Ht.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Ht.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Ht.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Ht.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Ht.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let e=Ht.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&n!==Ht.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new cl,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(Error("Crc error - "+e+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Ht.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Ht.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:Boolean(c),palette:Boolean(i&Ht.COLORTYPE_PALETTE),color:Boolean(i&Ht.COLORTYPE_COLOR),alpha:Boolean(i&Ht.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Ht.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}if(this._colorType===Ht.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Ht.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Ht.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Ht.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(e);let n=t-e.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var ji=bt((gl)=>{var As=Mi(),ul=[function(){},function(t,e,n,r){if(r===e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],hl=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function al(t,e){let n=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,a,f,l,m;switch(e){default:throw Error("unrecognised depth");case 16:l=t[r],r++,n.push((o<<8)+l);break;case 4:l=o&15,m=o>>4,n.push(m,l);break;case 2:a=o&3,f=o>>2&3,l=o>>4&3,m=o>>6&3,n.push(m,l,f,a);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,a=o>>4&1,f=o>>5&1,l=o>>6&1,m=o>>7&1,n.push(m,l,f,a,h,u,c,s);break}}return{get:function(o){while(n.length<o)i();let s=n.slice(0,o);return n=n.slice(o),s},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function fl(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let a=0;a<s;a++){let f=n(a,h,u);ul[r](e,i,f,o),o+=r}return o}function ll(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let a=0;a<s;a++){let f=i.get(r),l=n(a,h,u);hl[r](e,f,l,o)}i.resetAfterLine()}}gl.dataToBitMap=function(t,e){let{width:n,height:r,depth:i,bpp:o,interlace:s}=e,c;if(i!==8)c=al(t,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let h=Math.pow(2,i)-1,a=0,f,l;if(s)f=As.getImagePasses(n,r),l=As.getInterlaceIterator(n,r);else{let m=0;l=function(){let b=m;return m+=4,b},f=[{width:n,height:r}]}for(let m=0;m<f.length;m++)if(i===8)a=fl(f[m],u,l,o,t,a);else ll(f[m],u,l,o,c,h);if(i===8){if(a!==t.length)throw Error("extra data found")}else c.end();return u}});var Ri=bt((Ww,Js)=>{function ml(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)e[o+h]=u[h];o+=4}}function pl(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)e[o+h]=0;o+=4}}function wl(t,e,n,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<n;h++){for(let a=0;a<4;a++)e[c+a]=Math.floor(t[c+a]*o/s+0.5);c+=4}}Js.exports=function(t,e,n=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=e,h=t;if(s===3)ml(t,h,i,o,u);else{if(c)pl(t,h,i,o,c);if(r!==8&&!n){if(r===16)h=Buffer.alloc(i*o*4);wl(t,h,i,o,r)}}return h}});var Zs=bt((Qw,Qs)=>{var bl=Pt("util"),Pi=Pt("zlib"),Ws=vi(),$l=Ls(),kl=Oi(),El=ji(),yl=Ri(),ie=Qs.exports=function(t){Ws.call(this),this._parser=new kl(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};bl.inherits(ie,Ws);ie.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ie.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Pi.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,Pi.Z_MIN_CHUNK);this._inflate=Pi.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ie.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new $l(this._bitmapInfo)};ie.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ie.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ie.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ie.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ie.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ie.prototype._complete=function(t){if(this.errord)return;let e;try{let n=El.dataToBitMap(t,this._bitmapInfo);e=yl(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var xs=bt((Zw,qs)=>{var Xt=Ce();qs.exports=function(t,e,n,r){let i=[Xt.COLORTYPE_COLOR_ALPHA,Xt.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let b=function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&b)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Xt.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Xt.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(e*n*u),a=0,f=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function m(){let b,g,$,y=s;switch(r.inputColorType){case Xt.COLORTYPE_COLOR_ALPHA:y=o[a+3],b=o[a],g=o[a+1],$=o[a+2];break;case Xt.COLORTYPE_COLOR:b=o[a],g=o[a+1],$=o[a+2];break;case Xt.COLORTYPE_ALPHA:y=o[a+1],b=o[a],g=b,$=b;break;case Xt.COLORTYPE_GRAYSCALE:b=o[a],g=b,$=b;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,b=Math.min(Math.max(Math.round((1-y)*l.red+y*b),0),s),g=Math.min(Math.max(Math.round((1-y)*l.green+y*g),0),s),$=Math.min(Math.max(Math.round((1-y)*l.blue+y*$),0),s)}return{red:b,green:g,blue:$,alpha:y}}for(let b=0;b<n;b++)for(let g=0;g<e;g++){let $=m(o,a);switch(r.colorType){case Xt.COLORTYPE_COLOR_ALPHA:case Xt.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[f]=$.red,h[f+1]=$.green,h[f+2]=$.blue,i)h[f+3]=$.alpha}else if(h.writeUInt16BE($.red,f),h.writeUInt16BE($.green,f+2),h.writeUInt16BE($.blue,f+4),i)h.writeUInt16BE($.alpha,f+6);break;case Xt.COLORTYPE_ALPHA:case Xt.COLORTYPE_GRAYSCALE:{let y=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(h[f]=y,i)h[f+1]=$.alpha}else if(h.writeUInt16BE(y,f),i)h.writeUInt16BE($.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}a+=c,f+=u}return h}});var Cs=bt((qw,Xs)=>{var _s=Si();function vl(t,e,n,r,i){for(let o=0;o<n;o++)r[i+o]=t[e+o]}function Ml(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++)r+=Math.abs(t[o]);return r}function Sl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=t[e+s]-c;r[i+s]=u}}function Il(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=t[e+o]-s;i+=Math.abs(c)}return i}function Fl(t,e,n,r,i){for(let o=0;o<n;o++){let s=e>0?t[e+o-n]:0,c=t[e+o]-s;r[i+o]=c}}function Nl(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++){let s=e>0?t[o-n]:0,c=t[o]-s;r+=Math.abs(c)}return r}function Hl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=t[e+s]-(c+u>>1);r[i+s]=h}}function Ol(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=t[e+o]-(s+c>>1);i+=Math.abs(u)}return i}function jl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=e>0&&s>=o?t[e+s-(n+o)]:0,a=t[e+s]-_s(c,u,h);r[i+s]=a}}function Rl(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=e>0&&o>=r?t[e+o-(n+r)]:0,h=t[e+o]-_s(s,c,u);i+=Math.abs(h)}return i}var Pl={0:vl,1:Sl,2:Fl,3:Hl,4:jl},Gl={0:Ml,1:Il,2:Nl,3:Ol,4:Rl};Xs.exports=function(t,e,n,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=e*i,c=0,u=0,h=Buffer.alloc((s+1)*n),a=o[0];for(let f=0;f<n;f++){if(o.length>1){let l=1/0;for(let m=0;m<o.length;m++){let b=Gl[o[m]](t,u,s,i);if(b<l)a=o[m],l=b}}h[c]=a,c++,Pl[a](t,u,s,h,c,i),c+=s,u+=s}return h}});var Gi=bt((xw,Vs)=>{var Lt=Ce(),Ll=Hi(),Tl=xs(),Ul=Cs(),Kl=Pt("zlib"),$e=Vs.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Kl.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Lt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Lt.COLORTYPE_COLOR_ALPHA,[Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};$e.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};$e.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};$e.prototype.filterData=function(t,e,n){let r=Tl(t,e,n,this._options),i=Lt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Ul(r,e,n,this._options,i)};$e.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e)e.copy(r,8);return r.writeInt32BE(Ll.crc32(r.slice(4,r.length-4)),r.length-4),r};$e.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Lt.GAMMA_DIVISION),0),this._packChunk(Lt.TYPE_gAMA,e)};$e.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Lt.TYPE_IHDR,n)};$e.prototype.packIDAT=function(t){return this._packChunk(Lt.TYPE_IDAT,t)};$e.prototype.packIEND=function(){return this._packChunk(Lt.TYPE_IEND,null)}});var Ds=bt((_w,Bs)=>{var Al=Pt("util"),Ys=Pt("stream"),Jl=Ce(),Wl=Gi(),zs=Bs.exports=function(t){Ys.call(this);let e=t||{};this._packer=new Wl(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Al.inherits(zs,Ys);zs.prototype.pack=function(t,e,n,r){if(this.emit("data",Buffer.from(Jl.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var oc=bt((jn,ic)=>{var tc=Pt("assert").ok,Ve=Pt("zlib"),Ql=Pt("util"),ec=Pt("buffer").kMaxLength;function Oe(t){if(!(this instanceof Oe))return new Oe(t);if(t&&t.chunkSize<Ve.Z_MIN_CHUNK)t.chunkSize=Ve.Z_MIN_CHUNK;if(Ve.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function Zl(t){return new Oe(t)}function nc(t,e){if(e)process.nextTick(e);if(!t._handle)return;t._handle.close(),t._handle=null}Oe.prototype._processChunk=function(t,e,n){if(typeof n==="function")return Ve.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,a;this.on("error",function(b){a=b});function f(b,g){if(r._hadError)return;let $=o-g;if(tc($>=0,"have should not go down"),$>0){let y=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,y.length>s)y=y.slice(0,s);if(u.push(y),h+=y.length,s-=y.length,s===0)return!1}if(g===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(g===0)return c+=i-b,i=b,!0;return!1}tc(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(e,t,c,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&f(l[0],l[1]));if(this._hadError)throw a;if(h>=ec)throw nc(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+ec.toString(16)+" bytes");let m=Buffer.concat(u,h);return nc(this),m};Ql.inherits(Oe,Ve.Inflate);function ql(t,e){if(typeof e==="string")e=Buffer.from(e);if(!(e instanceof Buffer))throw TypeError("Not a string or buffer");let n=t._finishFlushFlag;if(n==null)n=Ve.Z_FINISH;return t._processChunk(e,n)}function rc(t,e){return ql(new Oe(e),t)}ic.exports=jn=rc;jn.Inflate=Oe;jn.createInflate=Zl;jn.inflateSync=rc});var Li=bt((Xw,cc)=>{var sc=cc.exports=function(t){this._buffer=t,this._reads=[]};sc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};sc.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var uc=bt((Xl)=>{var xl=Li(),_l=Ii();Xl.process=function(t,e){let n=[],r=new xl(t);return new _l(e,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var lc=bt((Vw,fc)=>{var hc=!0,ac=Pt("zlib"),Vl=oc();if(!ac.deflateSync)hc=!1;var Yl=Li(),zl=uc(),Bl=Oi(),Dl=ji(),tg=Ri();fc.exports=function(t,e){if(!hc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(M){n=M}let i;function o(M){i=M}function s(M){i.transColor=M}function c(M){i.palette=M}function u(){i.alpha=!0}let h;function a(M){h=M}let f=[];function l(M){f.push(M)}let m=new Yl(t);if(new Bl(e,{read:m.read.bind(m),error:r,metadata:o,gamma:a,palette:c,transColor:s,inflateData:l,simpleTransparency:u}).start(),m.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(i.interlace)$=ac.inflateSync(g);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=Vl(g,{chunkSize:p,maxLength:p})}if(g=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let y=zl.process($,i);g=null;let F=Dl.dataToBitMap(y,i);y=null;let E=tg(F,i,e.skipRescale);return i.data=E,i.gamma=h||0,i}});var pc=bt((Yw,mc)=>{var gc=!0,dc=Pt("zlib");if(!dc.deflateSync)gc=!1;var eg=Ce(),ng=Gi();mc.exports=function(t,e){if(!gc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new ng(e||{}),i=[];if(i.push(Buffer.from(eg.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=dc.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var wc=bt((og)=>{var rg=lc(),ig=pc();og.read=function(t,e){return rg(t,e||{})};og.write=function(t,e){return ig(t,e)}});var $c=bt((lg)=>{var ug=Pt("util"),bc=Pt("stream"),hg=Zs(),ag=Ds(),fg=wc(),Tt=lg.PNG=function(t){if(bc.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new hg(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new ag(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};ug.inherits(Tt,bc);Tt.sync=fg;Tt.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Tt.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};Tt.prototype.write=function(t){return this._parser.write(t),!0};Tt.prototype.end=function(t){this._parser.end(t)};Tt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Tt.prototype._gamma=function(t){this.gamma=t};Tt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Tt.bitblt=function(t,e,n,r,i,o,s,c){if(n|=0,r|=0,i|=0,o|=0,s|=0,c|=0,n>t.width||r>t.height||n+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>e.width||c>e.height||s+i>e.width||c+o>e.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(c+u)*e.width+s<<2,(r+u)*t.width+n<<2,(r+u)*t.width+n+i<<2)};Tt.prototype.bitblt=function(t,e,n,r,i,o,s){return Tt.bitblt(this,t,e,n,r,i,o,s),this};Tt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Tt.prototype.adjustGamma=function(){Tt.adjustGamma(this)}});var Ho=bt((Rk,Ta)=>{var No={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},qp={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},xp={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?No.up():"");if(t)e+=No.left;return e}};Ta.exports={cursor:No,scroll:qp,erase:xp,beep:"\x07"}});import{spawnSync as fw}from"node:child_process";import{isMainThread as lw}from"node:worker_threads";import{parseArgs as sw}from"node:util";var re={name:"@kecan0406/ttheme",version:"1.0.35",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as Xu}from"node:fs";import{basename as Fd,join as Dn}from"node:path";var xf=/^#[0-9a-f]{6}$/;function hs(t){return xf.test(t)}function Gt(t){let e=Number.parseInt(t.slice(1),16);return[e>>16&255,e>>8&255,e&255]}function zt(t){let[e,n,r]=Gt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*e+0.7152*n+0.0722*r}function ae(t,e){let n=zt(t),r=zt(e);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Mr(t,e){return Math.round(ae(t,e)*100)/100}var pe=7,as=3,bi=0.15,fs=1.6,ls=[1,2,3,4,5,6,9,10,11,12,13,14],gs=[7,15];function In(t,e){let n=t.ansi[e];if(n===void 0)throw Error(`${t.name}: missing ANSI ${e}`);return n}function $i(t,e,n){let r=t.background;return e.flatMap((i)=>{let o=In(t,i);return ae(o,r)<n?[`ANSI ${i} ${o} on ${r} is ${Mr(o,r)}:1, needs ${n}:1`]:[]})}function ds(t,e){return Math.min(...e.map((n)=>ae(In(t,n),t.background)))}var Sr=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:pe,measure:({foreground:t,background:e})=>ae(t,e),check:({foreground:t,background:e})=>ae(t,e)<pe?[`foreground ${t} on ${e} is ${Mr(t,e)}:1, needs ${pe}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:as,measure:(t)=>ds(t,ls),check:(t)=>$i(t,ls,as)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:bi,measure:(t)=>zt(In(t,0)),check:(t)=>{let e=In(t,0);return zt(e)>bi?[`ANSI 0 ${e} has luminance ${zt(e).toFixed(3)}, needs <= ${bi}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:pe,measure:(t)=>ds(t,gs),check:(t)=>$i(t,gs,pe)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:fs,measure:(t)=>ae(In(t,8),t.background),check:(t)=>$i(t,[8],fs)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:pe,measure:({foreground:t,selectionBackground:e})=>e===void 0?Number.NaN:ae(t,e),check:({foreground:t,selectionBackground:e})=>e!==void 0&&ae(t,e)<pe?[`foreground ${t} on selection ${e} is ${Mr(t,e)}:1, needs ${pe}:1`]:[]}],bw=Sr.map((t)=>t.rule),Ir=Sr.map(({rule:t,label:e,unit:n,min:r,max:i})=>({rule:t,label:e,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function ms(t){return Sr.map((e)=>Math.round(e.measure(t)*1000)/1000)}function ki(t){return Sr.filter((e)=>!t.waive.includes(e.rule)).flatMap((e)=>e.check(t).map((n)=>({theme:t.name,rule:e.rule,detail:n})))}function ps(t){return t.flatMap(ki)}var _f=["black","red","green","yellow","blue","magenta","cyan","white"];function ws(t,e){return[t,..._f.map((n,r)=>`${n} = '${e[r]}'`),""].join(`
|
|
3
|
-
`)}var
|
|
4
|
-
`);return[{path:`alacritty/themes/${ct(t.name)}.toml`,content:e}]}};var
|
|
5
|
-
`);return[{path:`ghostty/themes/${ct(t.name)}`,content:e}]}};function
|
|
6
|
-
`}function
|
|
7
|
-
`)}var
|
|
8
|
-
`);return[{path:`iterm2/${ct(t.name)}.itermcolors`,content:e}]}};var
|
|
9
|
-
`);return[{path:`kitty/themes/${ct(t.name)}.conf`,content:e}]}};function
|
|
10
|
-
`)}import{createHash as
|
|
11
|
-
`)}function
|
|
12
|
-
`)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?
|
|
13
|
-
`}]}};import{readdirSync as ad,readFileSync as bu}from"node:fs";import{basename as fd,join as $u}from"node:path";import{readdirSync as Pg,rmSync as Gg,statSync as Lg}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as Tg}from"node:net";import{homedir as Ug}from"node:os";import{join as Un}from"node:path";import{setTimeout as Kg}from"node:timers/promises";var Pe=100,Le=25000000,Ag=536870912,Kn=["safe","questionable","explicit"],Ge=["nudity","underwear"],Jg={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},Tn={safe:"s",questionable:"q",explicit:"e"},Wg=8191,Qg=20000,Zg=5000,Xc=3000,Cc=8,qg=3000,Bc=60000,Vc=3,Qi=`ttheme/${re.version} (+${re.homepage})`,xg=["orig","tile","thumb","cut"],Dc=new Map,_g=nd(process.env.TTHEME_FIND_HOSTS),Xg=ed(process.env.TTHEME_FIND_CUTOUTS);Tg(qg);function Yc(t){try{return Pg(t)}catch{return[]}}function Pr(t){return t.startsWith("//")?`https:${t}`:t}function An(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Jn(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function Cg(t){let e=t.trim(),r=(e?JSON.parse(e):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function Wi(t,e,n){let r=Pr(String(t??""));return{file:r,width:Number(e)||0,height:Number(n)||0,ext:An(r)}}function tu(t,e){let n=Pr(String(e.preview??""));if(!e.file||!n||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:e.file,preview:n,ext:e.ext,owner:String(e.owner??""),artist:e.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(e.md5??""),source:String(t.source??""),tags:e.tags.split(/\s+/).filter(Boolean),solo:e.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:e.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function Vg(t){let e=Cg(t);return Jn(t).flatMap((n)=>{let r=Pr(String(n.file_url??"")),i=String(n.tags??"");return tu(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||An(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((o)=>e.get(o)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[Wi(n.jpeg_url,n.jpeg_width,n.jpeg_height),Wi(n.sample_url,n.sample_width,n.sample_height)]})})}function Yg(t){return Jn(t).flatMap((e)=>{let n=Pr(String(e.file_url??"")),r=String(e.tag_string??""),i=e.media_asset??{};return tu(e,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??e.preview_file_url,file:n,ext:String(e.file_ext||An(n)).toLowerCase(),owner:"",artist:String(e.tag_string_artist??"").split(/\s+/)[0]??"",md5:e.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>Wi(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function zg(t){return Jn(t).flatMap((e)=>{let n=String(e.value??"");return n?[{value:n,count:Number(e.post_count)||0}]:[]})}function Bg(t){return Jn(t).flatMap((e)=>{let n=String(e.name??"");return n?[{value:n,count:Number(e.count)||0}]:[]})}function Dg(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function td(t){let e=t.trim()?JSON.parse(t):{};return Number(e.counts?.posts)||0}function ed(t){let e=new Map;for(let n of(t??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)e.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return e}function nd(t){let e=new Map;for(let n of(t??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let o=new URL(n.slice(r+1));if(i&&o.protocol==="https:")e.set(i,o.origin)}catch{}}return e}function eu(t,e,n,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=e.filter((s)=>i.includes(s));return o.length>0?o:[...n]}function Gr(t){return eu(t,Kn,["safe"])}function Lr(t){return eu(t,Ge,Ge,"none")}function nu(t,e,n){return{safe:new Set(t),questionable:new Set(e),explicit:new Set(n)}}function ru(t){let e=_g.get(t.key),n=Xg.get(t.key);return{...t,origin:e??t.origin,moved:e!==void 0&&e!==t.origin,cutouts:n??t.cutouts,vouched:t.vouched&&n===void 0}}function iu(t){return t.length<2?t.join(""):t.map((e)=>`~${e}`).join(" ")}function zc(t){let e=ru(t),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...e,cutouts:iu(e.cutouts),ratings:nu([Tn.safe],[Tn.questionable],[Tn.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${Tn[i]}`;let o=Kn.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${Tn[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${e.origin}/post.json?${n({limit:String(Pe),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${e.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/post/show/${r}`,parse:Vg,count:Dg}}function rd(t){let e=ru(t),n=nu(["g"],["s","q"],["e"]);return{...e,cutouts:iu(e.cutouts),ratings:n,rate:(r)=>r.length===Kn.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${e.origin}/posts.json?${new URLSearchParams({limit:String(Pe),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${e.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/posts/${r}`,parse:Yg,count:td}}function id(t){return lt.find((e)=>e.key===t||e.name===t||new URL(e.origin).host===t)}function Zi(t){return t.split(/\s+/).filter((e)=>e&&!e.startsWith("rating:")).length}function Tr(t,e){let n=t.trim();if(/^\d+$/.test(n))return{site:e,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let c=lt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let o=id(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var lt=[rd({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),zc({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),zc({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],le=134217728;function oe(t,e){let n=lt.indexOf(t);return(n===-1?lt.length:n)*le+e}function qi(t){let e;try{e=new URL(t).hostname}catch{return""}return e.split(".").slice(-2).join(".")}function ou(){return lt.filter((t)=>!t.tunneled).map((t)=>qi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function su(t,e=Ge){return t.tags.filter((n)=>e.some((r)=>Jg[r].has(n)))}function cu(t,e,n=["safe"]){return n.some((r)=>t.ratings[r].has(e.rating))}function Wn(t){return[t,...t.smaller].find((e)=>e.width*e.height<=Le)}function uu(t){let e=new Map;for(let[n,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;e.set(r,[...e.get(r)??[],n])}return e}function Ur(){return Un(process.env.XDG_CACHE_HOME??Un(Ug(),".cache"),"ttheme")}function ve(t){return Un(Ur(),t.key)}function hu(t=Ag,e=Ur()){let n=[],r=0;for(let i of Yc(e))for(let o of xg){let s=Un(e,i,o);for(let c of Yc(s)){let u=Un(s,c);try{let{size:h,mtimeMs:a}=Lg(u);n.push({path:u,size:h,at:a}),r+=h}catch{}}}n.sort((i,o)=>i.at-o.at);for(let i of n){if(r<=t)return;try{Gg(i.path,{force:!0}),r-=i.size}catch{}}}function od(t,e){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let n=t===null?Number.NaN:Date.parse(t);return Number.isNaN(n)?Bc:Math.max(0,n-e)}function Ee(t){return Dc.get(t.key)??0}function sd(t){for(let e=t;e instanceof Error;e=e.cause)if(e.code==="ECONNRESET")return!0;return!1}function cd(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function ye(t,e,n,r={},i=Qg){for(let o=1;;o++){let s=Ee(t)-Date.now();if(s>0)await Kg(s,void 0,{signal:n});let c;try{c=await fetch(e,{headers:{"User-Agent":Qi,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(u){if(o<Vc&&!n.aborted&&sd(u))continue;throw u}if(c.status===429&&o<Vc){await c.body?.cancel();let u=od(c.headers.get("retry-after"),Date.now());if(u>Bc)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);Dc.set(t.key,Math.max(Ee(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(cd(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function au(t,e,n,r){return t.parse(await(await ye(t,t.postsUrl(e,n),r)).text())}async function fu(t,e,n){return t.count(await(await ye(t,t.countUrl(e),n)).text())}async function xi(t,e,n){let[r]=t.parse(await(await ye(t,t.postUrl(e),n)).text());return r}function ud(t){let e=lt.find((r)=>r.key==="danbooru"),n=new URLSearchParams({limit:String(2*Pe),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${e.origin}/posts.json?${n}`}function hd(t){return new Map(Jn(t).flatMap((e)=>{let n=String(e.md5??"");return n?[[n,String(e.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function lu(t,e){for(let n of t){let r=e.get(n.md5);if(r)n.tags=[...new Set([...n.tags,...r])],n.solo=r.includes("solo")}}async function gu(t,e){let n=lt.find((i)=>i.key==="danbooru"),r=new Map;if(Ee(n)>Date.now())return r;for(let i=0;i<t.length;i+=Pe){let o=await(await ye(n,ud(t.slice(i,i+Pe)),e,{},Zg)).text();for(let[s,c]of hd(o))r.set(s,c)}return r}async function du(t,e){let n=lt.find((o)=>o.key==="danbooru");if(Ee(n)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(Cc)}),s=`${n.origin}/autocomplete.json?${o}`;return zg(await(await ye(n,s,e,{},Xc)).text())}catch(o){if(e.aborted)throw o}let r=lt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(Cc)});return Bg(await(await ye(r,`${r.origin}/tag.json?${i}`,e,{},Xc)).text())}async function mu(t,e,n){let r=await ye(t,e,n,{Range:`bytes=0-${Wg}`});return Pn(new Uint8Array(await r.arrayBuffer()))}async function pu(t,e,n,r){let i=await ye(t,e,n,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:f,value:l}=await s.read();if(f)break;c.push(l),u+=l.length,r?.(u,o)}let h=new Uint8Array(u),a=0;for(let f of c)h.set(f,a),a+=f.length;return h}var ge="_groups.toml",wu=3,ku=["background","foreground","cursor","selection"];function It(t,e){throw Error(`${t}: ${e}`)}function Te(t,e,n){if(typeof n!=="string"||!hs(n))It(t,`${e} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Me(t,e,n){if(typeof n!=="string"||n.length===0)It(t,`${e} must be a non-empty string`);return n}function Qn(t){return t&&typeof t==="object"?t:{}}function ld(t,e,n){if(e===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(e)?e:[e];if(r.length===0)It(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Te(t,`ghostty.icon_screen[${o}]`,i))}function gd(t,e,n){let r=Qn(e);return{iconGhost:r.icon_ghost===void 0?n.cursor:Te(t,"ghostty.icon_ghost",r.icon_ghost),iconScreen:ld(t,r.icon_screen,n)}}function dd(t){return new Map([...ku.map((e)=>[e,t[e]]),...t.ansi.map((e,n)=>[`ansi${n}`,e])])}function md(t,e,n){if(!Array.isArray(e)||e.length!==wu)It(t,`meta.signature must name exactly ${wu} palette slots`);let r=dd(n),i=[],o=[];for(let[s,c]of e.entries()){let u=`meta.signature[${s}]`,h=Me(t,u,c),a=r.get(h);if(a===void 0)It(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${ku.join(", ")} or ansi0-ansi15`);i.push(h),o.push(a)}if(new Set(o).size!==o.length)It(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function pd(t,e,n){if(e===void 0)return;if(!n)It(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!e||typeof e!=="object"||Array.isArray(e))It(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(e)){let s=lt.find((u)=>u.key===i);if(!s)It(t,`meta.booru_sites.${i} is not a find site — use ${lt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))It(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))It(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function wd(t){let n=Bun.TOML.parse(bu($u(t,ge),"utf8")).group;if(!Array.isArray(n)||n.length===0)It(ge,"needs at least one [[group]] table");return n.map((r)=>{let i=Qn(r);return{name:Me(ge,"group.name",i.name),native:i.native===void 0?void 0:Me(ge,"group.native",i.native),lead:Me(ge,"group.lead",i.lead)}})}function bd(t,e,n){let r=Bun.TOML.parse(e),i=Qn(r.meta),o=Qn(r.colors),s=Qn(r.contrast),c=o.ansi;if(!Array.isArray(c)||c.length!==16)It(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let u=Me(t,"meta.name",i.name);if(u!==fd(t,".toml"))It(t,`meta.name "${u}" does not match the filename`);if(u.startsWith("-"))It(t,`meta.name "${u}" would be read as a flag by the ttheme CLI`);let h=i.role;if(h!==void 0&&h!=="default")It(t,`meta.role must be "default", got ${JSON.stringify(h)}`);let a=Me(t,"meta.group",i.group),f=n.get(a);if(!f)It(t,`meta.group "${a}" has no [[group]] table in ${ge}`);let l=Te(t,"colors.background",o.background),m=Te(t,"colors.foreground",o.foreground),b=Te(t,"colors.cursor",o.cursor),g=Te(t,"colors.selection_background",o.selection_background),$=c.map((p,R)=>Te(t,`colors.ansi[${R}]`,p)),y=md(t,i.signature,{background:l,foreground:m,cursor:b,selection:g,ansi:$}),F=i.booru===void 0?void 0:Me(t,"meta.booru",i.booru);if(F!==void 0&&/\s/.test(F))It(t,`meta.booru must be a single booru tag, got ${JSON.stringify(F)}`);let E=pd(t,i.booru_sites,F),M=Array.isArray(s.waive)?s.waive.map(String):[];if(M.length>0&&typeof s.reason!=="string")It(t,"contrast.waive needs a contrast.reason explaining why");return{name:u,group:a,native:f.native,lead:f.lead===u,order:Number(i.order),role:h,ansiSource:Me(t,"meta.ansi_source",i.ansi_source),...F?{booru:F}:{},...E?{booruSites:E}:{},background:l,foreground:m,cursor:b,selectionBackground:g,ansi:$,signature:y.colors,signatureSlots:y.names,ghostty:gd(t,r.ghostty,{background:l,cursor:b,selectionBackground:g}),waive:M,waiveReason:typeof s.reason==="string"?s.reason:void 0}}function Eu(t){let e=wd(t),n=new Map(e.map((o)=>[o.name,o]));if(n.size!==e.length)It(ge,"group.name must be unique");let r=ad(t).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>bd(o,bu($u(t,o),"utf8"),n)).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of e){let s=r.filter((c)=>c.group===o.name);if(s.length===0)It(ge,`group "${o.name}" has no themes`);if(!s.some((c)=>c.name===o.lead))It(ge,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function yu(t){return t.filter((e)=>e.role===void 0)}function Zn(t){let e=(n,r)=>n<r?-1:n>r?1:0;return[...t].sort((n,r)=>e(n.group.toLowerCase(),r.group.toLowerCase())||e(n.name,r.name))}var $d=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Kr=[{name:"use",args:["<palette>"],about:"paint this tab — a unique prefix works: ttheme use ho",section:"tab",shell:!0},{name:"preview",args:[],about:"browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",shell:!0},{name:"next",args:[],about:"advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"make a palette the one new tabs open with",section:"tab"},{name:"on",args:[],about:"wear the default palette in new tabs again",section:"tab"},{name:"off",args:[],about:"take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"tab"},{name:"pin",args:[],about:"pick a palette for this directory — cd into it repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:[],about:"drop the palette pinned to this directory",section:"tab",shell:!0},{name:"config",args:[],about:"edit settings in $EDITOR — they apply in new tabs",section:"tab",shell:!0},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",section:"catalog"},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"print the matches as JSON: name, group, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh the catalog from the registry",section:"catalog"},{name:"init",args:[],about:"install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"accept every default without prompting"}}},{name:"uninstall",args:[],about:"take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"remove without asking"}}},{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:$d,about:"rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",section:"setup",hidden:!0}];var Ar=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Iu="# ttheme begin",Fu="# ttheme end",qn=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function xn(t,e){let n=`${Iu}
|
|
2
|
+
import{createRequire as il}from"node:module";var zf=Object.create;var{getPrototypeOf:Bf,defineProperty:gs,getOwnPropertyNames:Df}=Object;var tl=Object.prototype.hasOwnProperty;function el(t){return this[t]}var nl,rl,vr=(t,e,n)=>{var r=t!=null&&typeof t==="object";if(r){var i=e?nl??=new WeakMap:rl??=new WeakMap,o=i.get(t);if(o)return o}n=t!=null?zf(Bf(t)):{};let s=e||!t||!t.__esModule?gs(n,"default",{value:t,enumerable:!0}):n;for(let c of Df(t))if(!tl.call(s,c))gs(s,c,{get:el.bind(t,c),enumerable:!0});if(r)i.set(t,s);return s};var bt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Gt=il(import.meta.url);var Us=bt((Xw,Rr)=>{var As=As||function(t){return Buffer.from(t).toString("base64")};function dl(t){var e=this,n=Math.round,r=Math.floor,i=Array(64),o=Array(64),s=Array(64),c=Array(64),u,h,a,f,l=Array(65535),m=Array(65535),b=Array(64),g=Array(64),$=[],y=0,F=7,E=Array(64),v=Array(64),p=Array(64),j=Array(256),k=Array(2048),H,R=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],P=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],U=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],Ft=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],K=[0,1,2,3,4,5,6,7,8,9,10,11],z=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Et=[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 dt(d){var G=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(var J=0;J<64;J++){var A=r((G[J]*d+50)/100);if(A<1)A=1;else if(A>255)A=255;i[R[J]]=A}var Z=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(var q=0;q<64;q++){var rt=r((Z[q]*d+50)/100);if(rt<1)rt=1;else if(rt>255)rt=255;o[R[q]]=rt}var it=[1,1.387039845,1.306562965,1.175875602,1,0.785694958,0.5411961,0.275899379],St=0;for(var wt=0;wt<8;wt++)for(var M=0;M<8;M++)s[St]=1/(i[R[St]]*it[wt]*it[M]*8),c[St]=1/(o[R[St]]*it[wt]*it[M]*8),St++}function B(d,G){var J=0,A=0,Z=[];for(var q=1;q<=16;q++){for(var rt=1;rt<=d[q];rt++)Z[G[A]]=[],Z[G[A]][0]=J,Z[G[A]][1]=q,A++,J++;J*=2}return Z}function Nt(){u=B(L,P),h=B(Ft,K),a=B(C,U),f=B(z,Et)}function ot(){var d=1,G=2;for(var J=1;J<=15;J++){for(var A=d;A<G;A++)m[32767+A]=J,l[32767+A]=[],l[32767+A][1]=J,l[32767+A][0]=A;for(var Z=-(G-1);Z<=-d;Z++)m[32767+Z]=J,l[32767+Z]=[],l[32767+Z][1]=J,l[32767+Z][0]=G-1+Z;d<<=1,G<<=1}}function tt(){for(var d=0;d<256;d++)k[d]=19595*d,k[d+256>>0]=38470*d,k[d+512>>0]=7471*d+32768,k[d+768>>0]=-11059*d,k[d+1024>>0]=-21709*d,k[d+1280>>0]=32768*d+8421375,k[d+1536>>0]=-27439*d,k[d+1792>>0]=-5329*d}function X(d){var G=d[0],J=d[1]-1;while(J>=0){if(G&1<<J)y|=1<<F;if(J--,F--,F<0){if(y==255)w(255),w(0);else w(y);F=7,y=0}}}function w(d){$.push(d)}function T(d){w(d>>8&255),w(d&255)}function ht(d,G){var J,A,Z,q,rt,it,St,wt,M=0,O,Q=8,yt=64;for(O=0;O<Q;++O){J=d[M],A=d[M+1],Z=d[M+2],q=d[M+3],rt=d[M+4],it=d[M+5],St=d[M+6],wt=d[M+7];var _=J+wt,D=J-wt,ft=A+St,W=A-St,st=Z+it,Ht=Z-it,kt=q+rt,_t=q-rt,ne=_+kt,Oe=_-kt,qe=ft+st,_e=ft-st;d[M]=ne+qe,d[M+4]=ne-qe;var kn=(_e+Oe)*0.707106781;d[M+2]=Oe+kn,d[M+6]=Oe-kn,ne=_t+Ht,qe=Ht+W,_e=W+D;var En=(ne-_e)*0.382683433,kr=0.5411961*ne+En,yn=1.306562965*_e+En,Mn=qe*0.707106781,vn=D+Mn,Sn=D-Mn;d[M+5]=Sn+kr,d[M+3]=Sn-kr,d[M+1]=vn+yn,d[M+7]=vn-yn,M+=8}M=0;for(O=0;O<Q;++O){J=d[M],A=d[M+8],Z=d[M+16],q=d[M+24],rt=d[M+32],it=d[M+40],St=d[M+48],wt=d[M+56];var ts=J+wt,bi=J-wt,es=A+St,ns=A-St,rs=Z+it,is=Z-it,os=q+rt,Yf=q-rt,In=ts+os,$i=ts-os,Er=es+rs,yr=es-rs;d[M]=In+Er,d[M+32]=In-Er;var ss=(yr+$i)*0.707106781;d[M+16]=$i+ss,d[M+48]=$i-ss,In=Yf+is,Er=is+ns,yr=ns+bi;var cs=(In-yr)*0.382683433,us=0.5411961*In+cs,hs=1.306562965*yr+cs,as=Er*0.707106781,fs=bi+as,ls=bi-as;d[M+40]=ls+us,d[M+24]=ls-us,d[M+8]=fs+hs,d[M+56]=fs-hs,M++}var Mr;for(O=0;O<yt;++O)Mr=d[O]*G[O],b[O]=Mr>0?Mr+0.5|0:Mr-0.5|0;return b}function at(){T(65504),T(16),w(74),w(70),w(73),w(70),w(0),w(1),w(1),w(0),T(1),T(1),w(0),w(0)}function et(d){if(!d)return;if(T(65505),d[0]===69&&d[1]===120&&d[2]===105&&d[3]===102)T(d.length+2);else T(d.length+5+2),w(69),w(120),w(105),w(102),w(0);for(var G=0;G<d.length;G++)w(d[G])}function nt(d,G){T(65472),T(17),w(8),T(G),T(d),w(3),w(1),w(17),w(0),w(2),w(17),w(1),w(3),w(17),w(1)}function V(){T(65499),T(132),w(0);for(var d=0;d<64;d++)w(i[d]);w(1);for(var G=0;G<64;G++)w(o[G])}function N(){T(65476),T(418),w(0);for(var d=0;d<16;d++)w(L[d+1]);for(var G=0;G<=11;G++)w(P[G]);w(16);for(var J=0;J<16;J++)w(C[J+1]);for(var A=0;A<=161;A++)w(U[A]);w(1);for(var Z=0;Z<16;Z++)w(Ft[Z+1]);for(var q=0;q<=11;q++)w(K[q]);w(17);for(var rt=0;rt<16;rt++)w(z[rt+1]);for(var it=0;it<=161;it++)w(Et[it])}function I(d){if(typeof d>"u"||d.constructor!==Array)return;d.forEach((G)=>{if(typeof G!=="string")return;T(65534);var J=G.length;T(J+2);var A;for(A=0;A<J;A++)w(G.charCodeAt(A))})}function pt(){T(65498),T(12),w(3),w(1),w(0),w(2),w(17),w(3),w(17),w(0),w(63),w(0)}function x(d,G,J,A,Z){var q=Z[0],rt=Z[240],it,St=16,wt=63,M=64,O=ht(d,G);for(var Q=0;Q<M;++Q)g[R[Q]]=O[Q];var yt=g[0]-J;if(J=g[0],yt==0)X(A[0]);else it=32767+yt,X(A[m[it]]),X(l[it]);var _=63;for(;_>0&&g[_]==0;_--);if(_==0)return X(q),J;var D=1,ft;while(D<=_){var W=D;for(;g[D]==0&&D<=_;++D);var st=D-W;if(st>=St){ft=st>>4;for(var Ht=1;Ht<=ft;++Ht)X(rt);st=st&15}it=32767+g[D],X(Z[(st<<4)+m[it]]),X(l[it]),D++}if(_!=wt)X(q);return J}function Y(){var d=String.fromCharCode;for(var G=0;G<256;G++)j[G]=d(G)}this.encode=function(d,G){var J=new Date().getTime();if(G)qt(G);$=[],y=0,F=7,T(65496),at(),I(d.comments),et(d.exifBuffer),V(),nt(d.width,d.height),N(),pt();var A=0,Z=0,q=0;y=0,F=7,this.encode.displayName="_encode_";var{data:rt,width:it,height:St}=d,wt=it*4,M=it*3,O,Q=0,yt,_,D,ft,W,st,Ht,kt;while(Q<St){O=0;while(O<wt){ft=wt*Q+O,W=ft,st=-1,Ht=0;for(kt=0;kt<64;kt++){if(Ht=kt>>3,st=(kt&7)*4,W=ft+Ht*wt+st,Q+Ht>=St)W-=wt*(Q+1+Ht-St);if(O+st>=wt)W-=O+st-wt+4;yt=rt[W++],_=rt[W++],D=rt[W++],E[kt]=(k[yt]+k[_+256>>0]+k[D+512>>0]>>16)-128,v[kt]=(k[yt+768>>0]+k[_+1024>>0]+k[D+1280>>0]>>16)-128,p[kt]=(k[yt+1280>>0]+k[_+1536>>0]+k[D+1792>>0]>>16)-128}A=x(E,s,A,u,a),Z=x(v,c,Z,h,f),q=x(p,c,q,h,f),O+=32}Q+=8}if(F>=0){var _t=[];_t[1]=F+1,_t[0]=(1<<F+1)-1,X(_t)}if(T(65497),typeof Rr>"u")return new Uint8Array($);return Buffer.from($);var ne,Oe};function qt(d){if(d<=0)d=1;if(d>100)d=100;if(H==d)return;var G=0;if(d<50)G=Math.floor(5000/d);else G=Math.floor(200-d*2);dt(G),H=d}function Yt(){var d=new Date().getTime();if(!t)t=50;Y(),Nt(),ot(),tt(),qt(t);var G=new Date().getTime()-d}Yt()}if(typeof Rr<"u")Rr.exports=Ts;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=Ts;function Ts(t,e){if(typeof e>"u")e=50;var n=new dl(e),r=n.encode(t,e);return{data:r,width:t.width,height:t.height}}});var Js=bt((Vw,Fi)=>{var Ii=function(){var e=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,o=2276,s=1567,c=3784,u=5793,h=2896;function a(){}function f(F,E){var v=0,p=[],j,k,H=16;while(H>0&&!F[H-1])H--;p.push({children:[],index:0});var R=p[0],L;for(j=0;j<H;j++){for(k=0;k<F[j];k++){R=p.pop(),R.children[R.index]=E[v];while(R.index>0){if(p.length===0)throw Error("Could not recreate Huffman Table");R=p.pop()}R.index++,p.push(R);while(p.length<=j)p.push(L={children:[],index:0}),R.children[R.index]=L.children,R=L;v++}if(j+1<H)p.push(L={children:[],index:0}),R.children[R.index]=L.children,R=L}return p[0].children}function l(F,E,v,p,j,k,H,R,L,P){var{precision:C,samplesPerLine:U,scanLines:Ft,mcusPerLine:K,progressive:z,maxH:Et,maxV:dt}=v,B=E,Nt=0,ot=0;function tt(){if(ot>0)return ot--,Nt>>ot&1;if(Nt=F[E++],Nt==255){var M=F[E++];if(M)throw Error("unexpected marker: "+(Nt<<8|M).toString(16))}return ot=7,Nt>>>7}function X(M){var O=M,Q;while((Q=tt())!==null){if(O=O[Q],typeof O==="number")return O;if(typeof O!=="object")throw Error("invalid huffman sequence")}return null}function w(M){var O=0;while(M>0){var Q=tt();if(Q===null)return;O=O<<1|Q,M--}return O}function T(M){var O=w(M);if(O>=1<<M-1)return O;return O+(-1<<M)+1}function ht(M,O){var Q=X(M.huffmanTableDC),yt=Q===0?0:T(Q);O[0]=M.pred+=yt;var _=1;while(_<64){var D=X(M.huffmanTableAC),ft=D&15,W=D>>4;if(ft===0){if(W<15)break;_+=16;continue}_+=W;var st=e[_];O[st]=T(ft),_++}}function at(M,O){var Q=X(M.huffmanTableDC),yt=Q===0?0:T(Q)<<L;O[0]=M.pred+=yt}function et(M,O){O[0]|=tt()<<L}var nt=0;function V(M,O){if(nt>0){nt--;return}var Q=k,yt=H;while(Q<=yt){var _=X(M.huffmanTableAC),D=_&15,ft=_>>4;if(D===0){if(ft<15){nt=w(ft)+(1<<ft)-1;break}Q+=16;continue}Q+=ft;var W=e[Q];O[W]=T(D)*(1<<L),Q++}}var N=0,I;function pt(M,O){var Q=k,yt=H,_=0;while(Q<=yt){var D=e[Q],ft=O[D]<0?-1:1;switch(N){case 0:var W=X(M.huffmanTableAC),st=W&15,_=W>>4;if(st===0)if(_<15)nt=w(_)+(1<<_),N=4;else _=16,N=1;else{if(st!==1)throw Error("invalid ACn encoding");I=T(st),N=_?2:3}continue;case 1:case 2:if(O[D])O[D]+=(tt()<<L)*ft;else if(_--,_===0)N=N==2?3:0;break;case 3:if(O[D])O[D]+=(tt()<<L)*ft;else O[D]=I<<L,N=0;break;case 4:if(O[D])O[D]+=(tt()<<L)*ft;break}Q++}if(N===4){if(nt--,nt===0)N=0}}function x(M,O,Q,yt,_){var D=Q/K|0,ft=Q%K,W=D*M.v+yt,st=ft*M.h+_;if(M.blocks[W]===void 0&&P.tolerantDecoding)return;O(M,M.blocks[W][st])}function Y(M,O,Q){var yt=Q/M.blocksPerLine|0,_=Q%M.blocksPerLine;if(M.blocks[yt]===void 0&&P.tolerantDecoding)return;O(M,M.blocks[yt][_])}var qt=p.length,Yt,d,G,J,A,Z;if(z)if(k===0)Z=R===0?at:et;else Z=R===0?V:pt;else Z=ht;var q=0,rt,it;if(qt==1)it=p[0].blocksPerLine*p[0].blocksPerColumn;else it=K*v.mcusPerColumn;if(!j)j=it;var St,wt;while(q<it){for(d=0;d<qt;d++)p[d].pred=0;if(nt=0,qt==1){Yt=p[0];for(A=0;A<j;A++)Y(Yt,Z,q),q++}else for(A=0;A<j;A++){for(d=0;d<qt;d++){Yt=p[d],St=Yt.h,wt=Yt.v;for(G=0;G<wt;G++)for(J=0;J<St;J++)x(Yt,Z,q,G,J)}if(q++,q===it)break}if(q===it)do{if(F[E]===255){if(F[E+1]!==0)break}E+=1}while(E<F.length-2);if(ot=0,rt=F[E]<<8|F[E+1],rt<65280)throw Error("marker was not found");if(rt>=65488&&rt<=65495)E+=2;else break}return E-B}function m(F,E){var v=[],p=E.blocksPerLine,j=E.blocksPerColumn,k=p<<3,H=new Int32Array(64),R=new Uint8Array(64);function L(B,Nt,ot){var tt=E.quantizationTable,X,w,T,ht,at,et,nt,V,N,I=ot,pt;for(pt=0;pt<64;pt++)I[pt]=B[pt]*tt[pt];for(pt=0;pt<8;++pt){var x=8*pt;if(I[1+x]==0&&I[2+x]==0&&I[3+x]==0&&I[4+x]==0&&I[5+x]==0&&I[6+x]==0&&I[7+x]==0){N=u*I[0+x]+512>>10,I[0+x]=N,I[1+x]=N,I[2+x]=N,I[3+x]=N,I[4+x]=N,I[5+x]=N,I[6+x]=N,I[7+x]=N;continue}X=u*I[0+x]+128>>8,w=u*I[4+x]+128>>8,T=I[2+x],ht=I[6+x],at=h*(I[1+x]-I[7+x])+128>>8,V=h*(I[1+x]+I[7+x])+128>>8,et=I[3+x]<<4,nt=I[5+x]<<4,N=X-w+1>>1,X=X+w+1>>1,w=N,N=T*c+ht*s+128>>8,T=T*s-ht*c+128>>8,ht=N,N=at-nt+1>>1,at=at+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=X-ht+1>>1,X=X+ht+1>>1,ht=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=at*o+V*i+2048>>12,at=at*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+x]=X+V,I[7+x]=X-V,I[1+x]=w+nt,I[6+x]=w-nt,I[2+x]=T+et,I[5+x]=T-et,I[3+x]=ht+at,I[4+x]=ht-at}for(pt=0;pt<8;++pt){var Y=pt;if(I[8+Y]==0&&I[16+Y]==0&&I[24+Y]==0&&I[32+Y]==0&&I[40+Y]==0&&I[48+Y]==0&&I[56+Y]==0){N=u*ot[pt+0]+8192>>14,I[0+Y]=N,I[8+Y]=N,I[16+Y]=N,I[24+Y]=N,I[32+Y]=N,I[40+Y]=N,I[48+Y]=N,I[56+Y]=N;continue}X=u*I[0+Y]+2048>>12,w=u*I[32+Y]+2048>>12,T=I[16+Y],ht=I[48+Y],at=h*(I[8+Y]-I[56+Y])+2048>>12,V=h*(I[8+Y]+I[56+Y])+2048>>12,et=I[24+Y],nt=I[40+Y],N=X-w+1>>1,X=X+w+1>>1,w=N,N=T*c+ht*s+2048>>12,T=T*s-ht*c+2048>>12,ht=N,N=at-nt+1>>1,at=at+nt+1>>1,nt=N,N=V+et+1>>1,et=V-et+1>>1,V=N,N=X-ht+1>>1,X=X+ht+1>>1,ht=N,N=w-T+1>>1,w=w+T+1>>1,T=N,N=at*o+V*i+2048>>12,at=at*i-V*o+2048>>12,V=N,N=et*r+nt*n+2048>>12,et=et*n-nt*r+2048>>12,nt=N,I[0+Y]=X+V,I[56+Y]=X-V,I[8+Y]=w+nt,I[48+Y]=w-nt,I[16+Y]=T+et,I[40+Y]=T-et,I[24+Y]=ht+at,I[32+Y]=ht-at}for(pt=0;pt<64;++pt){var qt=128+(I[pt]+8>>4);Nt[pt]=qt<0?0:qt>255?255:qt}}y(k*j*8);var P,C;for(var U=0;U<j;U++){var Ft=U<<3;for(P=0;P<8;P++)v.push(new Uint8Array(k));for(var K=0;K<p;K++){L(E.blocks[U][K],R,H);var z=0,Et=K<<3;for(C=0;C<8;C++){var dt=v[Ft+C];for(P=0;P<8;P++)dt[Et+P]=R[z++]}}}return v}function b(F){return F<0?0:F>255?255:F}a.prototype={load:function(E){var v=new XMLHttpRequest;v.open("GET",E,!0),v.responseType="arraybuffer",v.onload=function(){var p=new Uint8Array(v.response||v.mozResponseArrayBuffer);if(this.parse(p),this.onload)this.onload()}.bind(this),v.send(null)},parse:function(E){var v=this.opts.maxResolutionInMP*1000*1000,p=0,j=E.length;function k(){var W=E[p]<<8|E[p+1];return p+=2,W}function H(){var W=k(),st=E.subarray(p,p+W-2);return p+=st.length,st}function R(W){var st=1,Ht=1,kt,_t;for(_t in W.components)if(W.components.hasOwnProperty(_t)){if(kt=W.components[_t],st<kt.h)st=kt.h;if(Ht<kt.v)Ht=kt.v}var ne=Math.ceil(W.samplesPerLine/8/st),Oe=Math.ceil(W.scanLines/8/Ht);for(_t in W.components)if(W.components.hasOwnProperty(_t)){kt=W.components[_t];var qe=Math.ceil(Math.ceil(W.samplesPerLine/8)*kt.h/st),_e=Math.ceil(Math.ceil(W.scanLines/8)*kt.v/Ht),kn=ne*kt.h,En=Oe*kt.v,kr=En*kn,yn=[];y(kr*256);for(var Mn=0;Mn<En;Mn++){var vn=[];for(var Sn=0;Sn<kn;Sn++)vn.push(new Int32Array(64));yn.push(vn)}kt.blocksPerLine=qe,kt.blocksPerColumn=_e,kt.blocks=yn}W.maxH=st,W.maxV=Ht,W.mcusPerLine=ne,W.mcusPerColumn=Oe}var L=null,P=null,C=null,U,Ft,K=[],z=[],Et=[],dt=[],B=k(),Nt=-1;if(this.comments=[],B!=65496)throw Error("SOI not found");B=k();while(B!=65497){var ot,tt,X;switch(B){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var w=H();if(B===65534){var T=String.fromCharCode.apply(null,w);this.comments.push(T)}if(B===65504){if(w[0]===74&&w[1]===70&&w[2]===73&&w[3]===70&&w[4]===0)L={version:{major:w[5],minor:w[6]},densityUnits:w[7],xDensity:w[8]<<8|w[9],yDensity:w[10]<<8|w[11],thumbWidth:w[12],thumbHeight:w[13],thumbData:w.subarray(14,14+3*w[12]*w[13])}}if(B===65505){if(w[0]===69&&w[1]===120&&w[2]===105&&w[3]===102&&w[4]===0)this.exifBuffer=w.subarray(5,w.length)}if(B===65518){if(w[0]===65&&w[1]===100&&w[2]===111&&w[3]===98&&w[4]===101&&w[5]===0)P={version:w[6],flags0:w[7]<<8|w[8],flags1:w[9]<<8|w[10],transformCode:w[11]}}break;case 65499:var ht=k(),at=ht+p-2;while(p<at){var et=E[p++];y(256);var nt=new Int32Array(64);if(et>>4===0)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=E[p++]}else if(et>>4===1)for(tt=0;tt<64;tt++){var V=e[tt];nt[V]=k()}else throw Error("DQT: invalid table spec");K[et&15]=nt}break;case 65472:case 65473:case 65474:k(),U={},U.extended=B===65473,U.progressive=B===65474,U.precision=E[p++],U.scanLines=k(),U.samplesPerLine=k(),U.components={},U.componentsOrder=[];var N=U.scanLines*U.samplesPerLine;if(N>v){var I=Math.ceil((N-v)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${I}MP`)}var pt=E[p++],x,Y=0,qt=0;for(ot=0;ot<pt;ot++){x=E[p];var Yt=E[p+1]>>4,d=E[p+1]&15,G=E[p+2];if(Yt<=0||d<=0)throw Error("Invalid sampling factor, expected values above 0");U.componentsOrder.push(x),U.components[x]={h:Yt,v:d,quantizationIdx:G},p+=3}R(U),z.push(U);break;case 65476:var J=k();for(ot=2;ot<J;){var A=E[p++],Z=new Uint8Array(16),q=0;for(tt=0;tt<16;tt++,p++)q+=Z[tt]=E[p];y(16+q);var rt=new Uint8Array(q);for(tt=0;tt<q;tt++,p++)rt[tt]=E[p];ot+=17+q,(A>>4===0?dt:Et)[A&15]=f(Z,rt)}break;case 65501:k(),Ft=k();break;case 65500:k(),k();break;case 65498:var it=k(),St=E[p++],wt=[],M;for(ot=0;ot<St;ot++){M=U.components[E[p++]];var O=E[p++];M.huffmanTableDC=dt[O>>4],M.huffmanTableAC=Et[O&15],wt.push(M)}var Q=E[p++],yt=E[p++],_=E[p++],D=l(E,p,U,wt,Ft,Q,yt,_>>4,_&15,this.opts);p+=D;break;case 65535:if(E[p]!==255)p--;break;default:if(E[p-3]==255&&E[p-2]>=192&&E[p-2]<=254){p-=3;break}else if(B===224||B==225){if(Nt!==-1)throw Error(`first unknown JPEG marker at offset ${Nt.toString(16)}, second unknown JPEG marker ${B.toString(16)} at offset ${(p-1).toString(16)}`);Nt=p-1;let W=k();if(E[p+W-2]===255){p+=W-2;break}}throw Error("unknown JPEG marker "+B.toString(16))}B=k()}if(z.length!=1)throw Error("only single frame JPEGs supported");for(var ot=0;ot<z.length;ot++){var ft=z[ot].components;for(var tt in ft)ft[tt].quantizationTable=K[ft[tt].quantizationIdx],delete ft[tt].quantizationIdx}this.width=U.samplesPerLine,this.height=U.scanLines,this.jfif=L,this.adobe=P,this.components=[];for(var ot=0;ot<U.componentsOrder.length;ot++){var M=U.components[U.componentsOrder[ot]];this.components.push({lines:m(U,M),scaleX:M.h/U.maxH,scaleY:M.v/U.maxV})}},getData:function(E,v){var p=this.width/E,j=this.height/v,k,H,R,L,P,C,U,Ft,K,z,Et=0,dt,B,Nt,ot,tt,X,w,T,ht,at,et,nt=E*v*this.components.length;y(nt);var V=new Uint8Array(nt);switch(this.components.length){case 1:k=this.components[0];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j];for(K=0;K<E;K++)dt=P[0|K*k.scaleX*p],V[Et++]=dt}break;case 2:k=this.components[0],H=this.components[1];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j];for(K=0;K<E;K++)dt=P[0|K*k.scaleX*p],V[Et++]=dt,dt=C[0|K*H.scaleX*p],V[Et++]=dt}break;case 3:if(et=!0,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],H=this.components[1],R=this.components[2];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j],U=R.lines[0|z*R.scaleY*j];for(K=0;K<E;K++){if(!et)T=P[0|K*k.scaleX*p],ht=C[0|K*H.scaleX*p],at=U[0|K*R.scaleX*p];else dt=P[0|K*k.scaleX*p],B=C[0|K*H.scaleX*p],Nt=U[0|K*R.scaleX*p],T=b(dt+1.402*(Nt-128)),ht=b(dt-0.3441363*(B-128)-0.71413636*(Nt-128)),at=b(dt+1.772*(B-128));V[Et++]=T,V[Et++]=ht,V[Et++]=at}}break;case 4:if(!this.adobe)throw Error("Unsupported color mode (4 components)");if(et=!1,this.adobe&&this.adobe.transformCode)et=!0;else if(typeof this.opts.colorTransform<"u")et=!!this.opts.colorTransform;k=this.components[0],H=this.components[1],R=this.components[2],L=this.components[3];for(z=0;z<v;z++){P=k.lines[0|z*k.scaleY*j],C=H.lines[0|z*H.scaleY*j],U=R.lines[0|z*R.scaleY*j],Ft=L.lines[0|z*L.scaleY*j];for(K=0;K<E;K++){if(!et)tt=P[0|K*k.scaleX*p],X=C[0|K*H.scaleX*p],w=U[0|K*R.scaleX*p],ot=Ft[0|K*L.scaleX*p];else dt=P[0|K*k.scaleX*p],B=C[0|K*H.scaleX*p],Nt=U[0|K*R.scaleX*p],ot=Ft[0|K*L.scaleX*p],tt=255-b(dt+1.402*(Nt-128)),X=255-b(dt-0.3441363*(B-128)-0.71413636*(Nt-128)),w=255-b(dt+1.772*(B-128));V[Et++]=255-tt,V[Et++]=255-X,V[Et++]=255-w,V[Et++]=255-ot}}break;default:throw Error("Unsupported color mode")}return V},copyToImageData:function(E,v){var{width:p,height:j,data:k}=E,H=this.getData(p,j),R=0,L=0,P,C,U,Ft,K,z,Et,dt,B;switch(this.components.length){case 1:for(C=0;C<j;C++)for(P=0;P<p;P++)if(U=H[R++],k[L++]=U,k[L++]=U,k[L++]=U,v)k[L++]=255;break;case 3:for(C=0;C<j;C++)for(P=0;P<p;P++)if(Et=H[R++],dt=H[R++],B=H[R++],k[L++]=Et,k[L++]=dt,k[L++]=B,v)k[L++]=255;break;case 4:for(C=0;C<j;C++)for(P=0;P<p;P++)if(K=H[R++],z=H[R++],U=H[R++],Ft=H[R++],Et=255-b(K*(1-Ft/255)+Ft),dt=255-b(z*(1-Ft/255)+Ft),B=255-b(U*(1-Ft/255)+Ft),k[L++]=Et,k[L++]=dt,k[L++]=B,v)k[L++]=255;break;default:throw Error("Unsupported color mode")}}};var g=0,$=0;function y(F=0){var E=g+F;if(E>$){var v=Math.ceil((E-$)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${v}MB`)}g=E}return a.resetMaxMemoryUsage=function(F){g=0,$=F},a.getBytesAllocated=function(){return g},a.requestMemoryAllocation=y,a}();if(typeof Fi<"u")Fi.exports=Ks;else if(typeof window<"u")window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=Ks;function Ks(t,e={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...e},i=new Uint8Array(t),o=new Ii;o.opts=r,Ii.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),o.parse(i);var s=r.formatAsRGBA?4:3,c=o.width*o.height*s;try{Ii.requestMemoryAllocation(c);var u={width:o.width,height:o.height,exifBuffer:o.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};if(o.comments.length>0)u.comments=o.comments}catch(h){if(h instanceof RangeError)throw Error("Could not allocate enough memory for the image. Required: "+c);if(h instanceof ReferenceError){if(h.message==="Buffer is not defined")throw Error("Buffer is not globally defined in this environment. Consider setting useTArray to true")}throw h}return o.copyToImageData(u,r.formatAsRGBA),u}});var xs=bt((Yw,Ws)=>{var ml=Us(),pl=Js();Ws.exports={encode:ml,decode:pl}});var Ni=bt((zw,Zs)=>{var wl=Gt("util"),Qs=Gt("stream"),Bt=Zs.exports=function(){Qs.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};wl.inherits(Bt,Qs);Bt.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};Bt.prototype.write=function(t,e){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let n;if(Buffer.isBuffer(t))n=t;else n=Buffer.from(t,e||this._encoding);if(this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};Bt.prototype.end=function(t,e){if(t)this.write(t,e);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};Bt.prototype.destroySoon=Bt.prototype.end;Bt.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};Bt.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};Bt.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];if(e.length>t.length)this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length));else this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e)};Bt.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);while(e<t.length){let i=this._buffers[n++],o=Math.min(i.length,t.length-e);if(i.copy(r,e,0,o),e+=o,o!==i.length)this._buffers[--n]=i.slice(o)}if(n>0)this._buffers.splice(0,n);this._buffered-=t.length,t.func.call(this,r)};Bt.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}if(this._buffers&&!this.writable)this._end()}catch(t){this.emit("error",t)}}});var Ri=bt((bl)=>{var $e=[{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]}];bl.getImagePasses=function(t,e){let n=[],r=t%8,i=e%8,o=(t-r)/8,s=(e-i)/8;for(let c=0;c<$e.length;c++){let u=$e[c],h=o*u.x.length,a=s*u.y.length;for(let f=0;f<u.x.length;f++)if(u.x[f]<r)h++;else break;for(let f=0;f<u.y.length;f++)if(u.y[f]<i)a++;else break;if(h>0&&a>0)n.push({width:h,height:a,index:c})}return n};bl.getInterlaceIterator=function(t){return function(e,n,r){let i=e%$e[r].x.length,o=(e-i)/$e[r].x.length*8+$e[r].x[i],s=n%$e[r].y.length,c=(n-s)/$e[r].y.length*8+$e[r].y[s];return o*4+c*t*4}}});var Oi=bt((Dw,qs)=>{qs.exports=function(e,n,r){let i=e+n-r,o=Math.abs(i-e),s=Math.abs(i-n),c=Math.abs(i-r);if(o<=s&&o<=c)return e;if(s<=c)return n;return r}});var Hi=bt((tb,Cs)=>{var El=Ri(),yl=Oi();function _s(t,e,n){let r=t*e;if(n!==8)r=Math.ceil(r/(8/n));return r}var Xe=Cs.exports=function(t,e){let{width:n,height:r,interlace:i,bpp:o,depth:s}=t;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],i){let c=El.getImagePasses(n,r);for(let u=0;u<c.length;u++)this._images.push({byteWidth:_s(c[u].width,o,s),height:c[u].height,lineIndex:0})}else this._images.push({byteWidth:_s(n,o,s),height:r,lineIndex:0});if(s===8)this._xComparison=o;else if(s===16)this._xComparison=o*2;else this._xComparison=1};Xe.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Xe.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,i=r-1;for(let o=0;o<n;o++){let s=t[1+o],c=o>i?e[o-r]:0;e[o]=s+c}};Xe.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let i=0;i<n;i++){let o=t[1+i],s=r?r[i]:0;e[i]=o+s}};Xe.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=Math.floor((h+u)/2);e[s]=c+a}};Xe.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,i=r-1,o=this._lastLine;for(let s=0;s<n;s++){let c=t[1+s],u=o?o[s]:0,h=s>i?e[s-r]:0,a=s>i&&o?o[s-r]:0,f=yl(h,u,a);e[s]=c+f}};Xe.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(e===0)n=t.slice(1,i+1);else switch(n=Buffer.alloc(i),e){case 1:this._unFilterType1(t,n,i);break;case 2:this._unFilterType2(t,n,i);break;case 3:this._unFilterType3(t,n,i);break;case 4:this._unFilterType4(t,n,i);break;default:throw Error("Unrecognised filter type - "+e)}if(this.write(n),r.lineIndex++,r.lineIndex>=r.height)this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex];else this._lastLine=n;if(r)this.read(r.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var Ys=bt((eb,Vs)=>{var Ml=Gt("util"),Xs=Ni(),vl=Hi(),Sl=Vs.exports=function(t){Xs.call(this);let e=[],n=this;this._filter=new vl(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Ml.inherits(Sl,Xs)});var Ve=bt((nb,zs)=>{zs.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 Gi=bt((rb,Bs)=>{var ji=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)if(e&1)e=3988292384^e>>>1;else e=e>>>1;ji[t]=e}})();var Pi=Bs.exports=function(){this._crc=-1};Pi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ji[(this._crc^t[e])&255]^this._crc>>>8;return!0};Pi.prototype.crc32=function(){return this._crc^-1};Pi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ji[(e^t[n])&255]^e>>>8;return e^-1}});var Li=bt((ib,Ds)=>{var Rt=Ve(),Il=Gi(),Ot=Ds.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[Rt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[Rt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[Rt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[Rt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[Rt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[Rt.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Ot.prototype.start=function(){this.read(Rt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Ot.prototype._parseSignature=function(t){let e=Rt.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let o=4;o<8;o++)r+=String.fromCharCode(t[o]);let i=Boolean(t[4]&32);if(!this._hasIHDR&&n!==Rt.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new Il,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!i){this.error(Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};Ot.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Ot.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(Error("Crc error - "+e+" - "+n));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Ot.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};Ot.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],i=t[9],o=t[10],s=t[11],c=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(Error("Unsupported bit depth "+r));return}if(!(i in Rt.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(o!==0){this.error(Error("Unsupported compression method"));return}if(s!==0){this.error(Error("Unsupported filter method"));return}if(c!==0&&c!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=i;let u=Rt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:Boolean(c),palette:Boolean(i&Rt.COLORTYPE_PALETTE),color:Boolean(i&Rt.COLORTYPE_COLOR),alpha:Boolean(i&Rt.COLORTYPE_ALPHA),bpp:u,colorType:i}),this._handleChunkEnd()};Ot.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};Ot.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Ot.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};Ot.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===Rt.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}if(this._colorType===Rt.COLORTYPE_GRAYSCALE)this.transColor([t.readUInt16BE(0)]);if(this._colorType===Rt.COLORTYPE_COLOR)this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]);this._handleChunkEnd()};Ot.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};Ot.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/Rt.GAMMA_DIVISION),this._handleChunkEnd()};Ot.prototype._handleIDAT=function(t){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-t,this._parseIDAT.bind(this,t))};Ot.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===Rt.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(e);let n=t-e.length;if(n>0)this._handleIDAT(n);else this._handleChunkEnd()};Ot.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};Ot.prototype._parseIEND=function(t){if(this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var Ti=bt((jl)=>{var tc=Ri(),Fl=[function(){},function(t,e,n,r){if(r===e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw Error("Ran out of data");let i=e[r];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Nl=[function(){},function(t,e,n,r){let i=e[0];t[n]=i,t[n+1]=i,t[n+2]=i,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Rl(t,e){let n=[],r=0;function i(){if(r===t.length)throw Error("Ran out of data");let o=t[r];r++;let s,c,u,h,a,f,l,m;switch(e){default:throw Error("unrecognised depth");case 16:l=t[r],r++,n.push((o<<8)+l);break;case 4:l=o&15,m=o>>4,n.push(m,l);break;case 2:a=o&3,f=o>>2&3,l=o>>4&3,m=o>>6&3,n.push(m,l,f,a);break;case 1:s=o&1,c=o>>1&1,u=o>>2&1,h=o>>3&1,a=o>>4&1,f=o>>5&1,l=o>>6&1,m=o>>7&1,n.push(m,l,f,a,h,u,c,s);break}}return{get:function(o){while(n.length<o)i();let s=n.slice(0,o);return n=n.slice(o),s},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw Error("extra data found")}}}function Ol(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++)for(let a=0;a<s;a++){let f=n(a,h,u);Fl[r](e,i,f,o),o+=r}return o}function Hl(t,e,n,r,i,o){let{width:s,height:c,index:u}=t;for(let h=0;h<c;h++){for(let a=0;a<s;a++){let f=i.get(r),l=n(a,h,u);Nl[r](e,f,l,o)}i.resetAfterLine()}}jl.dataToBitMap=function(t,e){let{width:n,height:r,depth:i,bpp:o,interlace:s}=e,c;if(i!==8)c=Rl(t,i);let u;if(i<=8)u=Buffer.alloc(n*r*4);else u=new Uint16Array(n*r*4);let h=Math.pow(2,i)-1,a=0,f,l;if(s)f=tc.getImagePasses(n,r),l=tc.getInterlaceIterator(n,r);else{let m=0;l=function(){let b=m;return m+=4,b},f=[{width:n,height:r}]}for(let m=0;m<f.length;m++)if(i===8)a=Ol(f[m],u,l,o,t,a);else Hl(f[m],u,l,o,c,h);if(i===8){if(a!==t.length)throw Error("extra data found")}else c.end();return u}});var Ai=bt((sb,ec)=>{function Gl(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=i[t[o]];if(!u)throw Error("index "+t[o]+" not in palette");for(let h=0;h<4;h++)e[o+h]=u[h];o+=4}}function Ll(t,e,n,r,i){let o=0;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=!1;if(i.length===1){if(i[0]===t[o])u=!0}else if(i[0]===t[o]&&i[1]===t[o+1]&&i[2]===t[o+2])u=!0;if(u)for(let h=0;h<4;h++)e[o+h]=0;o+=4}}function Tl(t,e,n,r,i){let o=255,s=Math.pow(2,i)-1,c=0;for(let u=0;u<r;u++)for(let h=0;h<n;h++){for(let a=0;a<4;a++)e[c+a]=Math.floor(t[c+a]*o/s+0.5);c+=4}}ec.exports=function(t,e,n=!1){let{depth:r,width:i,height:o,colorType:s,transColor:c,palette:u}=e,h=t;if(s===3)Gl(t,h,i,o,u);else{if(c)Ll(t,h,i,o,c);if(r!==8&&!n){if(r===16)h=Buffer.alloc(i*o*4);Tl(t,h,i,o,r)}}return h}});var ic=bt((cb,rc)=>{var Al=Gt("util"),Ui=Gt("zlib"),nc=Ni(),Ul=Ys(),Kl=Li(),Jl=Ti(),Wl=Ai(),ie=rc.exports=function(t){nc.call(this),this._parser=new Kl(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Al.inherits(ie,nc);ie.prototype._handleError=function(t){if(this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ie.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ui.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,Ui.Z_MIN_CHUNK);this._inflate=Ui.createInflate({chunkSize:r});let i=n,o=this.emit.bind(this,"error");this._inflate.on("error",function(c){if(!i)return;o(c)}),this._filter.on("complete",this._complete.bind(this));let s=this._filter.write.bind(this._filter);this._inflate.on("data",function(c){if(!i)return;if(c.length>i)c=c.slice(0,i);i-=c.length,s(c)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};ie.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ul(this._bitmapInfo)};ie.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ie.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ie.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ie.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ie.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ie.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Jl.dataToBitMap(t,this._bitmapInfo);e=Wl(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var sc=bt((ub,oc)=>{var Ct=Ve();oc.exports=function(t,e,n,r){let i=[Ct.COLORTYPE_COLOR_ALPHA,Ct.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let b=function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256}();if(r.bitDepth===8||r.bitDepth===16&&b)return t}let o=r.bitDepth!==16?t:new Uint16Array(t.buffer),s=255,c=Ct.COLORTYPE_TO_BPP_MAP[r.inputColorType];if(c===4&&!r.inputHasAlpha)c=3;let u=Ct.COLORTYPE_TO_BPP_MAP[r.colorType];if(r.bitDepth===16)s=65535,u*=2;let h=Buffer.alloc(e*n*u),a=0,f=0,l=r.bgColor||{};if(l.red===void 0)l.red=s;if(l.green===void 0)l.green=s;if(l.blue===void 0)l.blue=s;function m(){let b,g,$,y=s;switch(r.inputColorType){case Ct.COLORTYPE_COLOR_ALPHA:y=o[a+3],b=o[a],g=o[a+1],$=o[a+2];break;case Ct.COLORTYPE_COLOR:b=o[a],g=o[a+1],$=o[a+2];break;case Ct.COLORTYPE_ALPHA:y=o[a+1],b=o[a],g=b,$=b;break;case Ct.COLORTYPE_GRAYSCALE:b=o[a],g=b,$=b;break;default:throw Error("input color type:"+r.inputColorType+" is not supported at present")}if(r.inputHasAlpha){if(!i)y/=s,b=Math.min(Math.max(Math.round((1-y)*l.red+y*b),0),s),g=Math.min(Math.max(Math.round((1-y)*l.green+y*g),0),s),$=Math.min(Math.max(Math.round((1-y)*l.blue+y*$),0),s)}return{red:b,green:g,blue:$,alpha:y}}for(let b=0;b<n;b++)for(let g=0;g<e;g++){let $=m(o,a);switch(r.colorType){case Ct.COLORTYPE_COLOR_ALPHA:case Ct.COLORTYPE_COLOR:if(r.bitDepth===8){if(h[f]=$.red,h[f+1]=$.green,h[f+2]=$.blue,i)h[f+3]=$.alpha}else if(h.writeUInt16BE($.red,f),h.writeUInt16BE($.green,f+2),h.writeUInt16BE($.blue,f+4),i)h.writeUInt16BE($.alpha,f+6);break;case Ct.COLORTYPE_ALPHA:case Ct.COLORTYPE_GRAYSCALE:{let y=($.red+$.green+$.blue)/3;if(r.bitDepth===8){if(h[f]=y,i)h[f+1]=$.alpha}else if(h.writeUInt16BE(y,f),i)h.writeUInt16BE($.alpha,f+2);break}default:throw Error("unrecognised color Type "+r.colorType)}a+=c,f+=u}return h}});var hc=bt((hb,uc)=>{var cc=Oi();function xl(t,e,n,r,i){for(let o=0;o<n;o++)r[i+o]=t[e+o]}function Ql(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++)r+=Math.abs(t[o]);return r}function Zl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=t[e+s]-c;r[i+s]=u}}function ql(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=t[e+o]-s;i+=Math.abs(c)}return i}function _l(t,e,n,r,i){for(let o=0;o<n;o++){let s=e>0?t[e+o-n]:0,c=t[e+o]-s;r[i+o]=c}}function Cl(t,e,n){let r=0,i=e+n;for(let o=e;o<i;o++){let s=e>0?t[o-n]:0,c=t[o]-s;r+=Math.abs(c)}return r}function Xl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=t[e+s]-(c+u>>1);r[i+s]=h}}function Vl(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=t[e+o]-(s+c>>1);i+=Math.abs(u)}return i}function Yl(t,e,n,r,i,o){for(let s=0;s<n;s++){let c=s>=o?t[e+s-o]:0,u=e>0?t[e+s-n]:0,h=e>0&&s>=o?t[e+s-(n+o)]:0,a=t[e+s]-cc(c,u,h);r[i+s]=a}}function zl(t,e,n,r){let i=0;for(let o=0;o<n;o++){let s=o>=r?t[e+o-r]:0,c=e>0?t[e+o-n]:0,u=e>0&&o>=r?t[e+o-(n+r)]:0,h=t[e+o]-cc(s,c,u);i+=Math.abs(h)}return i}var Bl={0:xl,1:Zl,2:_l,3:Xl,4:Yl},Dl={0:Ql,1:ql,2:Cl,3:Vl,4:zl};uc.exports=function(t,e,n,r,i){let o;if(!("filterType"in r)||r.filterType===-1)o=[0,1,2,3,4];else if(typeof r.filterType==="number")o=[r.filterType];else throw Error("unrecognised filter types");if(r.bitDepth===16)i*=2;let s=e*i,c=0,u=0,h=Buffer.alloc((s+1)*n),a=o[0];for(let f=0;f<n;f++){if(o.length>1){let l=1/0;for(let m=0;m<o.length;m++){let b=Dl[o[m]](t,u,s,i);if(b<l)a=o[m],l=b}}h[c]=a,c++,Bl[a](t,u,s,h,c,i),c+=s,u+=s}return h}});var Ki=bt((ab,ac)=>{var Lt=Ve(),tg=Gi(),eg=sc(),ng=hc(),rg=Gt("zlib"),ke=ac.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||rg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType==="number"?t.colorType:Lt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType==="number"?t.inputColorType:Lt.COLORTYPE_COLOR_ALPHA,[Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw Error("option color type:"+t.colorType+" is not supported at present");if([Lt.COLORTYPE_GRAYSCALE,Lt.COLORTYPE_COLOR,Lt.COLORTYPE_COLOR_ALPHA,Lt.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw Error("option bit depth:"+t.bitDepth+" is not supported at present")};ke.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};ke.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};ke.prototype.filterData=function(t,e,n){let r=eg(t,e,n,this._options),i=Lt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return ng(r,e,n,this._options,i)};ke.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);if(r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e)e.copy(r,8);return r.writeInt32BE(tg.crc32(r.slice(4,r.length-4)),r.length-4),r};ke.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Lt.GAMMA_DIVISION),0),this._packChunk(Lt.TYPE_gAMA,e)};ke.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(Lt.TYPE_IHDR,n)};ke.prototype.packIDAT=function(t){return this._packChunk(Lt.TYPE_IDAT,t)};ke.prototype.packIEND=function(){return this._packChunk(Lt.TYPE_IEND,null)}});var dc=bt((fb,gc)=>{var ig=Gt("util"),fc=Gt("stream"),og=Ve(),sg=Ki(),lc=gc.exports=function(t){fc.call(this);let e=t||{};this._packer=new sg(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ig.inherits(lc,fc);lc.prototype.pack=function(t,e,n,r){if(this.emit("data",Buffer.from(og.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r)this.emit("data",this._packer.packGAMA(r));let i=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(o){this.emit("data",this._packer.packIDAT(o))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(i)}});var kc=bt((jn,$c)=>{var mc=Gt("assert").ok,Ye=Gt("zlib"),cg=Gt("util"),pc=Gt("buffer").kMaxLength;function He(t){if(!(this instanceof He))return new He(t);if(t&&t.chunkSize<Ye.Z_MIN_CHUNK)t.chunkSize=Ye.Z_MIN_CHUNK;if(Ye.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null)this._maxLength=t.maxLength}function ug(t){return new He(t)}function wc(t,e){if(e)process.nextTick(e);if(!t._handle)return;t._handle.close(),t._handle=null}He.prototype._processChunk=function(t,e,n){if(typeof n==="function")return Ye.Inflate._processChunk.call(this,t,e,n);let r=this,i=t&&t.length,o=this._chunkSize-this._offset,s=this._maxLength,c=0,u=[],h=0,a;this.on("error",function(b){a=b});function f(b,g){if(r._hadError)return;let $=o-g;if(mc($>=0,"have should not go down"),$>0){let y=r._buffer.slice(r._offset,r._offset+$);if(r._offset+=$,y.length>s)y=y.slice(0,s);if(u.push(y),h+=y.length,s-=y.length,s===0)return!1}if(g===0||r._offset>=r._chunkSize)o=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize);if(g===0)return c+=i-b,i=b,!0;return!1}mc(this._handle,"zlib binding closed");let l;do l=this._handle.writeSync(e,t,c,i,this._buffer,this._offset,o),l=l||this._writeState;while(!this._hadError&&f(l[0],l[1]));if(this._hadError)throw a;if(h>=pc)throw wc(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+pc.toString(16)+" bytes");let m=Buffer.concat(u,h);return wc(this),m};cg.inherits(He,Ye.Inflate);function hg(t,e){if(typeof e==="string")e=Buffer.from(e);if(!(e instanceof Buffer))throw TypeError("Not a string or buffer");let n=t._finishFlushFlag;if(n==null)n=Ye.Z_FINISH;return t._processChunk(e,n)}function bc(t,e){return hg(new He(e),t)}$c.exports=jn=bc;jn.Inflate=He;jn.createInflate=ug;jn.inflateSync=bc});var Ji=bt((lb,yc)=>{var Ec=yc.exports=function(t){this._buffer=t,this._reads=[]};Ec.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Ec.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var Mc=bt((lg)=>{var ag=Ji(),fg=Hi();lg.process=function(t,e){let n=[],r=new ag(t);return new fg(e,{read:r.read.bind(r),write:function(o){n.push(o)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Fc=bt((db,Ic)=>{var vc=!0,Sc=Gt("zlib"),dg=kc();if(!Sc.deflateSync)vc=!1;var mg=Ji(),pg=Mc(),wg=Li(),bg=Ti(),$g=Ai();Ic.exports=function(t,e){if(!vc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(v){n=v}let i;function o(v){i=v}function s(v){i.transColor=v}function c(v){i.palette=v}function u(){i.alpha=!0}let h;function a(v){h=v}let f=[];function l(v){f.push(v)}let m=new mg(t);if(new wg(e,{read:m.read.bind(m),error:r,metadata:o,gamma:a,palette:c,transColor:s,inflateData:l,simpleTransparency:u}).start(),m.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(i.interlace)$=Sc.inflateSync(g);else{let p=((i.width*i.bpp*i.depth+7>>3)+1)*i.height;$=dg(g,{chunkSize:p,maxLength:p})}if(g=null,!$||!$.length)throw Error("bad png - invalid inflate data response");let y=pg.process($,i);g=null;let F=bg.dataToBitMap(y,i);y=null;let E=$g(F,i,e.skipRescale);return i.data=E,i.gamma=h||0,i}});var Hc=bt((mb,Oc)=>{var Nc=!0,Rc=Gt("zlib");if(!Rc.deflateSync)Nc=!1;var kg=Ve(),Eg=Ki();Oc.exports=function(t,e){if(!Nc)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=new Eg(e||{}),i=[];if(i.push(Buffer.from(kg.PNG_SIGNATURE)),i.push(r.packIHDR(t.width,t.height)),t.gamma)i.push(r.packGAMA(t.gamma));let o=r.filterData(t.data,t.width,t.height),s=Rc.deflateSync(o,r.getDeflateOptions());if(o=null,!s||!s.length)throw Error("bad png - invalid compressed data response");return i.push(r.packIDAT(s)),i.push(r.packIEND()),Buffer.concat(i)}});var jc=bt((vg)=>{var yg=Fc(),Mg=Hc();vg.read=function(t,e){return yg(t,e||{})};vg.write=function(t,e){return Mg(t,e)}});var Gc=bt((Hg)=>{var Fg=Gt("util"),Pc=Gt("stream"),Ng=ic(),Rg=dc(),Og=jc(),Tt=Hg.PNG=function(t){if(Pc.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Ng(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new Rg(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};Fg.inherits(Tt,Pc);Tt.sync=Og;Tt.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};Tt.prototype.parse=function(t,e){if(e){let n,r;n=function(i){this.removeListener("error",r),this.data=i,e(null,this)}.bind(this),r=function(i){this.removeListener("parsed",n),e(i,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};Tt.prototype.write=function(t){return this._parser.write(t),!0};Tt.prototype.end=function(t){this._parser.end(t)};Tt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Tt.prototype._gamma=function(t){this.gamma=t};Tt.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};Tt.bitblt=function(t,e,n,r,i,o,s,c){if(n|=0,r|=0,i|=0,o|=0,s|=0,c|=0,n>t.width||r>t.height||n+i>t.width||r+o>t.height)throw Error("bitblt reading outside image");if(s>e.width||c>e.height||s+i>e.width||c+o>e.height)throw Error("bitblt writing outside image");for(let u=0;u<o;u++)t.data.copy(e.data,(c+u)*e.width+s<<2,(r+u)*t.width+n<<2,(r+u)*t.width+n+i<<2)};Tt.prototype.bitblt=function(t,e,n,r,i,o,s){return Tt.bitblt(this,t,e,n,r,i,o,s),this};Tt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let i=0;i<3;i++){let o=t.data[r+i]/255;o=Math.pow(o,0.45454545454545453/t.gamma),t.data[r+i]=Math.round(o*255)}}t.gamma=0}};Tt.prototype.adjustGamma=function(){Tt.adjustGamma(this)}});var Go=bt((zk,za)=>{var Po={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},h0={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},a0={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?Po.up():"");if(t)e+=Po.left;return e}};za.exports={cursor:Po,scroll:h0,erase:a0,beep:"\x07"}});import{spawnSync as Ow}from"node:child_process";import{isMainThread as Hw}from"node:worker_threads";import{parseArgs as Sw}from"node:util";var re={name:"@kecan0406/ttheme",version:"1.0.37",type:"module",bin:{ttheme:"bin/ttheme.js"},files:["bin","dist/manifest.json","shell","!shell/check.zsh"],description:"Character terminal palettes for Ghostty, kitty, Alacritty, WezTerm, iTerm2, Windows Terminal and Warp",license:"MIT",author:"kecan0406",repository:{type:"git",url:"git+https://github.com/kecan0406/ttheme.git"},homepage:"https://github.com/kecan0406/ttheme#readme",bugs:"https://github.com/kecan0406/ttheme/issues",keywords:["terminal","theme","ghostty","kitty","alacritty","wezterm","iterm2"],devDependencies:{"@biomejs/biome":"^2.3.0","@clack/core":"^1.4.3","@clack/prompts":"^1.7.0","@material/material-color-utilities":"^0.4.0","@types/bun":"^1.3.0","@types/pngjs":"6.0.5","jpeg-js":"^0.4.4",pngjs:"7.0.0",typescript:"^5.8.2"},engines:{bun:">=1.3",node:">=20.11"}};import{rmSync as uh}from"node:fs";import{basename as _d,join as tr}from"node:path";var sl=/^#[0-9a-f]{6}$/;function ds(t){return sl.test(t)}function jt(t){let e=Number.parseInt(t.slice(1),16);return[e>>16&255,e>>8&255,e&255]}function zt(t){let[e,n,r]=jt(t).map((i)=>{let o=i/255;return o<=0.03928?o/12.92:((o+0.055)/1.055)**2.4});return 0.2126*e+0.7152*n+0.0722*r}function ae(t,e){let n=zt(t),r=zt(e);return(Math.max(n,r)+0.05)/(Math.min(n,r)+0.05)}function Sr(t,e){return Math.round(ae(t,e)*100)/100}function cl(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function ms(t){let[e,n,r]=jt(t).map(cl),i=Math.cbrt(0.4122214708*e+0.5363325363*n+0.0514459929*r),o=Math.cbrt(0.2119034982*e+0.6806995451*n+0.1073969566*r),s=Math.cbrt(0.0883024619*e+0.2817188376*n+0.6299787005*r),c=1.9779984951*i-2.428592205*o+0.4505937099*s,u=0.0259040371*i+0.7827717662*o-0.808675766*s;return{l:0.2104542553*i+0.793617785*o-0.0040720468*s,c:Math.hypot(c,u),h:(Math.atan2(u,c)*180/Math.PI+360)%360}}var we=7,ps=3,ki=0.15,ws=1.6,Mi=[1,2,3,4,5,6,9,10,11,12,13,14],bs=[7,15],Ir=[1,2,3,4,5,6],Ms={1:{name:"red",center:19,width:25},2:{name:"green",center:132,width:35},3:{name:"yellow",center:88,width:35},4:{name:"blue",center:250,width:60},5:{name:"magenta",center:329,width:40},6:{name:"cyan",center:197,width:60}},ul=0.03,Ei=25,vs=15,Ss=0.08;function fe(t,e){let n=t.ansi[e];if(n===void 0)throw Error(`${t.name}: missing ANSI ${e}`);return n}function yi(t,e,n){let r=t.background;return e.flatMap((i)=>{let o=fe(t,i);return ae(o,r)<n?[`ANSI ${i} ${o} on ${r} is ${Sr(o,r)}:1, needs ${n}:1`]:[]})}function $s(t,e){return Math.min(...e.map((n)=>ae(fe(t,n),t.background)))}var Is=[{rule:"foreground",label:"foreground on background",unit:"ratio",min:we,measure:({foreground:t,background:e})=>ae(t,e),check:({foreground:t,background:e})=>ae(t,e)<we?[`foreground ${t} on ${e} is ${Sr(t,e)}:1, needs ${we}:1`]:[]},{rule:"accents",label:"weakest accent on background",unit:"ratio",min:ps,measure:(t)=>$s(t,Mi),check:(t)=>yi(t,Mi,ps)},{rule:"ansi0-dark",label:"ansi0 luminance",unit:"luminance",max:ki,measure:(t)=>zt(fe(t,0)),check:(t)=>{let e=fe(t,0);return zt(e)>ki?[`ANSI 0 ${e} has luminance ${zt(e).toFixed(3)}, needs <= ${ki}`]:[]}},{rule:"light-ansi",label:"ansi7 and ansi15 on background",unit:"ratio",min:we,measure:(t)=>$s(t,bs),check:(t)=>yi(t,bs,we)},{rule:"ansi8-visible",label:"ansi8 on background",unit:"ratio",min:ws,measure:(t)=>ae(fe(t,8),t.background),check:(t)=>yi(t,[8],ws)},{rule:"selection",label:"foreground on selection",unit:"ratio",min:we,measure:({foreground:t,selectionBackground:e})=>e===void 0?Number.NaN:ae(t,e),check:({foreground:t,selectionBackground:e})=>e!==void 0&&ae(t,e)<we?[`foreground ${t} on selection ${e} is ${Sr(t,e)}:1, needs ${we}:1`]:[]}];function vi(t,e){let n=Math.abs(t-e)%360;return Math.min(n,360-n)}var Si=(t)=>t>8?t-8:t;function Fs(t){let e=t.signatureSlots.filter((n)=>n.startsWith("ansi")).map((n)=>Number(n.slice(4)));return new Set(e.flatMap((n)=>Ir.includes(Si(n))?[n,n>8?n-8:n+8]:[n]))}function Fn(t,e){let n=ms(fe(t,e));return n.c<ul?void 0:n}function ks(t){let e=Fs(t);return Mi.flatMap((n)=>{let r=Fn(t,n),i=Ms[Si(n)];if(r===void 0||i===void 0||e.has(n))return[];let o=vi(r.h,i.center)-i.width;return o>0?[{slot:n,hue:r.h,over:o}]:[]})}function Es(t){let e=new Set(t.signatureSlots);return Ir.flatMap((n)=>{let r=Fn(t,n),i=Fn(t,n+8);if(r===void 0||i===void 0||e.has(`ansi${n}`)&&e.has(`ansi${n+8}`))return[];return[{normal:n,gap:vi(r.h,i.h)}]})}function ys(t){let e=Fs(t);return[0,8].flatMap((n)=>Ir.flatMap((r)=>Ir.filter((i)=>i>r).flatMap((i)=>{let[o,s]=[n+r,n+i],c=Fn(t,o),u=Fn(t,s);if(c===void 0||u===void 0||e.has(o)&&e.has(s))return[];return vi(c.h,u.h)<vs&&Math.abs(c.l-u.l)<Ss?[[o,s]]:[]})))}var hl=[{rule:"ansi-role",label:"accent hue outside its ANSI role",unit:"degrees",max:0,measure:(t)=>Math.max(0,...ks(t).map((e)=>e.over)),check:(t)=>ks(t).map(({slot:e,hue:n,over:r})=>{let i=Ms[Si(e)];return`ANSI ${e} ${fe(t,e)} has hue ${n.toFixed(0)}°, ${r.toFixed(0)}° outside ${i.name} (${i.center}±${i.width}°)`})},{rule:"bright-follows",label:"widest normal to bright hue gap",unit:"degrees",max:Ei,measure:(t)=>Math.max(0,...Es(t).map((e)=>e.gap)),check:(t)=>Es(t).filter((e)=>e.gap>Ei).map(({normal:e,gap:n})=>`ANSI ${e+8} is ${n.toFixed(0)}° from ANSI ${e}, needs <= ${Ei}°`)},{rule:"distinct",label:"accent pairs that read as one color",unit:"pairs",max:0,measure:(t)=>ys(t).length,check:(t)=>ys(t).map(([e,n])=>`ANSI ${e} ${fe(t,e)} and ANSI ${n} ${fe(t,n)} are within ${vs}° hue and ${Ss} lightness`)}],Fr=[...Is,...hl],Aw=Fr.map((t)=>t.rule),Nr=Fr.map(({rule:t,label:e,unit:n,min:r,max:i})=>({rule:t,label:e,unit:n,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}));function Ns(t){return Fr.map((e)=>Math.round(e.measure(t)*1000)/1000)}function Rs(t,e){return t.filter((n)=>!e.waive.includes(n.rule)).flatMap((n)=>n.check(e).map((r)=>({theme:e.name,rule:n.rule,detail:r})))}function al(t){return Rs(Fr,t)}function Os(t){return Rs(Is,t)}function Hs(t){return t.flatMap(al)}var fl=["black","red","green","yellow","blue","magenta","cyan","white"];function js(t,e){return[t,...fl.map((n,r)=>`${n} = '${e[r]}'`),""].join(`
|
|
3
|
+
`)}var Nn={id:"alacritty",limits:"no runtime color API (OSC only)",emit(t){let e=[...Ce(t),"","[colors.primary]",`background = '${t.background}'`,`foreground = '${t.foreground}'`,"","[colors.cursor]",`cursor = '${t.cursor}'`,`text = '${t.background}'`,"","[colors.selection]",`background = '${t.selectionBackground}'`,`text = '${t.foreground}'`,"",js("[colors.normal]",t.ansi.slice(0,8)),js("[colors.bright]",t.ansi.slice(8,16))].join(`
|
|
4
|
+
`);return[{path:`alacritty/themes/${ct(t.name)}.toml`,content:e}]}};var Rn={id:"ghostty",emit(t){let e=[...Ce(t),`background = ${t.background}`,`foreground = ${t.foreground}`,`cursor-color = ${t.cursor}`,`selection-background = ${t.selectionBackground}`,`selection-foreground = ${t.foreground}`,...t.ansi.map((n,r)=>`palette = ${r}=${n}`),"palette-generate = true","","macos-icon = custom-style",`macos-icon-ghost-color = ${t.ghostty.iconGhost}`,`macos-icon-screen-color = ${t.ghostty.iconScreen.join(",")}`,"macos-icon-frame = chrome",""].join(`
|
|
5
|
+
`);return[{path:`ghostty/themes/${ct(t.name)}`,content:e}]}};function be(t){let[e,n,r]=jt(t);return{"Alpha Component":1,"Blue Component":r/255,"Color Space":"P3","Green Component":n/255,"Red Component":e/255}}function Ps(t){return{...Object.fromEntries(t.ansi.map((e,n)=>[`Ansi ${n} Color`,be(e)])),"Background Color":be(t.background),"Bold Color":be(t.foreground),"Cursor Color":be(t.cursor),"Cursor Text Color":be(t.background),"Foreground Color":be(t.foreground),"Selected Text Color":be(t.foreground),"Selection Color":be(t.selectionBackground)}}function ll(t){return t?{"Background Image Location":t.image,"Background Image Mode":t.cover?2:3,Blend:t.opacity}:{"Background Image Location":""}}function Gs(t,e,n,r){let i=(s,c)=>({Name:`ttheme · ${c}`,Guid:`ttheme-${c}`,...r?{"Dynamic Profile Parent GUID":r}:{},"Use Separate Colors for Light and Dark Mode":!1,"Harmonize 256 Colors":!0,...ll(e.get(s.name)),...Ps(s)}),o=[...n?[i(n,"default")]:[],...t.map((s)=>i(s,s.name))];return`${JSON.stringify({Profiles:o},null,2)}
|
|
6
|
+
`}function gl(t,e){return[` <key>${t}</key>`,"\t<dict>",...Object.entries(e).flatMap(([n,r])=>[` <key>${n}</key>`,typeof r==="string"?` <string>${r}</string>`:` <real>${r}</real>`]),"\t</dict>"].join(`
|
|
7
|
+
`)}var On={id:"iterm2",limits:"colors are Display P3, the space iTerm2 reads OSC colors in",emit(t){let e=['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>",...Object.entries(Ps(t)).map(([n,r])=>gl(n,r)),"</dict>","</plist>",""].join(`
|
|
8
|
+
`);return[{path:`iterm2/${ct(t.name)}.itermcolors`,content:e}]}};var Hn={id:"kitty",emit(t){let e=[...Ce(t),`background ${t.background}`,`foreground ${t.foreground}`,`cursor ${t.cursor}`,`cursor_text_color ${t.background}`,`selection_background ${t.selectionBackground}`,`selection_foreground ${t.foreground}`,...t.ansi.map((n,r)=>`color${r} ${n}`),""].join(`
|
|
9
|
+
`);return[{path:`kitty/themes/${ct(t.name)}.conf`,content:e}]}};function Ls(t){return["# Generated by ttheme — rewritten on every add, remove and default; do not edit.","import os","",`THEMES = ${JSON.stringify(t.themes)}`,`BACKGROUNDS = ${JSON.stringify(t.backgrounds)}`,"PLACES = {"," 'top-left': 'top-left', 'top-center': 'top', 'top-right': 'top-right',"," 'center-left': 'left', 'center': 'center', 'center-center': 'center', 'center-right': 'right',"," 'bottom-left': 'bottom-left', 'bottom-center': 'bottom', 'bottom-right': 'bottom-right',","}","","shown = {}","faded = {}","worn = {}","","","def locate(path):"," if path.startswith('~/'):"," return os.path.expanduser(path)"," return path if os.path.isabs(path) else os.path.join(BACKGROUNDS, path)","","","def read(path, into):"," try:"," with open(path, encoding='utf-8') as f:"," lines = f.read().splitlines()"," except OSError:"," return False"," for line in lines:"," key, sep, value = line.partition('=')"," key, value = key.strip(), value.strip()"," if not sep or not key or key.startswith('#'):"," continue"," if key == 'config-file':"," read(locate(value.lstrip('?')), into)"," else:"," into[key] = value"," return True","","","def logo(palette):"," c = {}"," if not palette or not read(os.path.join(BACKGROUNDS, palette + '.conf'), c):"," return None"," image = c.get('background-image', '')"," try:"," opacity = min(float(c.get('background-image-opacity', '1')), 1.0)"," except ValueError:"," opacity = 1.0"," if not image or opacity <= 0:"," return None"," return locate(image), PLACES.get(c.get('background-image-position', 'center'), 'center'), opacity","","","def fade(path, opacity):"," key = f'{path}#{opacity}'"," if key not in faded:"," from kitty.fast_data_types import load_png_data, png_from_32bit_rgba_data"," with open(path, 'rb') as f:"," rgba, width, height = load_png_data(f.read())"," data = bytearray(rgba)"," data[3::4] = data[3::4].translate(bytes(round(a * opacity) for a in range(256)))"," if len(faded) > 8:"," faded.clear()"," faded[key] = png_from_32bit_rgba_data(bytes(data), width, height)"," return key, faded[key]","","","def show(window):"," want = logo(window.user_vars.get('ttheme_shown') or '')"," if window.id in shown and shown[window.id] == want:"," return"," shown[window.id] = want"," try:"," if want is None:"," window.set_logo('')"," elif want[2] < 1:"," key, png = fade(want[0], want[2])"," window.set_logo(key, want[1], 1, png)"," else:"," window.set_logo(want[0], want[1], 1)"," except Exception:"," shown.pop(window.id, None)","","","def theme(palette):"," path = os.path.join(THEMES, 'ttheme-' + palette + '.conf')"," if not palette or not os.path.exists(path):"," return None"," from kitty.colors import parse_colors"," return parse_colors([path])","","","def wear(palette):"," colors = theme(palette) if worn.get('startup') != palette else None"," if colors is None:"," return"," from kitty.colors import patch_colors"," patch_colors(colors[0], colors[1], True, ())"," worn['startup'] = palette","","","def rewear(boss):"," from kitty.colors import patch_colors"," for window in tuple(boss.all_windows):"," colors = theme(window.user_vars.get('ttheme_worn') or '')"," if colors is not None:"," patch_colors(colors[0], colors[1], False, (window,))","","","def on_load(boss, data):"," if getattr(boss, 'ttheme_rewears', False):"," return"," load = boss.load_config_file",""," def reload(*args, **kwargs):"," load(*args, **kwargs)"," worn.pop('startup', None)"," rewear(boss)",""," boss.load_config_file = reload"," boss.ttheme_rewears = True","","","def on_set_user_var(boss, window, data):"," if data['key'] == 'ttheme_shown':"," show(window)"," elif data['key'] == 'ttheme_startup':"," wear(data['value'] or '')","","","def on_focus_change(boss, window, data):"," if data['focused']:"," show(window)","","","def on_close(boss, window, data):"," shown.pop(window.id, None)",""].join(`
|
|
10
|
+
`)}import{createHash as Gg}from"node:crypto";import{mkdirSync as qc,readdirSync as je,readFileSync as _c,renameSync as Cc,rmSync as Be,statSync as Lg,utimesSync as Tg,writeFileSync as jr}from"node:fs";import{isAbsolute as Ag,join as Mt}from"node:path";var Ac=vr(xs(),1),Or=vr(Gc(),1),Lc=[137,80,78,71,13,10,26,10],Uc=13;function Pn(t){return t.length>=Lc.length&&Lc.every((e,n)=>t[n]===e)}function jg(t){let e=Or.PNG.sync.read(Buffer.from(t));return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function Kc(t,e){if(Pn(t)){let n=Gn(t);if(n&&n.width*n.height>e)throw Error(`${n.width}×${n.height} is over ${e/1e6} megapixels`);return jg(t)}if(t[0]===255&&t[1]===216){let n=Ac.decode(t,{useTArray:!0,formatAsRGBA:!0,maxResolutionInMP:e/1e6,maxMemoryUsageInMB:1024});return{width:n.width,height:n.height,data:n.data}}throw Error("not a PNG or JPEG image")}function ze(t){let e=new Or.PNG({width:t.width,height:t.height});return e.data=Buffer.from(t.data),Or.PNG.sync.write(e)}function Tc(t,e){for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let i=0;i<e.length&&r;i++)r=t[n+i]===e.charCodeAt(i);if(r)return n}return-1}function Gn(t){if(t.length<33||!Pn(t))return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint32(16),r=e.getUint32(20);if(t[25]===4||t[25]===6)return{width:n,height:r,alpha:!0};let i=Tc(t,"IDAT");return{width:n,height:r,alpha:Tc(i===-1?t:t.subarray(0,i),"tRNS")!==-1}}function Jc(t,e=Uc){let{width:n,height:r}=t,i=-1,o=-1;for(let s=0;s<t.height;s++)for(let c=0;c<t.width;c++)if((t.data[(s*t.width+c)*4+3]??0)>=e)n=Math.min(n,c),i=Math.max(i,c),r=Math.min(r,s),o=Math.max(o,s);return i<0?null:{x:n,y:r,w:i-n+1,h:o-r+1}}function Ln(t,e={x:0,y:0,w:t.width,h:t.height}){let n=0;for(let r=e.y;r<e.y+e.h;r++)for(let i=e.x;i<e.x+e.w;i++)if((t.data[(r*t.width+i)*4+3]??0)<Uc)n++;return Math.round(n*100/(e.w*e.h))}function Pg(t,e){if(e<=1)return t;let n=Math.max(1,Math.floor(t.width/e)),r=Math.max(1,Math.floor(t.height/e)),i=new Uint8Array(n*r*4),o=t.data;for(let s=0;s<r;s++)for(let c=0;c<n;c++){let u=0,h=0,a=0,f=0;for(let m=0;m<e;m++)for(let b=0;b<e;b++){let g=((s*e+m)*t.width+c*e+b)*4,$=o[g+3]??0;u+=(o[g]??0)*$,h+=(o[g+1]??0)*$,a+=(o[g+2]??0)*$,f+=$}let l=(s*n+c)*4;if(f>0)i[l]=Math.round(u/f),i[l+1]=Math.round(h/f),i[l+2]=Math.round(a/f);i[l+3]=Math.round(f/(e*e))}return{width:n,height:r,data:i}}function Wc(t,e,n){let r=Math.min(e/t.width,n/t.height),i=Math.max(1,Math.round(t.width*r)),o=Math.max(1,Math.round(t.height*r)),s=Hr(t,{x:0,y:0,w:t.width,h:t.height},i,o),c=new Uint8Array(e*n*4),u=Math.floor((e-i)/2),h=Math.floor((n-o)/2);for(let a=0;a<o;a++)c.set(s.data.subarray(a*i*4,(a+1)*i*4),((h+a)*e+u)*4);return{width:e,height:n,data:c}}function Hr(t,e,n,r){let i=Math.max(1,Math.floor(Math.min(e.w/n,e.h/r))),o=Pg(t,i),s=o.data,c=new Uint8Array(n*r*4);for(let u=0;u<r;u++){let h=Math.min(o.height-1,Math.max(0,e.y/i+(u+0.5)*e.h/i/r-0.5)),a=Math.floor(h),f=Math.min(o.height-1,a+1),l=h-a;for(let m=0;m<n;m++){let b=Math.min(o.width-1,Math.max(0,e.x/i+(m+0.5)*e.w/i/n-0.5)),g=Math.floor(b),$=Math.min(o.width-1,g+1),y=b-g,F=(a*o.width+g)*4,E=(a*o.width+$)*4,v=(f*o.width+g)*4,p=(f*o.width+$)*4,j=(s[F+3]??0)*(1-y)*(1-l),k=(s[E+3]??0)*y*(1-l),H=(s[v+3]??0)*(1-y)*l,R=(s[p+3]??0)*y*l,L=j+k+H+R,P=(u*n+m)*4;if(L>0)for(let C=0;C<3;C++){let U=(s[F+C]??0)*j+(s[E+C]??0)*k+(s[v+C]??0)*H+(s[p+C]??0)*R;c[P+C]=Math.round(U/L)}c[P+3]=Math.round(L)}}return{width:n,height:r,data:c}}var xc={width:2560,height:1550},Ug=2560,Kg=0.1,le={tall:1.15,reach:0.4,widest:0.95,headroom:0.04,margin:0.03,stands:12},Jg=zt(Wi("#19161e","#9b86c8",0.2)),Wg="shelf";function Wi(t,e,n){let r=jt(t),i=jt(e);return`#${r.map((o,s)=>Math.round(o+((i[s]??0)-o)*n).toString(16).padStart(2,"0")).join("")}`}function xg(t,e){if(e==="background"||e==="foreground"||e==="cursor")return t[e];if(e==="selection"&&t.selection)return t.selection;let n=/^ansi(\d|1[0-5])$/.exec(e),r=n?t.ansi[Number(n[1])]:void 0;if(!r)throw Error(`${t.name} has no slot ${e}`);return r}function Qc(t){if(t(1))return 1;let e=0,n=1;for(let r=0;r<40;r++){let i=(e+n)/2;if(t(i))e=i;else n=i}return e}function Zc(t,e){let n=xg(t,e),i=Qc((h)=>Os({name:t.name,background:Wi(t.background,n,h),foreground:t.foreground,ansi:t.ansi,waive:t.waived??[]}).length===0),o=Qc((h)=>zt(Wi(t.background,n,h))<=Jg),s=Math.floor(Math.min(i,o)*1000)/1000,c=jt(t.background),u=Math.hypot(...jt(n).map((h,a)=>(h-(c[a]??0))*s));return{slot:e,color:n,cap:i,matched:o,opacity:s,reach:u}}function Pr(t,e){let n=Zc(t,"cursor");if(n.opacity>=Kg)return n;return e.filter((r)=>r!=="cursor"&&r!=="background").map((r)=>Zc(t,r)).reduce((r,i)=>i.reach>r.reach?i:r,n)}function xi(t,e,n){let r=jt(e),i=jt(n),o=t.data;for(let s=0;s<o.length;s+=4){let c=(0.299*(o[s]??0)+0.587*(o[s+1]??0)+0.114*(o[s+2]??0))/255;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)+((i[u]??0)-(r[u]??0))*c)}return t}function Qg(t,e,n){let r=jt(e),i=t.data,o=new Uint8Array(i.length);for(let s=0;s<i.length;s+=4){let c=(i[s+3]??0)/255*n;for(let u=0;u<3;u++)o[s+u]=Math.round((r[u]??0)*(1-c)+(i[s+u]??0)*c);o[s+3]=255}return{width:t.width,height:t.height,data:o}}function Xc(t){return Jc(t)??{x:0,y:0,w:t.width,h:t.height}}function Zg(t,e){if(t<=0||e<=0)return xc;let n=Math.min(1,xc.width/Math.max(t,e));return{width:Math.round(t*n),height:Math.round(e*n)}}function qg(t,e){let n=Math.min(1,Ug/Math.max(e.w,e.h));return Hr(t,e,Math.round(e.w*n),Math.round(e.h*n))}function Vc(t,e,n,r){if(r<le.stands){let u=t.w*n>t.h*e?{x:t.x+(t.w-t.h*e/n)/2,y:t.y,w:t.h*e/n,h:t.h}:{x:t.x,y:t.y,w:t.w,h:t.w*n/e};return{crop:u,at:{x:0,y:0,w:e,h:n},focus:(u.y-t.y+u.h/2)/t.h}}let i=Math.max(le.tall*n,le.reach*e*t.h/t.w),o=i*t.w/t.h;if(o>le.widest*e)o=le.widest*e,i=o*t.h/t.w;let s=le.headroom*n,c=Math.min(1,(n-s)/i);return{crop:{x:t.x,y:t.y,w:t.w,h:t.h*c},at:{x:e*(1-le.margin)-o,y:s,w:o,h:i*c},focus:Math.min(1,(n/2-s)/i)}}function Yc(t,e,n,r){let i=Math.max(1,Math.round(e.at.w)),o=Math.max(1,Math.round(e.at.h)),s=Hr(t,e.crop,i,o),c=new Uint8Array(n*r*4),u=Math.round(e.at.x),h=Math.round(e.at.y);for(let a=0;a<o;a++){let f=h+a,l=Math.max(0,-u),m=Math.min(i,n-u);if(f<0||f>=r||m<=l)continue;c.set(s.data.subarray((a*i+l)*4,(a*i+m)*4),(f*n+u+l)*4)}return{width:n,height:r,data:c}}function zc(t,e,n,r,i){let o=Xc(t),s=Yc(t,Vc(o,r,i,Ln(t,o)),r,i);return Qg(xi(s,e.background,n.color),e.background,n.opacity)}function Ee(t){return Mt(t,"ttheme","backgrounds")}function _g(t,e,n,r,i){return[...r?[`# from ${r}`]:[],...i?[`# image ${i}`]:[],`background-image = ${e}`,"background-image-fit = cover","background-image-position = top-right",`background-image-opacity = ${n}`,`config-file = ?${t}.tune.conf`,`config-file = ?${t}.off.conf`,""].join(`
|
|
11
|
+
`)}function Bc(t,e,n){let r=new Map;for(let s of[`${e}.conf`,`${e}.tune.conf`,`${e}.off.conf`]){let c;try{c=_c(Mt(t,s),"utf8")}catch{if(s===`${e}.conf`)return;continue}for(let u of c.split(`
|
|
12
|
+
`)){let h=/^(background-image(?:-fit|-opacity)?)\s*=\s*(.*?)\s*$/.exec(u);if(h)r.set(h[1],h[2])}}let i=r.get("background-image")??"";if(i==="")return;let o=Number(r.get("background-image-opacity")??1);return{image:i.startsWith("~/")?Mt(n,i.slice(2)):Ag(i)?i:Mt(t,i),opacity:Number.isFinite(o)?o:1,cover:r.get("background-image-fit")==="cover"}}function Cg(t,e){for(let n of je(t))if(Qi(n,e))Be(Mt(t,n))}function Xg(t){return`${t.site}_${t.id}`}function Gr(t,e){return Mt(t,Wg,e)}function Qi(t,e){let n=t.slice(e.length);return t.startsWith(e)&&(n===".conf"||n===".tune.conf"||n===".off.conf"||/^(\.[0-9a-f]{8})?(@[a-z0-9-]+)?\.png$/.test(n))}function Tn(t,e){try{return/^# image (\S+)$/m.exec(_c(Mt(t,`${e}.conf`),"utf8"))?.[1]}catch{return}}function Vg(t,e){try{return je(Gr(t,e))}catch{return[]}}function Dc(t,e){let n=Tn(t,e);return[...n?[n]:[],...Vg(t,e)].sort()}function tu(t,e){let n=Tn(t,e);if(!n)return;let r=Mt(Gr(t,e),n);Be(r,{recursive:!0,force:!0}),qc(r,{recursive:!0});for(let i of je(t))if(Qi(i,e))Cc(Mt(t,i),Mt(r,i.slice(e.length)))}function eu(t,e,n){let r=Mt(Gr(t,e),n);for(let i of je(r))Cc(Mt(r,i),Mt(t,`${e}${i}`));Be(r,{recursive:!0})}function nu(t,e,n){try{return je(Mt(t,"originals")).find((r)=>r.startsWith(`${e}-${n}.`))}catch{return}}function ru(t,e,n){let r=nu(t,e,n);if(r){let i=new Date;Tg(Mt(t,"originals",r),i,i)}}function iu(t,e,n){let r=Ee(t),i=Dc(r,e),o=Tn(r,e);if(!o||i.length<2)throw Error(`${e} has no other image`);let s=(i.indexOf(o)+n+i.length)%i.length,c=i[s];return tu(r,e),eu(r,e,c),ru(r,e,c),{key:c,at:s+1,of:i.length}}function ou(t,e){let n=Ee(t),r=je(n).filter((h)=>Qi(h,e));if(r.length===0)throw Error(`${e} has no image`);let i=Dc(n,e),o=Tn(n,e),s=o&&nu(n,e,o);if(s)Be(Mt(n,"originals",s));for(let h of r)Be(Mt(n,h));let c=i.filter((h)=>h!==o),u=c[(o?i.indexOf(o):0)%c.length];if(u)eu(n,e,u),ru(n,e,u);return{key:o,left:c.length}}function Yg(t,e,n){if(Tn(t,e)!==n)tu(t,e);if(n)Be(Mt(Gr(t,e),n),{recursive:!0,force:!0});Cg(t,e)}function su(t,e,n,r,i,o){let s=Ee(t),c=e.name,u=Xg(i);qc(Mt(s,"originals"),{recursive:!0}),Yg(s,c,u);let h=Xc(r),{width:a,height:f}=Zg(o.width,o.height),l=Vc(h,a,f,Ln(r,h)),m=ze(xi(qg(r,h),e.background,n.color)),b=ze(xi(Yc(r,l,a,f),e.background,n.color)),g=Mt(s,`${c}.${Gg("sha1").update(m).update(b).digest("hex").slice(0,8)}`),$=`${g}.png`,y=`${g}@fill-${Math.round(l.focus*100)}.png`,F=Mt(s,`${c}.conf`),E=Mt(s,"originals",`${c}-${i.site}_${i.id}.${i.ext}`);return jr($,m),jr(y,b),jr(F,_g(c,y,n.opacity,i.from,u)),jr(E,i.bytes),[$,y,F,E]}function cu(t){let e=Mt(Ee(t),"originals"),n=new Map,r;try{r=je(e)}catch{return new Map}for(let i of r){let o=/^(.+)-([a-z.]+)_(\d+)\.[a-z]+$/.exec(i),[,s,c,u]=o??[];if(!s||!c||!u)continue;let h=Lg(Mt(e,i)).mtimeMs,a=n.get(s);if(!a||h>a.at)n.set(s,{site:c,id:Number(u),at:h})}return new Map([...n].map(([i,{site:o,id:s}])=>[i,{site:o,id:s}]))}function Zi(t){let{slot:e,color:n,opacity:r}=Pr({name:t.name,background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,ansi:t.ansi,waived:t.waive},t.signatureSlots);return{name:t.name,group:t.group,...t.native?{native:t.native}:{},...t.lead?{lead:!0}:{},order:t.order,ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},...t.role==="default"?{default:!0}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selection:t.selectionBackground,signature:t.signature,signatureSlots:t.signatureSlots,ansi:t.ansi,gate:Ns(t),...t.waive.length>0?{waived:t.waive}:{},backdrop:{slot:e,color:n,opacity:r}}}function Pe(t){return t.filter((e)=>e.default!==!0)}function zg(t){let[e]=t;if(!e)throw Error("manifest needs at least one theme");return{version:re.version,gate:Nr,placement:le,palettes:t.map(Zi)}}var qi={id:"meta",emitShared(t){return[{path:"manifest.json",content:`${JSON.stringify(zg(t),null,2)}
|
|
13
|
+
`}]}};import{readdirSync as Rd,readFileSync as Pu}from"node:fs";import{basename as Od,join as Gu}from"node:path";import{readdirSync as Bg,rmSync as Dg,statSync as td}from"node:fs";import{setDefaultAutoSelectFamilyAttemptTimeout as ed}from"node:net";import{homedir as nd}from"node:os";import{join as Un}from"node:path";import{setTimeout as rd}from"node:timers/promises";var Ge=100,Te=25000000,id=536870912,Kn=["safe","questionable","explicit"],Le=["nudity","underwear"],od={nudity:new Set(["nude","naked","topless","bottomless","nipples","naked_towel","undressing"]),underwear:new Set(["underwear","panties","pantsu","bra","lingerie","pantyshot"])},An={safe:"s",questionable:"q",explicit:"e"},sd=8191,cd=20000,ud=5000,uu=3000,hu=8,hd=3000,gu=60000,au=3,Ci=`ttheme/${re.version} (+${re.homepage})`,ad=["orig","tile","thumb","cut"],du=new Map,fd=Ed(process.env.TTHEME_FIND_HOSTS),ld=kd(process.env.TTHEME_FIND_CUTOUTS);ed(hd);function fu(t){try{return Bg(t)}catch{return[]}}function Lr(t){return t.startsWith("//")?`https:${t}`:t}function Jn(t){return(/\.([a-z0-9]+)(?:\?.*)?$/i.exec(t)?.[1]??"").toLowerCase()}function Wn(t){let e=t.trim();if(!e)return[];let n=JSON.parse(e);if(Array.isArray(n))return n;let r=n.posts;return Array.isArray(r)?r:[]}function gd(t){let e=t.trim(),r=(e?JSON.parse(e):{}).tags??{};return new Map(Object.entries(r).map(([i,o])=>[i,String(o)]))}function _i(t,e,n){let r=Lr(String(t??""));return{file:r,width:Number(e)||0,height:Number(n)||0,ext:Jn(r)}}function mu(t,e){let n=Lr(String(e.preview??""));if(!e.file||!n||!Number(t.id))return[];let r=Number(t.width??t.image_width)||0,i=Number(t.height??t.image_height)||0;return[{id:Number(t.id),width:r,height:i,file:e.file,preview:n,ext:e.ext,owner:String(e.owner??""),artist:e.artist,score:Number(t.score)||0,rating:String(t.rating??""),md5:String(e.md5??""),source:String(t.source??""),tags:e.tags.split(/\s+/).filter(Boolean),solo:e.solo,family:Number(t.parent_id)||(t.has_children===!0?Number(t.id):0),smaller:e.versions.filter((o)=>o.file&&o.width>0&&o.height>0&&o.width*o.height<r*i)}]}function dd(t){let e=gd(t);return Wn(t).flatMap((n)=>{let r=Lr(String(n.file_url??"")),i=String(n.tags??"");return mu(n,{preview:n.preview_url,file:r,ext:String(n.file_ext||Jn(r)).toLowerCase(),owner:n.author,artist:i.split(/\s+/).find((o)=>e.get(o)==="artist")??"",md5:n.md5,tags:i,solo:void 0,versions:[_i(n.jpeg_url,n.jpeg_width,n.jpeg_height),_i(n.sample_url,n.sample_width,n.sample_height)]})})}function md(t){return Wn(t).flatMap((e)=>{let n=Lr(String(e.file_url??"")),r=String(e.tag_string??""),i=e.media_asset??{};return mu(e,{preview:i.variants?.find((o)=>o.type==="360x360")?.url??e.preview_file_url,file:n,ext:String(e.file_ext||Jn(n)).toLowerCase(),owner:"",artist:String(e.tag_string_artist??"").split(/\s+/)[0]??"",md5:e.md5,tags:r,solo:r.split(/\s+/).includes("solo"),versions:(i.variants??[]).map((o)=>_i(o.url,o.width,o.height)).filter((o)=>o.ext==="jpg"||o.ext==="png").sort((o,s)=>s.width*s.height-o.width*o.height)})})}function pd(t){return Wn(t).flatMap((e)=>{let n=String(e.value??"");return n?[{value:n,count:Number(e.post_count)||0}]:[]})}function wd(t){return Wn(t).flatMap((e)=>{let n=String(e.name??"");return n?[{value:n,count:Number(e.count)||0}]:[]})}function bd(t){return Number(/count="(\d+)"/.exec(t)?.[1]??0)}function $d(t){let e=t.trim()?JSON.parse(t):{};return Number(e.counts?.posts)||0}function kd(t){let e=new Map;for(let n of(t??"").split(/\s+/).filter(Boolean)){let r=n.indexOf("=");if(r>0)e.set(n.slice(0,r),n.slice(r+1).split(",").filter(Boolean))}return e}function Ed(t){let e=new Map;for(let n of(t??"").split(/[\s,]+/).filter(Boolean)){let r=n.indexOf("="),i=n.slice(0,r);try{let o=new URL(n.slice(r+1));if(i&&o.protocol==="https:")e.set(i,o.origin)}catch{}}return e}function pu(t,e,n,r){let i=(t??"").split(/\s+/);if(r!==void 0&&i.includes(r))return[];let o=e.filter((s)=>i.includes(s));return o.length>0?o:[...n]}function Tr(t){return pu(t,Kn,["safe"])}function Ar(t){return pu(t,Le,Le,"none")}function wu(t,e,n){return{safe:new Set(t),questionable:new Set(e),explicit:new Set(n)}}function bu(t){let e=fd.get(t.key),n=ld.get(t.key);return{...t,origin:e??t.origin,moved:e!==void 0&&e!==t.origin,cutouts:n??t.cutouts,vouched:t.vouched&&n===void 0}}function $u(t){return t.length<2?t.join(""):t.map((e)=>`~${e}`).join(" ")}function lu(t){let e=bu(t),n=(r)=>new URLSearchParams({api_version:"2",include_tags:"1",...r});return{...e,cutouts:$u(e.cutouts),ratings:wu([An.safe],[An.questionable],[An.explicit]),rate:(r)=>{let[i]=r;if(r.length===1&&i)return`rating:${An[i]}`;let o=Kn.filter((c)=>!r.includes(c)),[s]=o;return o.length===1&&s?`-rating:${An[s]}`:""},best:"order:score",tagBudget:Number.POSITIVE_INFINITY,postsUrl:(r,i)=>`${e.origin}/post.json?${n({limit:String(Ge),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/post.xml?${new URLSearchParams({limit:"1",tags:r})}`,postUrl:(r)=>`${e.origin}/post.json?${n({tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/post/show/${r}`,parse:dd,count:bd}}function yd(t){let e=bu(t),n=wu(["g"],["s","q"],["e"]);return{...e,cutouts:$u(e.cutouts),ratings:n,rate:(r)=>r.length===Kn.length?"":`rating:${r.flatMap((i)=>[...n[i]]).join(",")}`,best:"order:score",tagBudget:2,postsUrl:(r,i)=>`${e.origin}/posts.json?${new URLSearchParams({limit:String(Ge),page:String(i+1),tags:r})}`,countUrl:(r)=>`${e.origin}/counts/posts.json?${new URLSearchParams({tags:r})}`,postUrl:(r)=>`${e.origin}/posts.json?${new URLSearchParams({limit:"1",tags:`id:${r}`})}`,pageUrl:(r)=>`${e.origin}/posts/${r}`,parse:md,count:$d}}function Md(t){return lt.find((e)=>e.key===t||e.name===t||new URL(e.origin).host===t)}function Xi(t){return t.split(/\s+/).filter((e)=>e&&!e.startsWith("rating:")).length}function Ur(t,e){let n=t.trim();if(/^\d+$/.test(n))return{site:e,id:Number(n)};let r=/^([\w.]+):(\d+)$/.exec(n);if(r){let c=lt.find((u)=>u.key===r[1]||u.name===r[1]);return c&&{site:c,id:Number(r[2])}}let i;try{i=new URL(n)}catch{return}let o=Md(i.host),s=Number(i.searchParams.get("id")??i.pathname.split("/").filter(Boolean).at(-1));return o&&s>0?{site:o,id:s}:void 0}var lt=[yd({key:"danbooru",name:"danbooru",origin:"https://danbooru.donmai.us",cutouts:["transparent_background"],vouched:!1,tunneled:!0,ansi:2}),lu({key:"konachan",name:"konachan",origin:"https://konachan.net",cutouts:["transparent","vector"],vouched:!1,tunneled:!1,ansi:6}),lu({key:"yande",name:"yande.re",origin:"https://yande.re",cutouts:["transparent_png"],vouched:!0,tunneled:!1,ansi:5})],ge=134217728;function oe(t,e){let n=lt.indexOf(t);return(n===-1?lt.length:n)*ge+e}function Vi(t){let e;try{e=new URL(t).hostname}catch{return""}return e.split(".").slice(-2).join(".")}function ku(){return lt.filter((t)=>!t.tunneled).map((t)=>Vi(t.origin)).flatMap((t)=>[t,`.${t}`]).join(",")}function Eu(t,e=Le){return t.tags.filter((n)=>e.some((r)=>od[r].has(n)))}function yu(t,e,n=["safe"]){return n.some((r)=>t.ratings[r].has(e.rating))}function xn(t){return[t,...t.smaller].find((e)=>e.width*e.height<=Te)}function Mu(t){let e=new Map;for(let[n,r]of[...t].sort(([i],[o])=>i<o?-1:1)){if(r==="")continue;e.set(r,[...e.get(r)??[],n])}return e}function Kr(){return Un(process.env.XDG_CACHE_HOME??Un(nd(),".cache"),"ttheme")}function ve(t){return Un(Kr(),t.key)}function vu(t=id,e=Kr()){let n=[],r=0;for(let i of fu(e))for(let o of ad){let s=Un(e,i,o);for(let c of fu(s)){let u=Un(s,c);try{let{size:h,mtimeMs:a}=td(u);n.push({path:u,size:h,at:a}),r+=h}catch{}}}n.sort((i,o)=>i.at-o.at);for(let i of n){if(r<=t)return;try{Dg(i.path,{force:!0}),r-=i.size}catch{}}}function vd(t,e){if(t!==null&&/^\s*\d+\s*$/.test(t))return Number(t)*1000;let n=t===null?Number.NaN:Date.parse(t);return Number.isNaN(n)?gu:Math.max(0,n-e)}function ye(t){return du.get(t.key)??0}function Sd(t){for(let e=t;e instanceof Error;e=e.cause)if(e.code==="ECONNRESET")return!0;return!1}function Id(t){return(t.headers.get("server")??"").startsWith("cloudflare")&&t.headers.get("cf-mitigated")==="challenge"}async function Me(t,e,n,r={},i=cd){for(let o=1;;o++){let s=ye(t)-Date.now();if(s>0)await rd(s,void 0,{signal:n});let c;try{c=await fetch(e,{headers:{"User-Agent":Ci,Referer:`${t.origin}/`,...r},signal:i?AbortSignal.any([n,AbortSignal.timeout(i)]):n})}catch(u){if(o<au&&!n.aborted&&Sd(u))continue;throw u}if(c.status===429&&o<au){await c.body?.cancel();let u=vd(c.headers.get("retry-after"),Date.now());if(u>gu)throw Error(`${t.name} asks to wait ${Math.ceil(u/1000)}s`);du.set(t.key,Math.max(ye(t),Date.now()+u));continue}if(!c.ok)throw await c.body?.cancel(),Error(Id(c)?`${t.name} is behind a Cloudflare challenge`:`${t.name} answered ${c.status}`);return c}}async function Su(t,e,n,r){return t.parse(await(await Me(t,t.postsUrl(e,n),r)).text())}async function Iu(t,e,n){return t.count(await(await Me(t,t.countUrl(e),n)).text())}async function Yi(t,e,n){let[r]=t.parse(await(await Me(t,t.postUrl(e),n)).text());return r}function Fd(t){let e=lt.find((r)=>r.key==="danbooru"),n=new URLSearchParams({limit:String(2*Ge),only:"md5,tag_string",tags:`md5:${t.join(",")}`});return`${e.origin}/posts.json?${n}`}function Nd(t){return new Map(Wn(t).flatMap((e)=>{let n=String(e.md5??"");return n?[[n,String(e.tag_string??"").split(/\s+/).filter(Boolean)]]:[]}))}function Fu(t,e){for(let n of t){let r=e.get(n.md5);if(r)n.tags=[...new Set([...n.tags,...r])],n.solo=r.includes("solo")}}async function Nu(t,e){let n=lt.find((i)=>i.key==="danbooru"),r=new Map;if(ye(n)>Date.now())return r;for(let i=0;i<t.length;i+=Ge){let o=await(await Me(n,Fd(t.slice(i,i+Ge)),e,{},ud)).text();for(let[s,c]of Nd(o))r.set(s,c)}return r}async function Ru(t,e){let n=lt.find((o)=>o.key==="danbooru");if(ye(n)<=Date.now())try{let o=new URLSearchParams({"search[query]":t,"search[type]":"tag_query",limit:String(hu)}),s=`${n.origin}/autocomplete.json?${o}`;return pd(await(await Me(n,s,e,{},uu)).text())}catch(o){if(e.aborted)throw o}let r=lt.find((o)=>o.key==="yande"),i=new URLSearchParams({name:t,order:"count",limit:String(hu)});return wd(await(await Me(r,`${r.origin}/tag.json?${i}`,e,{},uu)).text())}async function Ou(t,e,n){let r=await Me(t,e,n,{Range:`bytes=0-${sd}`});return Gn(new Uint8Array(await r.arrayBuffer()))}async function Hu(t,e,n,r){let i=await Me(t,e,n,{},0),o=Number(i.headers.get("content-length"))||0,s=i.body?.getReader();if(!s)return new Uint8Array(await i.arrayBuffer());let c=[],u=0;for(;;){let{done:f,value:l}=await s.read();if(f)break;c.push(l),u+=l.length,r?.(u,o)}let h=new Uint8Array(u),a=0;for(let f of c)h.set(f,a),a+=f.length;return h}var de="_groups.toml",ju=3,Lu=["background","foreground","cursor","selection"];function It(t,e){throw Error(`${t}: ${e}`)}function Ae(t,e,n){if(typeof n!=="string"||!ds(n))It(t,`${e} must be "#rrggbb" (lowercase), got ${JSON.stringify(n)}`);return n}function Se(t,e,n){if(typeof n!=="string"||n.length===0)It(t,`${e} must be a non-empty string`);return n}function Qn(t){return t&&typeof t==="object"?t:{}}function Hd(t,e,n){if(e===void 0)return[n.cursor,n.selectionBackground,n.background];let r=Array.isArray(e)?e:[e];if(r.length===0)It(t,"ghostty.icon_screen must not be empty");return r.map((i,o)=>Ae(t,`ghostty.icon_screen[${o}]`,i))}function jd(t,e,n){let r=Qn(e);return{iconGhost:r.icon_ghost===void 0?n.cursor:Ae(t,"ghostty.icon_ghost",r.icon_ghost),iconScreen:Hd(t,r.icon_screen,n)}}function Pd(t){return new Map([...Lu.map((e)=>[e,t[e]]),...t.ansi.map((e,n)=>[`ansi${n}`,e])])}function Gd(t,e,n){if(!Array.isArray(e)||e.length!==ju)It(t,`meta.signature must name exactly ${ju} palette slots`);let r=Pd(n),i=[],o=[];for(let[s,c]of e.entries()){let u=`meta.signature[${s}]`,h=Se(t,u,c),a=r.get(h);if(a===void 0)It(t,`${u} ${JSON.stringify(c)} is not a palette slot — use ${Lu.join(", ")} or ansi0-ansi15`);i.push(h),o.push(a)}if(new Set(o).size!==o.length)It(t,"meta.signature slots must resolve to three different colors");return{names:i,colors:o}}function Ld(t,e,n){if(e===void 0)return;if(!n)It(t,"meta.booru_sites renames meta.booru per site, so it needs meta.booru");if(!e||typeof e!=="object"||Array.isArray(e))It(t,'meta.booru_sites must be a table of site = "tag" or site = ["tag", ...]');let r={};for(let[i,o]of Object.entries(e)){let s=lt.find((u)=>u.key===i);if(!s)It(t,`meta.booru_sites.${i} is not a find site — use ${lt.map((u)=>u.key).join(", ")}`);let c=typeof o==="string"?[o]:Array.isArray(o)?o:void 0;if(!c||c.some((u)=>typeof u!=="string"||u===""||/\s/.test(u)))It(t,`meta.booru_sites.${i} must be one tag or a list of tags, got ${JSON.stringify(o)}`);if(c.length>1&&Number.isFinite(s.tagBudget))It(t,`meta.booru_sites.${i} takes one tag — ${s.name} searches ${s.tagBudget} tags at a time`);r[i]=c}return r}function Td(t){let n=Bun.TOML.parse(Pu(Gu(t,de),"utf8")).group;if(!Array.isArray(n)||n.length===0)It(de,"needs at least one [[group]] table");return n.map((r)=>{let i=Qn(r);return{name:Se(de,"group.name",i.name),native:i.native===void 0?void 0:Se(de,"group.native",i.native),lead:Se(de,"group.lead",i.lead)}})}function Ad(t,e,n){let r=Bun.TOML.parse(e),i=Qn(r.meta),o=Qn(r.colors),s=Qn(r.contrast),c=o.ansi;if(!Array.isArray(c)||c.length!==16)It(t,`colors.ansi must hold exactly 16 colors, got ${Array.isArray(c)?c.length:typeof c}`);let u=Se(t,"meta.name",i.name);if(u!==Od(t,".toml"))It(t,`meta.name "${u}" does not match the filename`);if(u.startsWith("-"))It(t,`meta.name "${u}" would be read as a flag by the ttheme CLI`);let h=i.role;if(h!==void 0&&h!=="default")It(t,`meta.role must be "default", got ${JSON.stringify(h)}`);let a=Se(t,"meta.group",i.group),f=n.get(a);if(!f)It(t,`meta.group "${a}" has no [[group]] table in ${de}`);let l=Ae(t,"colors.background",o.background),m=Ae(t,"colors.foreground",o.foreground),b=Ae(t,"colors.cursor",o.cursor),g=Ae(t,"colors.selection_background",o.selection_background),$=c.map((p,j)=>Ae(t,`colors.ansi[${j}]`,p)),y=Gd(t,i.signature,{background:l,foreground:m,cursor:b,selection:g,ansi:$}),F=i.booru===void 0?void 0:Se(t,"meta.booru",i.booru);if(F!==void 0&&/\s/.test(F))It(t,`meta.booru must be a single booru tag, got ${JSON.stringify(F)}`);let E=Ld(t,i.booru_sites,F),v=Array.isArray(s.waive)?s.waive.map(String):[];if(v.length>0&&typeof s.reason!=="string")It(t,"contrast.waive needs a contrast.reason explaining why");return{name:u,group:a,native:f.native,lead:f.lead===u,order:Number(i.order),role:h,ansiSource:Se(t,"meta.ansi_source",i.ansi_source),...F?{booru:F}:{},...E?{booruSites:E}:{},background:l,foreground:m,cursor:b,selectionBackground:g,ansi:$,signature:y.colors,signatureSlots:y.names,ghostty:jd(t,r.ghostty,{background:l,cursor:b,selectionBackground:g}),waive:v,waiveReason:typeof s.reason==="string"?s.reason:void 0}}function Tu(t){let e=Td(t),n=new Map(e.map((o)=>[o.name,o]));if(n.size!==e.length)It(de,"group.name must be unique");let r=Rd(t).filter((o)=>o.endsWith(".toml")&&!o.startsWith("_")).map((o)=>Ad(o,Pu(Gu(t,o),"utf8"),n)).sort((o,s)=>o.order-s.order);if(new Set(r.map((o)=>o.order)).size!==r.length)throw Error("themes: meta.order must be unique across all themes");for(let o of e){let s=r.filter((c)=>c.group===o.name);if(s.length===0)It(de,`group "${o.name}" has no themes`);if(!s.some((c)=>c.name===o.lead))It(de,`group "${o.name}" lead "${o.lead}" is not one of its themes`)}return r}function Au(t){return t.filter((e)=>e.role===void 0)}function Zn(t){let e=(n,r)=>n<r?-1:n>r?1:0;return[...t].sort((n,r)=>e(n.group.toLowerCase(),r.group.toLowerCase())||e(n.name,r.name))}var Ud=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Jr=[{name:"use",args:["<palette>"],about:"paint this tab — a unique prefix works: ttheme use ho",section:"tab",shell:!0},{name:"preview",args:[],about:"browse live — focus repaints, enter keeps (this tab or default), esc restores, ? lists keys",section:"tab",shell:!0},{name:"next",args:[],about:"advance this tab to the next palette",section:"tab",shell:!0},{name:"default",args:["<palette>"],about:"make a palette the one new tabs open with",section:"tab"},{name:"on",args:[],about:"wear the default palette in new tabs again",section:"tab"},{name:"off",args:[],about:"take the palette and picture off every tab — the terminal's own colors until `ttheme on`",section:"tab"},{name:"pin",args:[],about:"pick a palette for this directory — cd into it repaints, cd out restores",section:"tab",shell:!0},{name:"unpin",args:[],about:"drop the palette pinned to this directory",section:"tab",shell:!0},{name:"config",args:[],about:"edit settings in $EDITOR — they apply in new tabs",section:"tab",shell:!0},{name:"browse",args:[],about:"pick palettes from the catalog in a live picker",section:"catalog"},{name:"list",args:["[query]"],about:"show the catalog, marking what is installed",section:"catalog",flags:{json:{type:"boolean",about:"print the matches as JSON: name, group, installed"}}},{name:"add",args:["<palette...>"],about:"install palettes from the catalog",section:"catalog"},{name:"remove",args:["<palette...>"],about:"uninstall palettes",section:"catalog"},{name:"update",args:[],about:"refresh the catalog from the registry",section:"catalog"},{name:"init",args:[],about:"install the shell layer and wire your terminal configs",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"accept every default without prompting"}}},{name:"uninstall",args:[],about:"take ttheme out of every terminal config and delete what it wrote",section:"setup",flags:{yes:{type:"boolean",short:"y",about:"remove without asking"}}},{name:"build",args:[],about:"emit dist/ for every terminal, plus the zsh palette table — from a checkout",section:"setup",hidden:!0,flags:{only:{type:"string",multiple:!0,value:"<terminal>",choices:Ud,about:"rebuild just this terminal — repeat it for more"}}},{name:"find",args:["<palette>"],about:"pick a booru background for a palette — preview opens this on tab",section:"setup",hidden:!0},{name:"image",args:["<palette>","<action>"],about:"switch a palette between its saved backgrounds, remove the one shown, or pass on tuning — preview calls this",section:"setup",hidden:!0}];var Wr=["ghostty","kitty","alacritty","wezterm","iterm2","windows-terminal","warp"],Wu="# ttheme begin",xu="# ttheme end",qn=/# ttheme begin\n[\s\S]*?# ttheme end\n?/;function _n(t,e){let n=`${Wu}
|
|
14
14
|
${e}
|
|
15
|
-
${
|
|
15
|
+
${xu}
|
|
16
16
|
`;if(qn.test(t))return t.replace(qn,n);if(t==="")return n;return`${t.replace(/\n*$/,`
|
|
17
17
|
`)}
|
|
18
|
-
${n}`}function
|
|
19
|
-
`)}function Ue(t,e){let n=t.replace(qn,"");return new RegExp(String.raw`^[ \t]*${e}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function
|
|
20
|
-
`)}function
|
|
18
|
+
${n}`}function Cn(t){let e=t.replace(/\n?# ttheme begin\n[\s\S]*?# ttheme end(?=\n|$)/,"");if(e===t)return t;return e.trim()===""?"":e.replace(/\n*$/,`
|
|
19
|
+
`)}function Ue(t,e){let n=t.replace(qn,"");return new RegExp(String.raw`^[ \t]*${e}(?:[ \t]*=|[ \t]+\S)`,"m").test(n)}function xr(t){if(t.TERM_PROGRAM==="WarpTerminal")return"warp";if(t.GHOSTTY_RESOURCES_DIR||t.TERM_PROGRAM==="ghostty")return"ghostty";if(t.KITTY_WINDOW_ID)return"kitty";if(t.WEZTERM_PANE)return"wezterm";if(t.ALACRITTY_WINDOW_ID)return"alacritty";if(t.ITERM_SESSION_ID||t.TERM_PROGRAM==="iTerm.app")return"iterm2";if(t.TERM_PROGRAM==="Apple_Terminal")return"terminal-app";if(t.WT_SESSION&&!t.TERM_PROGRAM)return"windows-terminal";if(t.TERM?.startsWith("foot"))return"foot";return"unknown"}function Qu(t,e,n=""){let r=[];if(!Ue(n,"command")){if(r.push(`command = ${t}/launch-tab.zsh`),!Ue(n,"shell-integration"))r.push("shell-integration = zsh")}if(e)r.push(`theme = ${ct(e)}`);return r.push(`config-file = ?${t}/backgrounds/shown.conf`),r.join(`
|
|
20
|
+
`)}function Zu(t){return`source ${t}/ttheme.zsh`}var Kd="# ttheme settings — uncomment a line to change it; exported variables win over this file",Xn={TTHEME_TAB_PALETTE:{doc:"# new tabs: off keeps the configured terminal theme, seq rotates through the palettes (default off)",default:"off"},TTHEME_ANNOUNCE:{doc:'# the palette notice under "Last login:": 1 shows it, 0 silences it (default 1)',default:"1"},TTHEME_FX:{doc:"# search hint animation: typewriter, decode or glitch (default typewriter)",default:"typewriter"},TTHEME_SORT:{doc:"# series and palettes in ttheme and preview: abc sorts them by name, series keeps the order they were added (default abc)",default:"abc"},TTHEME_FIND_RATING:{doc:"# the ratings find lists, any of safe, questionable and explicit, each booru read in its own rating vocabulary (default safe)",default:"safe"},TTHEME_FIND_BLOCK:{doc:'# the posts find drops by tag: nudity, underwear, both, or none to keep them all (default "nudity underwear")',default:"nudity underwear"},TTHEME_FIND_POSTS:{doc:"# what find lists first: all is every post of the character, cutouts are the transparent ones (default all)",default:"all"},TTHEME_FIND_SOLO:{doc:"# on keeps the danbooru posts tagged solo, the character alone; off lists every post (default on)",default:"on"},TTHEME_FIND_CUTOUTS:{doc:'# the tags find calls a transparent cutout, per site as key=tag,tag pairs — e.g. "konachan=transparent,vector yande=transparent_png" (default the built-in tags)',default:""},TTHEME_FIND_ORDER:{doc:"# the order find lists posts in: fit ranks each page by how well it makes a backdrop, newest or score (default fit)",default:"fit"},TTHEME_FIND_SETS:{doc:"# runs of the same picture at the same size from one uploader: fold shows them as one tile, show lists each (default fold)",default:"fold"},TTHEME_FIND_REMOVE_BG:{doc:"# an opaque picture tried on in find: on cuts the character out with macOS Vision, off leaves it as it is (default on)",default:"on"},TTHEME_FIND_UNBLOCK:{doc:"# when a network blocks a booru by name, 1 sends find through a local proxy that splits the TLS handshake — find offers to turn it on (default 0)",default:"0"},TTHEME_FIND_HOSTS:{doc:'# send a find site somewhere else, as key=https://host pairs — e.g. "danbooru=https://safebooru.donmai.us" (default none)',default:""}};function zi(t,e){let n=`: \${${t}:=${e}}`;return Xn[t]?.default===e?`# ${n}`:n}function qu(t){return new RegExp(String.raw`^#? ?: \$\{${t}[^\n]*$`,"m")}function Jd(t,e){if(qu(e).test(t))return t;let n=Xn[e];return`${t.replace(/\n*$/,`
|
|
21
21
|
`)}
|
|
22
22
|
${n.doc}
|
|
23
|
-
${
|
|
24
|
-
`}var
|
|
25
|
-
${
|
|
23
|
+
${zi(e,n.default)}
|
|
24
|
+
`}var _u=Object.keys(Xn);function Bi(){let t=Object.entries(Xn).map(([e,n])=>`${n.doc}
|
|
25
|
+
${zi(e,n.default)}`);return`${[Kd,...t].join(`
|
|
26
26
|
|
|
27
27
|
`)}
|
|
28
|
-
`}function
|
|
28
|
+
`}function Cu(t,e,n){let r=zi(e,n),i=qu(e);if(i.test(t))return t.replace(i,r);return`${t.replace(/\n*$/,`
|
|
29
29
|
`)}
|
|
30
30
|
${r}
|
|
31
|
-
`}function
|
|
32
|
-
`)}function
|
|
33
|
-
import = ["${t}"]`:""}function
|
|
31
|
+
`}function Xu(t){if(t==="")return Bi();return Object.keys(Xn).reduce(Jd,t)}function Vu(t,e,n=""){return[...t?[`include themes/${ct(t)}.conf`]:[],`watcher ${e}`,...["window_logo_scale 100","window_logo_alpha 1"].filter((r)=>!Ue(n,r.split(" ")[0]))].join(`
|
|
32
|
+
`)}function Yu(t){let e=t.replace(qn,"");return/^[ \t]*\[colors[\].]/m.test(e)||/^[ \t]*colors[ \t]*[.=]/m.test(e)}var Wd=/^[ \t]*\[general\][ \t]*(?:#.*)?$/m,Uu=/^[ \t]*\[/m,Ku=/^[ \t]*import[ \t]*=/m,xd=/^[ \t]*general[ \t]*[.=]/m;function Qd(t){return t?`[general]
|
|
33
|
+
import = ["${t}"]`:""}function Vn(t,e){let n=t.replace(qn,""),r=Wd.exec(n);if(!r){let u=n.search(Uu),h=u<0?n:n.slice(0,u);if(xd.test(n)||Ku.test(h))return;return _n(t,Qd(e))}let i=r.index+r[0].length,o=n.slice(i),s=o.search(Uu);if(Ku.test(s<0?o:o.slice(0,s)))return;let c=e?`import = ["${e}"]
|
|
34
34
|
`:"";return`${n.slice(0,i)}
|
|
35
|
-
${
|
|
36
|
-
${c}${
|
|
35
|
+
${Wu}
|
|
36
|
+
${c}${xu}${o}`}var Ju=/-- ttheme begin\n[\s\S]*?-- ttheme end\n?/,Zd=/^return config[ \t]*$/gm;function zu(t){return`dofile(${JSON.stringify(t)})(config)`}var Bu=`local wezterm = require 'wezterm'
|
|
37
37
|
local config = wezterm.config_builder()
|
|
38
38
|
|
|
39
|
-
`;function
|
|
40
|
-
`?"":e}function
|
|
39
|
+
`;function Du(t){let e=t.replace(/-- ttheme begin\n[\s\S]*?-- ttheme end\n\n?/,"");return e===`${Bu}return config
|
|
40
|
+
`?"":e}function Yn(t,e){let n=`-- ttheme begin
|
|
41
41
|
${e}
|
|
42
42
|
-- ttheme end
|
|
43
|
-
`;if(
|
|
43
|
+
`;if(Ju.test(t))return t.replace(Ju,n);if(t==="")return`${Bu}${n}
|
|
44
44
|
return config
|
|
45
|
-
`;let r=[...t.matchAll(
|
|
46
|
-
${t.slice(r.index)}`}var
|
|
47
|
-
`),n=
|
|
48
|
-
`),r=
|
|
45
|
+
`;let r=[...t.matchAll(Zd)].at(-1);if(r?.index===void 0)return;return`${t.slice(0,r.index)}${n}
|
|
46
|
+
${t.slice(r.index)}`}var th="[appearance.themes]";function eh(t){let e=t.findIndex((r)=>r.trim()===th);if(e<0)return;let n=t.findIndex((r,i)=>i>e&&r.trimStart().startsWith("["));return[e,n<0?t.length:n]}function Qr(t){let e=t.split(`
|
|
47
|
+
`),n=eh(e);if(!n)return;return e.slice(n[0]+1,n[1]).find((i)=>/^theme\s*=/.test(i))?.replace(/^theme\s*=\s*/,"").trim()}function nh(t){return`{ custom = { name = "${t}", path = "${ct(t)}.yaml" } }`}function Zr(t,e){let n=t.split(`
|
|
48
|
+
`),r=eh(n);if(!r)return e===void 0?t:`${t.replace(/\n*$/,`
|
|
49
49
|
`)}
|
|
50
|
-
${
|
|
50
|
+
${th}
|
|
51
51
|
theme = ${e}
|
|
52
52
|
`;let i=n.findIndex((o,s)=>s>r[0]&&s<r[1]&&/^theme\s*=/.test(o));if(i>=0)n.splice(i,1,...e===void 0?[]:[`theme = ${e}`]);else if(e!==void 0)n.splice(r[0]+1,0,`theme = ${e}`);return n.join(`
|
|
53
|
-
`)}function
|
|
54
|
-
`)}var
|
|
55
|
-
`);return[{path:`warp/themes/${ct(t.name)}.yaml`,content:e}]}};var
|
|
56
|
-
`);return[{path:`wezterm/colors/${ct(t.name)}.toml`,content:e}]}},
|
|
57
|
-
`)}var
|
|
58
|
-
`}var
|
|
59
|
-
`}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:
|
|
60
|
-
${n.length} themes (${
|
|
53
|
+
`)}function Di(t,e,n=[]){for(let a of t)for(let f of[a.name,a.group,a.native??"",a.ansiSource])if(/["$`\\]/.test(f))throw Error(`${a.name}: "${f}" contains a character that breaks zsh quoting`);let r=Math.max(0,...t.map((a)=>a.name.length)),i=(a,f)=>` ${a.name.padEnd(r)} "${f}"`,o=(a)=>a.map((f)=>f.name).join(" "),s=Pe(t),c=(a)=>`'${a.replaceAll("'","'\\''")}'`,u=Jr.filter((a)=>a.section!=="setup"&&!a.hidden),h=u.flatMap((a,f)=>f>0&&u[f-1]?.section!==a.section?["-",a.name]:[a.name]);return["# Generated by `mise run build` — do not edit.","# Source of truth: themes/*.toml in the ttheme repo.","",`typeset -g TTHEME_VERSION=${re.version}`,"",'# the palette new tabs open with, which the iTerm2 "ttheme · default" profile wears',`typeset -g TTHEME_STARTUP=${e??""}`,"","# the terminals ttheme is wired into: a picture change reaches every one of them, from whichever runs the shell",`typeset -ga TTHEME_TERMINALS=(${n.join(" ")})`,"","# the commands the shell layer knows (src/verbs.ts): help, completion and argument checks read them",`typeset -ga TTHEME_VERBS=(${h.join(" ")})`,`typeset -ga TTHEME_SHELL_VERBS=(${u.filter((a)=>a.shell).map((a)=>a.name).join(" ")})`,"typeset -gA TTHEME_VERB_ARGS=(",...u.map((a)=>` ${a.name} ${c(a.args.join(" "))}`),")","typeset -gA TTHEME_VERB_ABOUT=(",...u.map((a)=>` ${a.name} ${c(a.about)}`),")","","# the settings config.zsh holds, handed to the CLI on every call",`typeset -ga TTHEME_SETTINGS=(${_u.join(" ")})`,"","# seed for `ttheme config` when no config.zsh exists yet",`typeset -g TTHEME_CONFIG_TEMPLATE='${Bi().trimEnd().replaceAll("'","'\\''")}'`,"","typeset -gA TTHEME_PALETTE=(",...t.map((a)=>i(a,[a.background,a.foreground,a.cursor,a.selection,...a.ansi].join(" "))),")","","# series order: new tabs cycle through it and TTHEME_SORT=series lists it — the default role stays applyable but unlisted",`typeset -ga TTHEME_ORDER=(${o(s)})`,"","# the same palettes by series name, then palette name: TTHEME_SORT=abc lists them this way",`typeset -ga TTHEME_ABC=(${o(Zn(s))})`,"","typeset -gA TTHEME_GROUP=(",...t.map((a)=>i(a,a.group)),")","","# original-language title, rendered dim next to the group","typeset -gA TTHEME_NATIVE=(",...t.filter((a)=>a.native).map((a)=>i(a,a.native??"")),")","","# where each palette's 16 ANSI colors came from","typeset -gA TTHEME_SRC=(",...t.map((a)=>i(a,a.ansiSource)),")",""].join(`
|
|
54
|
+
`)}var to={id:"shell",emitShared(t){return[{path:"shell/palettes.zsh",content:Di(t.map(Zi))}]}};var qd=["black","red","green","yellow","blue","magenta","cyan","white"];function rh(t,e){return[` ${t}:`,...qd.map((n,r)=>` ${n}: "${e[r]}"`)]}var zn={id:"warp",limits:"no selection color, and Warp paints one theme app-wide",emit(t){let e=[`name: "${t.name}"`,`background: "${t.background}"`,`foreground: "${t.foreground}"`,`accent: "${t.cursor}"`,`cursor: "${t.cursor}"`,`details: ${zt(t.background)<0.18?"darker":"lighter"}`,"terminal_colors:",...rh("normal",t.ansi.slice(0,8)),...rh("bright",t.ansi.slice(8,16)),""].join(`
|
|
55
|
+
`);return[{path:`warp/themes/${ct(t.name)}.yaml`,content:e}]}};var ih=(t)=>`[${t.map((e)=>`"${e}"`).join(", ")}]`,Bn={id:"wezterm",limits:"OSC repaints per pane, pictures show per window",emit(t){let e=["[metadata]",`name = "${ct(t.name)}"`,`origin_url = "${t.ansiSource}"`,"","[colors]",`foreground = "${t.foreground}"`,`background = "${t.background}"`,`cursor_bg = "${t.cursor}"`,`cursor_border = "${t.cursor}"`,`cursor_fg = "${t.background}"`,`selection_bg = "${t.selectionBackground}"`,`selection_fg = "${t.foreground}"`,"",`ansi = ${ih(t.ansi.slice(0,8))}`,`brights = ${ih(t.ansi.slice(8,16))}`,""].join(`
|
|
56
|
+
`);return[{path:`wezterm/colors/${ct(t.name)}.toml`,content:e}]}},De=(t)=>JSON.stringify(t);function oh(t){return["-- Generated by ttheme — rewritten on every add, remove and default; do not edit.","local wezterm = require 'wezterm'","",`local MODULE = ${De(t.path)}`,`local COLORS = ${De(t.colors)}`,`local BACKGROUNDS = ${De(t.backgrounds)}`,`local STARTUP = ${t.startup?De(ct(t.startup)):"nil"}`,"local PALETTES = {",...t.palettes.map((e)=>` [${De(e.name)}] = ${De(e.background)},`),"}","","local X = { left = 'Left', center = 'Center', right = 'Right' }","local Y = { top = 'Top', center = 'Middle', bottom = 'Bottom' }","local SIZE = { cover = 'Cover', contain = 'Contain', stretch = '100%' }","","local function locate(path)"," if path:sub(1, 2) == '~/' then"," return os.getenv('HOME') .. path:sub(2)"," elseif path:sub(1, 1) == '/' or path:match('^%a:[/\\\\]') then"," return path"," end"," return BACKGROUNDS .. '/' .. path","end","","local function read(path, into)"," local f = io.open(path, 'r')"," if not f then"," return false"," end"," for line in f:lines() do"," local key, value = line:match('^%s*([%w%-]+)%s*=%s*(.-)%s*$')"," if key == 'config-file' then"," read(locate((value:gsub('^%?', ''))), into)"," elseif key then"," into[key] = value"," end"," end"," f:close()"," return true","end","","local function layers(palette)"," local color = PALETTES[palette]"," local c = {}"," if not color or not read(BACKGROUNDS .. '/' .. palette .. '.conf', c) then"," return nil, 'none'"," end"," local image = c['background-image'] or ''"," local opacity = tonumber(c['background-image-opacity'] or '1') or 1"," if image == '' or opacity <= 0 then"," return nil, 'none'"," end"," local fit = c['background-image-fit'] or 'contain'"," local position = c['background-image-position'] or 'center'"," local y, x = position:match('^(%a+)-(%a+)$')"," local rep = c['background-image-repeat'] == 'true' and 'Repeat' or 'NoRepeat'"," return {"," { source = { Color = color }, width = '100%', height = '100%' },"," {"," source = { File = locate(image) },"," opacity = opacity,"," width = SIZE[fit],"," height = SIZE[fit],"," horizontal_align = X[x or 'center'],"," vertical_align = Y[y or 'center'],"," repeat_x = rep,"," repeat_y = rep,"," },"," }, table.concat({ color, image, opacity, fit, position, rep }, '|')","end","","local shown = {}","","local function show(window, pane)"," local want = pane:get_user_vars().ttheme_shown"," if not want or want == '' then"," return"," end"," local background, key = layers(want)"," local id = window:window_id()"," if shown[id] == key then"," return"," end"," shown[id] = key"," local overrides = window:get_config_overrides() or {}"," overrides.background = background"," window:set_config_overrides(overrides)","end","","wezterm.on('user-var-changed', function(window, pane, name)"," if name == 'ttheme_shown' then"," show(window, pane)"," end","end)","wezterm.on('update-status', show)","","return function(config)"," local dirs = config.color_scheme_dirs or {}"," table.insert(dirs, COLORS)"," config.color_scheme_dirs = dirs"," if STARTUP then"," config.color_scheme = STARTUP"," end"," wezterm.add_to_config_reload_watch_list(MODULE)","end",""].join(`
|
|
57
|
+
`)}var sh=["black","red","green","yellow","blue","purple","cyan","white"];function ch(t){return{name:ct(t.name),background:t.background,foreground:t.foreground,cursorColor:t.cursor,selectionBackground:t.selectionBackground,...Object.fromEntries(sh.map((e,n)=>[e,t.ansi[n]])),...Object.fromEntries(sh.map((e,n)=>[`bright${e[0]?.toUpperCase()}${e.slice(1)}`,t.ansi[n+8]]))}}function eo(t,e,n){let r={...e&&n?{profiles:[{updates:e,colorScheme:ct(n)}]}:{},schemes:t.map(ch)};return`${JSON.stringify(r,null,2)}
|
|
58
|
+
`}var Dn={id:"windows-terminal",limits:"no kitty graphics, so no pictures; OSC repaints per pane",emit(t){return[{path:`windows-terminal/schemes/${ct(t.name)}.json`,content:`${JSON.stringify(ch(t),null,2)}
|
|
59
|
+
`}]},emitShared(t){return[{path:"windows-terminal/ttheme.json",content:eo(t)}]}};function ct(t){return`ttheme-${t}`}function Ce(t){return[`# ${t.name} — ${t.group}${t.native?` (${t.native})`:""}`,`# ANSI: ${t.ansiSource}`]}var hh=tr(import.meta.dirname,".."),Cd=tr(hh,"themes"),no=tr(hh,"dist"),qr=[Rn,Hn,Nn,Bn,On,Dn,zn],Xd=[to,qi],E$=qr.map((t)=>t.id);async function _r({only:t}={}){if(typeof Bun>"u")throw Error("needs bun — run it from a checkout: bun src/bin.ts build");let e=t&&t.length>0?qr.filter((o)=>t.includes(o.id)):qr,n=Tu(Cd),r=Hs(n);if(r.length>0){for(let o of r)console.error(` ✗ ${o.theme} [${o.rule}] ${o.detail}`);throw Error(`${r.length} contrast violation(s). Fix the palette, or waive the rule in its [contrast] section with a reason.`)}if(e.length===qr.length)uh(no,{recursive:!0,force:!0});else for(let o of e)uh(tr(no,o.id),{recursive:!0,force:!0});let i=0;for(let o of[...e,...Xd]){let s=n.flatMap((h)=>o.emit?.(h)??[]),c=o.emitShared?.(n)??[];for(let h of[...s,...c])await Bun.write(tr(no,h.path),h.content),i++;let u=s.length>0?`${n.length} themes${o.limits?` (${o.limits})`:""}`:c.map((h)=>_d(h.path)).join(" ");console.log(` ${o.id.padEnd(16)} ${u}`)}console.log(`
|
|
60
|
+
${n.length} themes (${Au(n).length} in the new-tab rotation) -> ${i} files in dist/`)}import{spawn as Oa}from"node:child_process";import{createHash as Ha}from"node:crypto";import{existsSync as un,mkdirSync as gr,mkdtempSync as Hp,readFileSync as ja,rmSync as Io,statSync as jp,writeFileSync as dr}from"node:fs";import{tmpdir as Pp}from"node:os";import{dirname as ui,join as he}from"node:path";import{pathToFileURL as Gp}from"node:url";import{execFile as Vd}from"node:child_process";import{createHash as gh}from"node:crypto";import{existsSync as Yd,mkdtempSync as zd,readFileSync as Yr,rmSync as Bd,statSync as dh,writeFileSync as mh}from"node:fs";import{homedir as Dd,tmpdir as tm}from"node:os";import{join as Cr}from"node:path";import{fileURLToPath as em}from"node:url";import{promisify as nm}from"node:util";var se=nm(Vd),Xr=67108864,rm=4096,oo=["image/png","image/jpeg","image/webp","image/gif","image/tiff","image/heic"],im=["text/uri-list","text/plain;charset=utf-8","text/plain"],ro=[...oo,"text/uri-list","text/plain"];function om(t){try{return dh(t).isFile()}catch{return!1}}function sm(t){let e=[],n="",r="",i=!1;for(let o=0;o<t.length;o++){let s=t[o];if(r==="'")if(s==="'")r="";else n+=s;else if(r==='"')if(s==='"')r="";else if(s==="\\"&&'"\\$`'.includes(t[o+1]??""))n+=t[++o];else n+=s;else if(s==="\\"&&o+1<t.length)n+=t[++o],i=!0;else if(s==="'"||s==='"')r=s,i=!0;else if(/\s/.test(s)){if(i)e.push(n);n="",i=!1}else n+=s,i=!0}if(i)e.push(n);return e}function ah(t){if(/^file:\/\//i.test(t))try{return em(t)}catch{return}if(t.startsWith("~/"))return Cr(Dd(),t.slice(2));return t.startsWith("/")?t:void 0}function zr(t,e=om){let n=[];for(let r of t.replace(/\r\n?/g,`
|
|
61
61
|
`).split(`
|
|
62
|
-
`)){let i=
|
|
62
|
+
`)){let i=ah(r.trim());if(i&&e(i)){n.push(i);continue}for(let o of sm(r)){if(/^https?:\/\/\S+$/i.test(o)){n.push(o);continue}let s=ah(o);if(s&&e(s))n.push(s)}}return n}function cm(t){if(t[0]!==255||t[1]!==216)return null;let e=2;while(e+9<t.length){if(t[e]!==255){e++;continue}let n=t[e+1];if(n===255){e++;continue}let r=t[e+2]<<8|t[e+3];if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204)return{height:t[e+5]<<8|t[e+6],width:t[e+7]<<8|t[e+8]};e+=2+r}return null}function fh(t){let e=Pn(t)?Gn(t):cm(t);if(!e)return;return{ext:Pn(t)?"png":"jpg",width:e.width,height:e.height}}async function Vr(t,e){let n=fh(t);if(n&&n.width*n.height<=Te)return{bytes:t,...n,source:e};if(process.platform!=="darwin")throw Error(n?`${n.width}×${n.height} is over ${Te/1e6} megapixels`:"only PNG and JPEG pictures work here");let r=zd(Cr(tm(),"ttheme-attach-"));try{let i=Cr(r,"in"),o=Cr(r,"out.png");mh(i,t);let s=!n||n.width*n.height>Te?["--resampleHeightWidthMax",String(rm)]:[];await se("sips",["-s","format","png",...s,i,"--out",o]).catch(()=>{throw Error("that is not a picture macOS can read")});let c=new Uint8Array(Yr(o)),u=fh(c);if(!u)throw Error("that is not a picture macOS can read");return{bytes:c,...u,source:e}}finally{Bd(r,{recursive:!0,force:!0})}}async function so(t,e){if(/^https?:\/\//i.test(t)){let n=await fetch(t,{headers:{"User-Agent":Ci},signal:e});if(!n.ok)throw Error(`${new URL(t).host} answered ${n.status}`);if(Number(n.headers.get("content-length")??0)>Xr)throw Error("that picture is over 64 MB");let r=new Uint8Array(await n.arrayBuffer());if(/^text\/html/i.test(n.headers.get("content-type")??""))throw Error(`${new URL(t).host} sent a web page, not a picture — copy the image address instead`);return Vr(r,t)}if(dh(t).size>Xr)throw Error("that picture is over 64 MB");return Vr(new Uint8Array(Yr(t)),t)}var ph=new Map,Br={key:"local",name:"local",origin:"file://",moved:!1,cutouts:"",best:"",tagBudget:0,vouched:!0,tunneled:!1,ansi:7,ratings:{safe:new Set,questionable:new Set,explicit:new Set},rate:()=>"",postsUrl:()=>"",countUrl:()=>"",postUrl:()=>"",pageUrl:(t)=>ph.get(t)??"",parse:()=>[],count:()=>0};function wh(t){if(/^https?:\/\//i.test(t))return"";return t.split("/").pop()??t}function bh(t,e){ph.set(t,e)}function $h(t){return Number.parseInt(gh("sha1").update(t).digest("hex").slice(0,8),16)%ge}var um=`ObjC.import('AppKit')
|
|
63
63
|
function run(argv) {
|
|
64
64
|
const pb = $.NSPasteboard.generalPasteboard
|
|
65
65
|
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
@@ -84,16 +84,16 @@ function run(argv) {
|
|
|
84
84
|
if (web && web.count > 0) return web.objectAtIndex(0).absoluteString.js
|
|
85
85
|
const text = pb.stringForType('public.utf8-plain-text')
|
|
86
86
|
return text && !text.isNil() ? text.js : ''
|
|
87
|
-
}`,
|
|
87
|
+
}`,hm=`Add-Type -AssemblyName System.Windows.Forms,System.Drawing
|
|
88
88
|
$c = [Windows.Forms.Clipboard]
|
|
89
89
|
$f = $c::GetFileDropList(); if ($f.Count) { $f; exit }
|
|
90
90
|
$p = Join-Path $env:TEMP 'ttheme-clipboard.png'
|
|
91
91
|
$s = $c::GetData('PNG'); if ($s -is [IO.MemoryStream]) { [IO.File]::WriteAllBytes($p, $s.ToArray()); $p; exit }
|
|
92
92
|
$i = $c::GetImage(); if ($i) { $i.Save($p, [Drawing.Imaging.ImageFormat]::Png); $p; exit }
|
|
93
|
-
$c::GetText()`;function
|
|
94
|
-
`).map((s)=>s.trim()),i=(s)=>e?se("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:
|
|
93
|
+
$c::GetText()`;function kh(){if(process.platform!=="linux")return!1;try{return/microsoft/i.test(Yr("/proc/version","utf8"))}catch{return!1}}async function am(t){let e=Boolean(process.env.WAYLAND_DISPLAY),n=e?["wl-paste",["--list-types"]]:["xclip",["-selection","clipboard","-t","TARGETS","-o"]],r=(await se(n[0],n[1])).stdout.split(`
|
|
94
|
+
`).map((s)=>s.trim()),i=(s)=>e?se("wl-paste",["--no-newline","--type",s],{encoding:"buffer",maxBuffer:Xr}):se("xclip",["-selection","clipboard","-t",s,"-o"],{encoding:"buffer",maxBuffer:Xr});if(r.includes("text/uri-list"))return{text:(await i("text/uri-list")).stdout.toString("utf8")};let o=oo.find((s)=>r.includes(s));if(o)return mh(t,(await i(o)).stdout),{image:t};return{text:r.some((s)=>s.startsWith("text/plain")||s==="UTF8_STRING")?(await i(r.includes("text/plain")?"text/plain":"UTF8_STRING")).stdout.toString("utf8"):""}}function co(){return Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY)}async function Eh(t){if(process.platform==="darwin"){let e=(await se("osascript",["-l","JavaScript","-e",um,t])).stdout.trim();return e===t?{image:t}:{text:e}}if(kh()){let e=(await se("powershell.exe",["-NoProfile","-STA","-Command",hm])).stdout.replace(/\r/g,"").trim(),n=await Promise.all(e.split(`
|
|
95
95
|
`).map(async(r)=>/^[A-Za-z]:\\/.test(r)?(await se("wslpath",["-u",r])).stdout.trim():r));return n.length===1&&/ttheme-clipboard\.png$/.test(n[0]??"")?{image:n[0]}:{text:n.join(`
|
|
96
|
-
`)}}if(process.platform==="linux")return
|
|
96
|
+
`)}}if(process.platform==="linux")return am(t);throw Error(`reading the clipboard is not supported on ${process.platform}`)}var fm=`ObjC.import('AppKit')
|
|
97
97
|
function run() {
|
|
98
98
|
const pb = $.NSPasteboard.generalPasteboard
|
|
99
99
|
const files = pb.readObjectsForClassesOptions($([$.NSURL]), $({ NSPasteboardURLReadingFileURLsOnlyKey: true }))
|
|
@@ -105,8 +105,8 @@ function run() {
|
|
|
105
105
|
picture = ['public.png', 'public.tiff', 'public.jpeg', 'public.heic'].some((t) => types.includes(t))
|
|
106
106
|
}
|
|
107
107
|
return pb.changeCount + '\\t' + (picture ? 'picture' : '')
|
|
108
|
-
}`;async function
|
|
109
|
-
`)}function
|
|
108
|
+
}`;async function yh(){if(co())return;if(process.platform==="darwin"){let[t="",e=""]=(await se("osascript",["-l","JavaScript","-e",fm])).stdout.trim().split("\t");return{stamp:t,picture:e==="picture"}}if(process.platform==="linux"&&!kh()){let e=Boolean(process.env.WAYLAND_DISPLAY)?(await se("wl-paste",["--list-types"])).stdout:(await se("xclip",["-selection","clipboard","-t","TARGETS","-o"])).stdout;return{stamp:e,picture:/^image\//m.test(e)}}return}function Mh(t){let e=[],n="",r=0;while(r<t.length){if(t[r]!=="\x1B"){n+=t[r],r++;continue}if(t.startsWith("\x1B[200~",r)){let o=t.indexOf("\x1B[201~",r+6);if(o===-1)return{events:e,keys:n,pending:t.slice(r)};e.push({kind:"paste",text:t.slice(r+6,o)}),r=o+6;continue}if(t.startsWith("\x1B]5522;",r)||t.startsWith("\x1B]72;",r)){let o=[t.indexOf("\x1B\\",r),t.indexOf("\x07",r)].filter((f)=>f!==-1);if(o.length===0)return{events:e,keys:n,pending:t.slice(r)};let s=Math.min(...o),c=t.slice(r+2,s),[u="",h="",...a]=c.split(";");e.push({kind:"osc",code:u,meta:lm(h),payload:a.join(";")}),r=s+(t[s]==="\x07"?1:2);continue}let i=/^\[\?([\d;]*)(\$y|c)/.exec(t.slice(r+1,r+64));if(i){if(i[2]==="c")e.push({kind:"attributes"});else{let[o="0",s="0"]=(i[1]??"").split(";");e.push({kind:"mode",mode:Number(o),value:Number(s)})}r+=1+i[0].length;continue}if(/^(?:\[(?:\?[\d;$]*|2|20|200|201)?|\](?:5|55|552|5522|7|72)?)$/.test(t.slice(r+1)))return{events:e,keys:n,pending:t.slice(r)};n+=t[r],r++}return{events:e,keys:n,pending:""}}function lm(t){let e={};for(let n of t.split(":")){let r=n.indexOf("=");if(r>0)e[n.slice(0,r)]=n.slice(r+1)}return e}var er=(t)=>Buffer.from(t).toString("base64"),io=(t)=>Buffer.from(t,"base64");function lh(t,e){return e.find((n)=>t.includes(n))}class uo{clipboard=!1;drops=!1;reading;offered=[];dropping;pw=er(gh("sha1").update(`${process.pid}:${Date.now()}`).digest("hex"));send;deliver;constructor(t,e){this.send=t,this.deliver=e}start(){let t="\x1B[?2004h";if(this.clipboard)t+="\x1B[?5522h";if(this.drops)t+=`\x1B]72;t=a;${ro.join(" ")}\x1B\\`;this.send(t)}stop(){this.send(`\x1B[?2004l${this.clipboard?"\x1B[?5522l":""}${this.drops?"\x1B]72;t=A\x1B\\":""}`)}ask(){this.reading={mime:".",chunks:[],pw:"",listing:!0},this.send(`\x1B]5522;type=read:name=${er("ttheme")}:pw=${this.pw};${er(".")}\x1B\\`)}take(t){if(t.code==="5522")this.clip(t.meta,t.payload);else if(t.code==="72")this.drop(t.meta,t.payload)}clip(t,e){if(t.type!=="read")return;let n=t.status??"";if(n==="OK"){if(this.reading??={mime:".",chunks:[],pw:t.pw??"",listing:!0},t.pw)this.reading.pw=t.pw;return}let r=this.reading;if(!r)return;if(n==="DATA"){if(r.mime=t.mime?io(t.mime).toString("utf8"):r.mime,e)r.chunks.push(io(e));return}if(this.reading=void 0,n!=="DONE"){this.deliver({kind:"error",message:n==="EPERM"?"the clipboard read was not allowed":`the terminal answered ${n}`});return}let i=Buffer.concat(r.chunks);if(r.listing){let o=i.toString("utf8").split(/\s+/).filter(Boolean),s=lh(o,[...oo,...im]);if(!s){this.deliver({kind:"text",text:""});return}let c=r.pw||this.pw,u=r.pw?"Paste event":"ttheme";this.reading={mime:s,chunks:[],pw:c,listing:!1},this.send(`\x1B]5522;type=read:name=${er(u)}:pw=${c};${er(s)}\x1B\\`);return}this.deliver(r.mime.startsWith("image/")?{kind:"bytes",bytes:new Uint8Array(i),source:"clipboard"}:{kind:"text",text:i.toString("utf8")})}drop(t,e){let n=t.t??"";if(n==="m"){if(t.x==="-1"){this.offered=[];return}if(e){this.offered=e.split(" ").filter(Boolean);let c=ro.filter((u)=>this.offered.includes(u));this.send(`\x1B]72;t=m:o=${c.length>0?1:0};${c.join(" ")}\x1B\\`)}return}if(n==="M"){let c=e?e.split(" ").filter(Boolean):this.offered,u=lh(c,ro);if(!u){this.send("\x1B]72;t=r:o=0\x1B\\");return}this.dropping={mimes:c,index:c.indexOf(u)+1,chunks:[]},this.send(`\x1B]72;t=r:x=${this.dropping.index}\x1B\\`);return}let r=this.dropping;if(!r)return;if(n==="R"){this.dropping=void 0,this.send("\x1B]72;t=r:o=0\x1B\\"),this.deliver({kind:"error",message:`the drop failed: ${e.split(":")[0]||"unknown error"}`});return}if(n!=="r"&&n!=="")return;if(e)r.chunks.push(io(e));if(t.m==="1"||e)return;this.dropping=void 0;let i=Buffer.concat(r.chunks),o=r.mimes[r.index-1]??"",s;if(o.startsWith("image/"))s={kind:"bytes",bytes:new Uint8Array(i),source:"drop"};else{let c=i.toString("utf8"),u=o==="text/uri-list"?zr(c).find((h)=>Yd(h)):void 0;s=u?{kind:"bytes",bytes:new Uint8Array(Yr(u)),source:u}:{kind:"text",text:c}}this.send("\x1B]72;t=r:o=1\x1B\\"),this.deliver(s)}}import{existsSync as gm,mkdirSync as dm,readFileSync as mm,writeFileSync as pm}from"node:fs";import{dirname as wm,join as bm}from"node:path";var vh="https://kecan0406.github.io/ttheme/manifest.json",$m=20000;function Dr(t){return bm(t,"ttheme","catalog.json")}function ti(t,e){let n=Dr(t);dm(wm(n),{recursive:!0}),pm(n,`${JSON.stringify(e,null,2)}
|
|
109
|
+
`)}function At(t){let e=Dr(t);if(!gm(e))throw Error(`no catalog at ${e} — run \`ttheme init\` first`);return Sh(mm(e,"utf8"))}function Sh(t){let e;try{e=JSON.parse(t)}catch{throw Error("catalog is not valid JSON")}let n=e;if(typeof n?.version!=="string"||!Array.isArray(n.palettes))throw Error("catalog has no version or palettes");for(let r of n.palettes)if(typeof r?.name!=="string"||!Array.isArray(r.ansi)||r.ansi.length!==16)throw Error(`catalog entry ${JSON.stringify(r?.name)} is missing name or its 16 ANSI colors`);return n}async function Ih(t){let e;try{e=await fetch(t,{signal:AbortSignal.timeout($m)})}catch(n){throw Error(`cannot reach the registry at ${t} — ${n instanceof Error?n.message:String(n)}`)}if(!e.ok)throw Error(`registry at ${t} answered ${e.status}`);return Sh(await e.text())}function Fh(t){let e=new Set(t.waived??[]);return Nr.flatMap((n,r)=>{let i=t.gate?.[r];if(e.has(n.rule)||typeof i!=="number")return[];if(n.min!==void 0&&i<n.min)return[`${n.label} ${i} < ${n.min}`];if(n.max!==void 0&&i>n.max)return[`${n.label} ${i} > ${n.max}`];return[]})}function ei(t,e){let n=t.find((r)=>r.name===e);if(!n)throw Error(`no palette named ${e} in the catalog — ${ho(t,[e])}`);return n}function ho(t,e){let n=e.map((s)=>s.toLowerCase()),r=t.filter((s)=>n.some((c)=>s.name.includes(c))),i=t.filter((s)=>!r.includes(s)&&n.some((c)=>s.group.toLowerCase().includes(c))),o=[...r,...i].map((s)=>s.name).slice(0,3);return o.length>0?`did you mean: ${o.join(", ")}?`:"`ttheme list` shows what is there"}function Nh(t,e){let n=e.toLowerCase();return t.filter((r)=>[r.name,r.group,r.native??"",r.ansiSource].some((i)=>i.toLowerCase().includes(n)))}function Rh(t,e,n){let r=n.toLowerCase(),i=(o)=>o.name===e.name?0:o.group===e.group?1:2;return t.filter((o)=>o.booru?.toLowerCase().includes(r)).map((o,s)=>({p:o,at:s})).sort((o,s)=>i(o.p)-i(s.p)||o.at-s.at).map(({p:o})=>o)}function Oh(t,e){return t.booruSites?.[e]??(t.booru?[t.booru]:[])}import{spawn as km}from"node:child_process";var Em=30000,ym=3,Mm=97,vm=`ObjC.import('Vision')
|
|
110
110
|
ObjC.import('CoreImage')
|
|
111
111
|
ObjC.import('CoreGraphics')
|
|
112
112
|
function run(argv) {
|
|
@@ -125,99 +125,99 @@ function run(argv) {
|
|
|
125
125
|
$.CIImage.imageWithCVPixelBuffer(buffer), $.NSURL.fileURLWithPath(argv[1]), $.kCIFormatRGBA8,
|
|
126
126
|
$.CGColorSpaceCreateWithName($.kCGColorSpaceSRGB), $({}), error)
|
|
127
127
|
if (!written) throw new Error('write failed')
|
|
128
|
-
}`;function
|
|
129
|
-
`).at(-1)||`osascript exited ${c}`))})})}var
|
|
130
|
-
`?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return e}var Eh="\x1B]1337;ReportCellSize\x07\x1B[16t",bh="\x1B]1337;ReportCellSize=";function uo(t){let e=t.indexOf(bh);if(e!==-1){let i=t.slice(e+bh.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,e)+i.slice(s+(i[s]==="\x07"?1:2))}}}let n=t.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,n)+t.slice(n+1+r[0].length)}}function De(t,e){return{perRow:Math.max(1,Math.floor((t+1)/At.pitch)),rowsVis:Math.max(1,Math.floor((e-4)/At.height))}}function yh(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function vh(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function Mh(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Sh(t){return`\x1B[38;2;${Gt(t).join(";")}m`}function so(t){return`\x1B[48;2;${Gt(t).join(";")}m`}function Ct(t){return Array.from(t).length}class ei{parts=[];cols;constructor(t){this.cols=t}put(t,e,n=""){return this.parts.push({col:t,text:e,sgr:n}),t+Ct(e)}run(t,e){let n=t;for(let[r,i]of e)n=this.put(n,r,i);return n}right(t,e){this.run(t-e.reduce((n,[r])=>n+Ct(r),0),e)}render(){let t="";for(let{col:e,text:n,sgr:r}of this.parts){if(e>=this.cols||e<0)continue;let i=Array.from(n).slice(0,this.cols-e).join("");t+=`\x1B[${e+1}G${r}${i}${r?hm:""}`}return t}}function Ih(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function lm(t,e){if(!e)return Ih(t);return e>=1e6?`${(t/1e6).toFixed(1)}/${(e/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(e/1000)} KB`}function Fh(t){return t.replace(/_\([^)]*\)?$/,"")}function Nh(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<um?Qt:ut]}function nr(t,e,n,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let a=[...o?[Ct(o[0])]:[],...i.map(([l,m])=>Ct(l)+1+Ct(m))];return(r.badge?Ct(r.badge)+4:0)+a.reduce((l,m)=>l+m,0)+3*Math.max(0,a.length-1)+(s?3+Ct(s[0])+1+Ct(s[1]):0)};while(c()>e)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>e){let a=Math.max(0,Ct(o[0])-(c()-e)-1);o=[`${Array.from(o[0]).slice(0,a).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...o?[[o]]:[],...i.map(([a,f])=>[[a,ue],[` ${f}`,ut]])].forEach((a,f)=>{u=t.run(u+(f?3:0),a)}),s)t.right(e,[[s[0],ue],[` ${s[1]}`,ut]])}function gm(t,e,n,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let a=n;for(let b=0;b<8;b++)a=(t[e]?.put(a,"▀".repeat(h),Sh(s[b]??u)+so(s[b+8]??u))??a)+1;let f=["❯ ",ce],l=[[["~/code/demo",ti],[" on ",ut],["main",am],[" +2",ce],[" ~1",Qt]]];if(l.push([f,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",ce],["...",""],["origin/main",er],[" [ahead 1]",Qt]]);if(l.push([[" M",er],[" src/main.rs",""]]),l.push([["??",er],[" notes.md",""]]),l.push([]),r>=44)l.push([f,["ls",""]]),l.push([["docs",ti],[" ",""],["src",ti],[" ",""],["tests",ti],[" Cargo.toml README.md",""]]),l.push([]);l.push([f,["cargo test",""]]),l.push([[" ✓",ce],[" parses config",""]]);let m=[[" ✗",er],[" renders frame",""]];if(r>=44)m.push([" expected ",ut],["3",ce],[", received ",ut],["2",er]);l.push(m),l.push([]),l.push([f,["echo ",""],["selected text",so(c)],[" ",""],[" ",so(u)]]),l.forEach((b,g)=>{let $=e+2+g;if($<=i)t[$]?.run(n,b)})}function dm(t,e,n,r,i,o){t[e]?.put(n,`╭${"─".repeat(i-2)}╮`,o);for(let s=e+1;s<e+r-1;s++)t[s]?.put(n,"│",o),t[s]?.put(n+i-1,"│",o);t[e+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,o)}function co(t,e=t.site,n=t.siteAnsi){return[` ${e} `,`\x1B[7;${30+n}m`]}function mm(t){return`${lt[Math.floor(t/le)]?.name??"local"} ${t%le}`}function pm(t,e,n){let r=[{name:"all",moved:!1},...lt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===n.site?co(n,u):[` ${u} `,ut];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Ct(c),0)<=e,o=t.run(0,i?r:[co(n)]);if(n.asking!==void 0)t.run(o,[[` ${n.asking} was cut off — this network may block it. turn on the unblock proxy? `,Qt],["y",ue],[" turn on ",ut],["n",ue],[" not now",ut]])}function wm(t,e,n,r){if(n.editing!==void 0){let c=t.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),u=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,n.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,ut);return}let i=t.run(0,[["⌕ ",r],[n.tag||"nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":ut]]),o=Ge.filter((c)=>!n.block.includes(c)),s=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...n.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ut),n.total>0||!n.searching){let c=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)c.push([` of ${n.total}`,ut]);t.right(e,c)}}function bm(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,ce]];if(t.cut==="off")return[["opaque · x cuts out",Qt]];if(t.cut==="failed")return[["opaque · no cut-out",Qt]];return[t.clear>0?[`${t.clear}% transparent`,ce]:["opaque",Qt]]}function $h(t){return t.site==="all"?"any site":t.site}function Hh(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${mm(t.installing)}`,Qt];if(t.hint)return[t.hint,ce];if(t.error)return[t.error,Qt];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,Qt];if(t.fetching)return[`fetching ${t.fetching.id%le} · ${lm(t.fetching.got,t.fetching.size)}`,Qt];if(t.cutting!==void 0)return[`cutting out ${t.cutting%le}`,Qt];if(t.preparing!==void 0)return[`preparing ${t.preparing%le}`,Qt];if(t.saved)return[t.saved,ce];if(t.note)return[t.note,ut];return}function $m(t,e,n,r,i,o){let{perRow:s,rowsVis:c}=De(n,r);wm(t[0],n,i,o),pm(t[1],n,i);for(let m=0;m<s*c;m++){let b=i.top*s+m,g=i.tiles[b];if(!g)break;let $=2+Math.floor(m/s)*At.height,y=m%s*At.pitch,F=b===i.focus;if(F)dm(t,$,y,At.height,At.pitch-1,o);if(g.thumb)e.push({id:g.key,path:g.thumb,row:$+1,col:y+1,cols:At.cols,rows:At.rows,z:-1});if(t[$+10]?.run(y+1,[...i.installed.includes(g.key)?[["✓ ",ce]]:[],...i.site==="all"?[["● ",`\x1B[${30+g.siteAnsi}m`]]:[],[String(g.id),F?ue:""],[" ",""],Nh(g)]),g.mates.length>0)t[$+10]?.put(y+At.cols,"≈",o);let E=g.artist?Fh(g.artist):g.owner&&`@${g.owner}`;if(E)t[$+11]?.put(y+1,E.slice(0,At.cols-8),ut);let M=[];if(g.score>0)M.push([`★${g.score}`,ut]);if(g.variants>1)M.push([` ×${g.variants}`,o]);if(M.length>0)t[$+11]?.right(y+At.cols+1,M)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,a=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(a.length>0)t[r-2]?.put(0,a.join(" "),ut);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${$h(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${$h(i)} — tab tries ${i.nextSite}`,ut);let f=t[r-1],l=Hh(i);if(i.searching&&i.tiles.length===0&&!l){nr(f,n,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ut],right:["esc","back"]});return}nr(f,n,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function km(t,e,n,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[co(i,s.site,s.siteAnsi),[" ",""],[String(s.id),ue],[" ",""],Nh(s)];if(s.artist)u.push([` · ${Fh(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ut]);if(c)u.push([` · ${Ih(c.bytes)}`,ut]);if(s.owner)u.push([` · ${s.owner}`,ut]);if(s.origin)u.push([` · ${s.origin}`,ut]);if(c)u.push([" ",""],...bm(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(n,[["≈ ",o],[s.mates.join(" "),ut]]);if(gm(t,3,2,n-4,r-2,i),i.shown)e.push({id:sm+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:cm});let h=Hh(i);nr(t[r-1],n,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Em={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${lt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function ym(t,e,n,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),c=Math.max(...r.settings.map((l)=>l.choices.reduce((m,b)=>m+b.length+(l.multi?6:3),0))),u=Math.min(e-2,Math.max(28,s+c+8)),h=r.settings.length+4,a=Math.floor((e-u)/2),f=Math.max(2,Math.floor((n-h)/2));t[f]?.put(a,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let l=f+1;l<f+h-1;l++)t[l]?.put(a,`│${" ".repeat(u-2)}│`);r.settings.forEach((l,m)=>{let b=t[f+2+m];b.put(a+3,l.label,m===o?ue:ut);let g=a+5+s,$=l.value.split(" ");l.choices.forEach((y,F)=>{let E=$.includes(y),M=l.multi&&m===o&&F===l.cursor?"4;":"",p=l.multi?` ${E?"[x]":"[ ]"} ${y} `:` ${y} `;g=b.put(g,p,E?`\x1B[${M}7;${30+r.siteAnsi}m`:M?`\x1B[4m${ut}`:ut)+1})}),t[f+h-1]?.put(a,`╰${"─".repeat(u-2)}╯`),nr(t[n-1],e,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function vm(t,e,n,r,i){let o=Em[r.mode],s=Math.min(e-2,50),c=o.length+4,u=Math.floor((e-s)/2),h=Math.max(2,Math.floor((n-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let a=h+1;a<h+c-1;a++)t[a]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([a,f],l)=>{t[h+2+l]?.put(u+3,a,ue),t[h+2+l]?.put(u+13,f.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),nr(t[n-1],e,i,{badge:"KEYS",right:["? esc","close"]})}function Mm(t,e,n){let r=e.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Ct(c.value))),s=Math.max(7,...i.map(Ct));r.forEach((c,u)=>{let h=u===e.pick,a=t[1+u];a?.run(0,[[h?"▸ ":" ",n],[c.value,h?ue+n:""]]),a?.right(2+o+2+s,[[i[u],ut]])})}function Oh(t,e,n){let r=Array.from({length:n},()=>new ei(e)),i=[],o=Sh(t.colors.cursor);if(e<Ke.cols||n<Ke.rows)return r[0]?.put(0,"ttheme find",ue+o),r[1]?.put(0,`needs ${Ke.cols}×${Ke.rows} — now ${e}×${n}`),r[2]?.put(0,"esc quits",ut),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")km(r,i,e,n,t,o);else $m(r,i,e,n,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<n-1;s++)r[s]=new ei(e);return Mm(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<n;c++)r[c]=new ei(e);if(t.help)vm(r,e,n,t,o);else ym(r,e,n,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Sm=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),Im=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),Fm=0.04,Nm=0.1,Hm=0.05,Om=4096;function jm(t){return new Set(t.cutouts.split(/\s+/).map((e)=>e.replace(/^~/,"")).filter(Boolean))}function Rm(t,e,n,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...jm(i)].some((a)=>s.has(a)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(e.w/e.h):1;return(o.solo?2:0)+([...Sm].some((a)=>s.has(a))?-3:0)+([...Im].some((a)=>s.has(a))?-1.5:0)+2*Math.min(1,u/e.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(n>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(n):0)+2*r}function ni(t,e,n=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:Rm(i,e,r.get(i.site)??0,n.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Rh(t){let e=new Map;for(let r of t)e.set(r.site,[...e.get(r.site)??[],r]);let n=[];for(let r=0;n.length<t.length;r++)for(let i of e.values()){let o=i[r];if(o)n.push(o)}return n}function ho(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function jh(t,e,n){let[r,i,o]=[ho(t),ho(e),ho(n)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function Ph(t,e){let n=e.map((s)=>jh(...Gt(s))).filter(([,s,c])=>Math.hypot(s,c)>=Fm);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/Om))),i=n.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,a,f]=jh(t.data[u],t.data[u+1],t.data[u+2]);n.forEach(([l,m,b],g)=>{if(Math.hypot(h-l,a-m,f-b)<Nm)i[g]=i[g]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/Hm),0)/n.length}import{execFileSync as Qm,spawn as Zm}from"node:child_process";import{existsSync as Dt,mkdirSync as or,readFileSync as en,realpathSync as qm,rmSync as lo,utimesSync as xm,writeFileSync as sr}from"node:fs";import{homedir as nn}from"node:os";import{dirname as cr,join as mt}from"node:path";import{chmodSync as Pm,copyFileSync as Gm,existsSync as tn,mkdirSync as Lm,readFileSync as ao,realpathSync as Tm,renameSync as Um,rmSync as Gh,statSync as Km,writeFileSync as Am}from"node:fs";import{dirname as Jm}from"node:path";function Lh(t){return`${t}.ttheme.bak`}var Wm=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function fo(t){let e=Lh(t);if(tn(t)&&!tn(e)&&!Wm.test(ao(t,"utf8")))Gm(t,e)}function Th(t,e){let n=tn(t)?Tm(t):t;Lm(Jm(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(Am(r,e),tn(n))Pm(r,Km(n).mode&4095);Um(r,n)}function rr(t,e){if((tn(t)?ao(t,"utf8"):void 0)===e)return!1;return fo(t),Th(t,e),!0}function Uh(t,e){let n=Lh(t),r=tn(n)?ao(n,"utf8"):void 0;if(e===""&&r===void 0)return Gh(t,{force:!0}),"removed";if(Th(t,e),r===void 0||r===e)return Gh(n,{force:!0}),"restored";return"kept backup"}var _m={ghostty:Nn,kitty:On,alacritty:Fn,wezterm:zn,iterm2:Hn,"windows-terminal":Bn,warp:Yn},Kh="ttheme-default";function Se(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let e=(n,r)=>Qm(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?e("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")e("defaults",["write",t,"Default Bookmark Guid","-string",n])},running:()=>{try{return e("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function te(t){return t.off?void 0:on(t)}function ur(t,e){if(!t.terminals.includes("iterm2"))return t;let n=e.read();return n&&!n.startsWith("ttheme-")?{...t,itermBase:n}:t}function We(t,e){if(!t.terminals.includes("iterm2"))return!1;let n=e.read(),r=te(t)?Kh:n===Kh?t.itermBase:void 0;if(!r||r===n)return!1;return e.write(r),!0}function Rt(){return process.env.XDG_CONFIG_HOME??mt(nn(),".config")}function hr(t){return mt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function Ah(t){return mt(t,"ttheme","installed.json")}function Jt(t){let e=Ah(t);if(!Dt(e))throw Error(`nothing installed yet at ${e} — run \`ttheme init\` first`);let n=JSON.parse(en(e,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${e} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>Ar.includes(r)),...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},palettes:n.palettes}}function ar(t,e){let n=Ah(t);or(cr(n),{recursive:!0}),sr(n,`${JSON.stringify(e,null,2)}
|
|
131
|
-
`)}function
|
|
128
|
+
}`;function ao(){return process.platform==="darwin"}function Hh(t){return t>=ym&&t<=Mm}function jh(t,e,n){return new Promise((r,i)=>{let o=km("osascript",["-l","JavaScript","-e",vm,t,e],{stdio:["ignore","ignore","pipe"],signal:AbortSignal.any([n,AbortSignal.timeout(Em)])}),s="";o.stderr.on("data",(c)=>{s+=c}),o.on("error",i),o.on("close",(c)=>{if(c===0){r();return}i(Error(s.trim().split(`
|
|
129
|
+
`).at(-1)||`osascript exited ${c}`))})})}var Kt={pitch:25,cols:22,rows:9,height:13},Ke={cols:25,rows:16},Sm=2147483648,Im=-1073741826,Fm=1600,Nm="\x1B[0m",ue="\x1B[1m",ut="\x1B[2m",nr="\x1B[31m",ce="\x1B[32m",xt="\x1B[33m",ni="\x1B[1;34m",Rm="\x1B[35m",Om={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end","1~":"home","7~":"home","4~":"end","8~":"end","5~":"pgup","6~":"pgdn",I:"focus-in",O:"focus-out"};function Lh(t){let e=[],n=0;while(n<t.length){let r=t[n]??"";if(r==="\x1B"){let i=/^(?:\[([0-9;]*)([A-Za-z~])|O([A-Za-z]))/.exec(t.slice(n+1));if(i){e.push(Om[`${i[1]??""}${i[2]??i[3]??""}`]??"nop"),n+=1+i[0].length;continue}let o=t[n+1]??"";if(/^[a-z]$/.test(o)){e.push(`alt-${o}`),n+=2;continue}e.push("esc"),n++;continue}e.push(r==="\r"||r===`
|
|
130
|
+
`?"enter":r==="\t"?"tab":r==="\x03"?"ctrl-c":r==="\x16"?"ctrl-v":r===""||r==="\b"?"backspace":r),n++}return e}var Th="\x1B]1337;ReportCellSize\x07\x1B[16t",Ph="\x1B]1337;ReportCellSize=";function go(t){let e=t.indexOf(Ph);if(e!==-1){let i=t.slice(e+Ph.length),o=[i.indexOf("\x07"),i.indexOf("\x1B\\")].filter((u)=>u!==-1),s=o.length>0?Math.min(...o):-1,c=s===-1?null:/^([\d.]+);([\d.]+);([\d.]+)$/.exec(i.slice(0,s));if(c){let u=Number(c[3]);return{cell:{h:Math.round(Number(c[1])*u),w:Math.round(Number(c[2])*u)},rest:t.slice(0,e)+i.slice(s+(i[s]==="\x07"?1:2))}}}let n=t.indexOf("\x1B[6;"),r=n===-1?null:/^\[6;(\d+);(\d+)t/.exec(t.slice(n+1));if(!r)return null;return{cell:{h:Number(r[1]),w:Number(r[2])},rest:t.slice(0,n)+t.slice(n+1+r[0].length)}}function tn(t,e){return{perRow:Math.max(1,Math.floor((t+1)/Kt.pitch)),rowsVis:Math.max(1,Math.floor((e-4)/Kt.height))}}function Ah(t){return`\x1B_Ga=t,t=f,f=100,i=${t.id},q=2;${Buffer.from(t.path).toString("base64")}\x1B\\`}function Uh(t){return`\x1B[${t.row+1};${t.col+1}H\x1B_Ga=p,i=${t.id},p=${t.id},c=${t.cols},r=${t.rows},C=1,z=${t.z},q=2\x1B\\`}function Kh(t){return`\x1B_Ga=d,d=I,i=${t},q=2\x1B\\`}function Jh(t){return`\x1B[38;2;${jt(t).join(";")}m`}function fo(t){return`\x1B[48;2;${jt(t).join(";")}m`}function Xt(t){return Array.from(t).length}class ri{parts=[];cols;constructor(t){this.cols=t}put(t,e,n=""){return this.parts.push({col:t,text:e,sgr:n}),t+Xt(e)}run(t,e){let n=t;for(let[r,i]of e)n=this.put(n,r,i);return n}right(t,e){this.run(t-e.reduce((n,[r])=>n+Xt(r),0),e)}render(){let t="";for(let{col:e,text:n,sgr:r}of this.parts){if(e>=this.cols||e<0)continue;let i=Array.from(n).slice(0,this.cols-e).join("");t+=`\x1B[${e+1}G${r}${i}${r?Nm:""}`}return t}}function Wh(t){return t>=1e6?`${(t/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(t/1000))} KB`}function Hm(t,e){if(!e)return Wh(t);return e>=1e6?`${(t/1e6).toFixed(1)}/${(e/1e6).toFixed(1)} MB`:`${Math.round(t/1000)}/${Math.round(e/1000)} KB`}function xh(t){return t.replace(/_\([^)]*\)?$/,"")}function Qh(t){return[`${t.reduced?"↓":""}${t.width}×${t.height}`,Math.max(t.width,t.height)<Fm?xt:ut]}function rr(t,e,n,r){let i=[...r.keys??[]],o=r.lead,s=r.right,c=()=>{let a=[...o?[Xt(o[0])]:[],...i.map(([l,m])=>Xt(l)+1+Xt(m))];return(r.badge?Xt(r.badge)+4:0)+a.reduce((l,m)=>l+m,0)+3*Math.max(0,a.length-1)+(s?3+Xt(s[0])+1+Xt(s[1]):0)};while(c()>e)if(i.length>2)i.splice(-2,1);else if(s)s=void 0;else if(i.length>1)i.splice(-2,1);else break;if(o&&c()>e){let a=Math.max(0,Xt(o[0])-(c()-e)-1);o=[`${Array.from(o[0]).slice(0,a).join("")}…`,o[1]]}let u=0;if(r.badge)u=t.put(0,` ${r.badge} `,`\x1B[7;1m${n}`)+2;if([...o?[[o]]:[],...i.map(([a,f])=>[[a,ue],[` ${f}`,ut]])].forEach((a,f)=>{u=t.run(u+(f?3:0),a)}),s)t.right(e,[[s[0],ue],[` ${s[1]}`,ut]])}function jm(t,e,n,r,i,o){let{ansi:s,selection:c,cursor:u}=o.colors,h=r<44?3:4;if(r>=56)h=Math.min(7,Math.floor((r+1)/8)-1);let a=n;for(let b=0;b<8;b++)a=(t[e]?.put(a,"▀".repeat(h),Jh(s[b]??u)+fo(s[b+8]??u))??a)+1;let f=["❯ ",ce],l=[[["~/code/demo",ni],[" on ",ut],["main",Rm],[" +2",ce],[" ~1",xt]]];if(l.push([f,["git status -sb",""]]),r>=44)l.push([["## ",""],["main",ce],["...",""],["origin/main",nr],[" [ahead 1]",xt]]);if(l.push([[" M",nr],[" src/main.rs",""]]),l.push([["??",nr],[" notes.md",""]]),l.push([]),r>=44)l.push([f,["ls",""]]),l.push([["docs",ni],[" ",""],["src",ni],[" ",""],["tests",ni],[" Cargo.toml README.md",""]]),l.push([]);l.push([f,["cargo test",""]]),l.push([[" ✓",ce],[" parses config",""]]);let m=[[" ✗",nr],[" renders frame",""]];if(r>=44)m.push([" expected ",ut],["3",ce],[", received ",ut],["2",nr]);l.push(m),l.push([]),l.push([f,["echo ",""],["selected text",fo(c)],[" ",""],[" ",fo(u)]]),l.forEach((b,g)=>{let $=e+2+g;if($<=i)t[$]?.run(n,b)})}function Pm(t,e,n,r,i,o){t[e]?.put(n,`╭${"─".repeat(i-2)}╮`,o);for(let s=e+1;s<e+r-1;s++)t[s]?.put(n,"│",o),t[s]?.put(n+i-1,"│",o);t[e+r-1]?.put(n,`╰${"─".repeat(i-2)}╯`,o)}function lo(t,e=t.site,n=t.siteAnsi){return[` ${e} `,`\x1B[7;${30+n}m`]}function Gm(t){return`${lt[Math.floor(t/ge)]?.name??"local"} ${t%ge}`}function Lm(t,e,n){let r=[{name:"all",moved:!1},...lt].flatMap((s,c)=>{let u=`${s.name}${s.moved?"*":""}`,h=s.name===n.site?lo(n,u):[` ${u} `,ut];return c?[[" ",""],h]:[h]}),i=r.reduce((s,[c])=>s+Xt(c),0)<=e,o=t.run(0,i?r:[lo(n)]);if(n.asking!==void 0)t.run(o,[[` ${n.asking} was cut off — this network may block it. turn on the unblock proxy? `,xt],["y",ue],[" turn on ",ut],["n",ue],[" not now",ut]])}function Tm(t,e,n,r){if(n.editing!==void 0){let c=t.run(0,[["⌕ ",r],[n.editing,""],["█",r]]),u=n.suggest?.length?" ↑↓ pick enter searches":" enter searches";t.put(c,n.editing?u:` a tag, a post url or an id, or drop a picture or ctrl+v — ${n.tag||"esc leaves"}`,ut);return}let i=t.run(0,[["⌕ ",r],[n.tag||"nothing yet — / searches, ctrl+v pastes a picture",n.tag?"":ut]]),o=Le.filter((c)=>!n.block.includes(c)),s=[n.preset,...n.solo?["solo"]:[],n.order,...n.rating.join("+")==="safe"?[]:[n.rating.join("+")],...o.length>0?[`allows ${o.join("+")}`]:[],...n.unblocked?["unblock"]:[]];if(t.put(i,` ${s.join(" ")}`,ut),n.total>0||!n.searching){let c=[[`${n.tiles.length}/${n.checked}`,""]];if(n.checked<n.total)c.push([` of ${n.total}`,ut]);t.right(e,c)}}function Am(t){if(t.cut==="on")return[[`cut out · ${t.clear}% transparent`,ce]];if(t.cut==="off")return[["opaque · x cuts out",xt]];if(t.cut==="failed")return[["opaque · no cut-out",xt]];return[t.clear>0?[`${t.clear}% transparent`,ce]:["opaque",xt]]}function Gh(t){return t.site==="all"?"any site":t.site}function Zh(t){if(t.installing!==void 0)return[`installing ${t.palette} ← ${Gm(t.installing)}`,xt];if(t.hint)return[t.hint,ce];if(t.error)return[t.error,xt];if(t.waiting!==void 0)return[`${t.slow??t.site} asked to slow down · ${t.waiting}s`,xt];if(t.fetching)return[`fetching ${t.fetching.id%ge} · ${Hm(t.fetching.got,t.fetching.size)}`,xt];if(t.cutting!==void 0)return[`cutting out ${t.cutting%ge}`,xt];if(t.preparing!==void 0)return[`preparing ${t.preparing%ge}`,xt];if(t.saved)return[t.saved,ce];if(t.note)return[t.note,ut];return}function Um(t,e,n,r,i,o){let{perRow:s,rowsVis:c}=tn(n,r);Tm(t[0],n,i,o),Lm(t[1],n,i);for(let m=0;m<s*c;m++){let b=i.top*s+m,g=i.tiles[b];if(!g)break;let $=2+Math.floor(m/s)*Kt.height,y=m%s*Kt.pitch,F=b===i.focus;if(F)Pm(t,$,y,Kt.height,Kt.pitch-1,o);if(g.thumb)e.push({id:g.key,path:g.thumb,row:$+1,col:y+1,cols:Kt.cols,rows:Kt.rows,z:-1});if(t[$+10]?.run(y+1,[...i.installed.includes(g.key)?[["✓ ",ce]]:[],...i.site==="all"?[["● ",`\x1B[${30+g.siteAnsi}m`]]:[],[String(g.id),F?ue:""],[" ",""],Qh(g)]),g.mates.length>0)t[$+10]?.put(y+Kt.cols,"≈",o);let E=g.artist?xh(g.artist):g.owner&&`@${g.owner}`;if(E)t[$+11]?.put(y+1,E.slice(0,Kt.cols-8),ut);let v=[];if(g.score>0)v.push([`★${g.score}`,ut]);if(g.variants>1)v.push([` ×${g.variants}`,o]);if(v.length>0)t[$+11]?.right(y+Kt.cols+1,v)}let u=i.top*s,h=i.tiles.length-(i.top+c)*s,a=[...u>0?[`↑ ${u} above`]:[],...h>0?[`↓ ${h} more`]:[]];if(a.length>0)t[r-2]?.put(0,a.join(" "),ut);if(!i.searching&&i.tiles.length===0&&!i.error)t[3]?.put(0,i.preset==="cutouts"?`no transparent cutouts of ${i.tag} on ${Gh(i)} — c searches every post, tab tries ${i.nextSite}`:`no posts of ${i.tag} on ${Gh(i)} — tab tries ${i.nextSite}`,ut);let f=t[r-1],l=Zh(i);if(i.searching&&i.tiles.length===0&&!l){rr(f,n,o,{badge:"FIND",lead:[i.preset==="cutouts"?"checking png headers":"fetching posts",ut],right:["esc","back"]});return}rr(f,n,o,{badge:"FIND",lead:l,keys:i.asking!==void 0?[]:[["←↑↓→","move"],["enter","try on"],["tab","site"],["ctrl+v","picture"],["s","settings"],["/","search"],["?","keys"]],right:i.asking!==void 0?void 0:["esc","back"]})}function Km(t,e,n,r,i,o){let s=i.tiles[i.focus];if(!s)return;let c=i.shown?.id===s.key?i.shown:void 0,u=[lo(i,s.site,s.siteAnsi),[" ",""],[String(s.id),ue],[" ",""],Qh(s)];if(s.artist)u.push([` · ${xh(s.artist)}`,""]);if(s.score>0)u.push([` · ★${s.score}`,ut]);if(c)u.push([` · ${Wh(c.bytes)}`,ut]);if(s.owner)u.push([` · ${s.owner}`,ut]);if(s.origin)u.push([` · ${s.origin}`,ut]);if(c)u.push([" ",""],...Am(c));if(t[0]?.run(0,u),s.mates.length>0)t[0]?.right(n,[["≈ ",o],[s.mates.join(" "),ut]]);if(jm(t,3,2,n-4,r-2,i),i.shown)e.push({id:Sm+i.shown.id,path:i.shown.path,row:0,col:0,cols:n,rows:r,z:Im});let h=Zh(i);rr(t[r-1],n,o,{badge:"TRY",lead:h,keys:i.installing===void 0?[["←→","browse"],["enter","install"],...i.shown?.cut==="on"||i.shown?.cut==="off"?[["x","cut out"]]:[],["?","keys"]]:[],right:i.installing===void 0?["esc","grid"]:void 0})}var Jm={grid:[["move","←↑↓→ home end pgup pgdn"],["try on","enter"],["site",`tab all, ${lt.map((t)=>t.name).join(", ")}`],["posts","c cutouts or every post"],["search","/ a tag, a post url or an id"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window or paste its link"],["unfold","space a set of ×N"],["open","o the post page in a browser"],["settings","s rating, block, posts, solo, order, sets, remove bg"],["back","esc returns to preview"],["close","? esc"]],try:[["browse","←→"],["install","enter"],["cut out","x the background off or on, on an opaque picture"],["open","o the post page in a browser"],["your own","ctrl+v or v a picture from the clipboard · drop one on the window"],["grid","esc"],["close","? esc"]]};function Wm(t,e,n,r,i){let o=r.panel??0,s=Math.max(...r.settings.map((l)=>l.label.length)),c=Math.max(...r.settings.map((l)=>l.choices.reduce((m,b)=>m+b.length+(l.multi?6:3),0))),u=Math.min(e-2,Math.max(28,s+c+8)),h=r.settings.length+4,a=Math.floor((e-u)/2),f=Math.max(2,Math.floor((n-h)/2));t[f]?.put(a,`╭─ settings ${"─".repeat(Math.max(0,u-13))}╮`);for(let l=f+1;l<f+h-1;l++)t[l]?.put(a,`│${" ".repeat(u-2)}│`);r.settings.forEach((l,m)=>{let b=t[f+2+m];b.put(a+3,l.label,m===o?ue:ut);let g=a+5+s,$=l.value.split(" ");l.choices.forEach((y,F)=>{let E=$.includes(y),v=l.multi&&m===o&&F===l.cursor?"4;":"",p=l.multi?` ${E?"[x]":"[ ]"} ${y} `:` ${y} `;g=b.put(g,p,E?`\x1B[${v}7;${30+r.siteAnsi}m`:v?`\x1B[4m${ut}`:ut)+1})}),t[f+h-1]?.put(a,`╰${"─".repeat(u-2)}╯`),rr(t[n-1],e,i,{badge:"SET",keys:[["↑↓","setting"],["←→","value"],["space","toggle"],["enter","save"]],right:["esc","undo"]})}function xm(t,e,n,r,i){let o=Jm[r.mode],s=Math.min(e-2,50),c=o.length+4,u=Math.floor((e-s)/2),h=Math.max(2,Math.floor((n-c)/2));t[h]?.put(u,`╭─ keys ${"─".repeat(s-9)}╮`);for(let a=h+1;a<h+c-1;a++)t[a]?.put(u,`│${" ".repeat(s-2)}│`);o.forEach(([a,f],l)=>{t[h+2+l]?.put(u+3,a,ue),t[h+2+l]?.put(u+13,f.slice(0,s-16))}),t[h+c-1]?.put(u,`╰${"─".repeat(s-2)}╯`),rr(t[n-1],e,i,{badge:"KEYS",right:["? esc","close"]})}function Qm(t,e,n){let r=e.suggest??[],i=r.map((c)=>c.count>0?String(c.count):c.palette??"0"),o=Math.max(...r.map((c)=>Xt(c.value))),s=Math.max(7,...i.map(Xt));r.forEach((c,u)=>{let h=u===e.pick,a=t[1+u];a?.run(0,[[h?"▸ ":" ",n],[c.value,h?ue+n:""]]),a?.right(2+o+2+s,[[i[u],ut]])})}function qh(t,e,n){let r=Array.from({length:n},()=>new ri(e)),i=[],o=Jh(t.colors.cursor);if(e<Ke.cols||n<Ke.rows)return r[0]?.put(0,"ttheme find",ue+o),r[1]?.put(0,`needs ${Ke.cols}×${Ke.rows} — now ${e}×${n}`),r[2]?.put(0,"esc quits",ut),{lines:r.map((s)=>s.render()),images:i};if(t.mode==="try")Km(r,i,e,n,t,o);else Um(r,i,e,n,t,o);if(t.mode==="grid"&&t.editing!==void 0&&t.suggest?.length){for(let s=1;s<n-1;s++)r[s]=new ri(e);return Qm(r,t,o),{lines:r.map((s)=>s.render()),images:[]}}if(t.help||t.panel!==void 0){let s=t.mode==="try"?i:[];for(let c=0;c<n;c++)r[c]=new ri(e);if(t.help)xm(r,e,n,t,o);else Wm(r,e,n,t,o);return{lines:r.map((c)=>c.render()),images:s}}return{lines:r.map((s)=>s.render()),images:i}}var Zm=new Set(["comic","4koma","monochrome","greyscale","sketch","lineart","speech_bubble"]),qm=new Set(["scenery","landscape","scenic","no_humans","wide_shot","very_wide_shot"]),_m=0.04,Cm=0.1,Xm=0.05,Vm=4096;function Ym(t){return new Set(t.cutouts.split(/\s+/).map((e)=>e.replace(/^~/,"")).filter(Boolean))}function zm(t,e,n,r=0){let{site:i,post:o}=t,s=new Set(o.tags),c=[...Ym(i)].some((a)=>s.has(a)),u=Math.min(o.width,o.height),h=o.width>0&&o.height>0?o.width/o.height/(e.w/e.h):1;return(o.solo?2:0)+([...Zm].some((a)=>s.has(a))?-3:0)+([...qm].some((a)=>s.has(a))?-1.5:0)+2*Math.min(1,u/e.h)+(c?1.5:-Math.min(1.5,Math.abs(Math.log(h))))+(n>0?1.5*Math.log1p(Math.max(0,o.score))/Math.log1p(n):0)+2*r}function ii(t,e,n=new Map){let r=new Map;for(let{site:i,post:o}of t)r.set(i,Math.max(r.get(i)??0,o.score));return t.map((i,o)=>({pick:i,at:o,score:zm(i,e,r.get(i.site)??0,n.get(i.post))})).sort((i,o)=>o.score-i.score||i.at-o.at).map(({pick:i})=>i)}function Ch(t){let e=new Map;for(let r of t)e.set(r.site,[...e.get(r.site)??[],r]);let n=[];for(let r=0;n.length<t.length;r++)for(let i of e.values()){let o=i[r];if(o)n.push(o)}return n}function mo(t){let e=t/255;return e<=0.04045?e/12.92:((e+0.055)/1.055)**2.4}function _h(t,e,n){let[r,i,o]=[mo(t),mo(e),mo(n)],s=Math.cbrt(0.4122214708*r+0.5363325363*i+0.0514459929*o),c=Math.cbrt(0.2119034982*r+0.6806995451*i+0.1073969566*o),u=Math.cbrt(0.0883024619*r+0.2817188376*i+0.6299787005*o);return[0.2104542553*s+0.793617785*c-0.0040720468*u,1.9779984951*s-2.428592205*c+0.4505937099*u,0.0259040371*s+0.7827717662*c-0.808675766*u]}function Xh(t,e){let n=e.map((s)=>_h(...jt(s))).filter(([,s,c])=>Math.hypot(s,c)>=_m);if(n.length===0)return 0;let r=Math.max(1,Math.floor(Math.sqrt(t.width*t.height/Vm))),i=n.map(()=>0),o=0;for(let s=0;s<t.height;s+=r)for(let c=0;c<t.width;c+=r){let u=(s*t.width+c)*4;if(t.data[u+3]<128)continue;o++;let[h,a,f]=_h(t.data[u],t.data[u+1],t.data[u+2]);n.forEach(([l,m,b],g)=>{if(Math.hypot(h-l,a-m,f-b)<Cm)i[g]=i[g]+1})}if(o===0)return 0;return i.reduce((s,c)=>s+Math.min(1,c/o/Xm),0)/n.length}import{execFileSync as cp,spawn as up}from"node:child_process";import{existsSync as Dt,mkdirSync as sr,readFileSync as nn,realpathSync as hp,rmSync as bo,utimesSync as ap,writeFileSync as cr}from"node:fs";import{homedir as rn}from"node:os";import{dirname as ur,join as mt}from"node:path";import{chmodSync as Bm,copyFileSync as Dm,existsSync as en,mkdirSync as tp,readFileSync as po,realpathSync as ep,renameSync as np,rmSync as Vh,statSync as rp,writeFileSync as ip}from"node:fs";import{dirname as op}from"node:path";function Yh(t){return`${t}.ttheme.bak`}var sp=/^(?:#|--) ttheme begin$|path = "ttheme-/m;function wo(t){let e=Yh(t);if(en(t)&&!en(e)&&!sp.test(po(t,"utf8")))Dm(t,e)}function zh(t,e){let n=en(t)?ep(t):t;tp(op(n),{recursive:!0});let r=`${n}.ttheme-${process.pid}`;if(ip(r,e),en(n))Bm(r,rp(n).mode&4095);np(r,n)}function ir(t,e){if((en(t)?po(t,"utf8"):void 0)===e)return!1;return wo(t),zh(t,e),!0}function Bh(t,e){let n=Yh(t),r=en(n)?po(n,"utf8"):void 0;if(e===""&&r===void 0)return Vh(t,{force:!0}),"removed";if(zh(t,e),r===void 0||r===e)return Vh(n,{force:!0}),"restored";return"kept backup"}var fp={ghostty:Rn,kitty:Hn,alacritty:Nn,wezterm:Bn,iterm2:On,"windows-terminal":Dn,warp:zn},Dh="ttheme-default";function Ie(t=process.env.TTHEME_ITERM_SUITE??"com.googlecode.iterm2"){let e=(n,r)=>cp(n,r,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return{read:()=>{try{return process.platform==="darwin"?e("defaults",["read",t,"Default Bookmark Guid"])||void 0:void 0}catch{return}},write:(n)=>{if(process.platform==="darwin")e("defaults",["write",t,"Default Bookmark Guid","-string",n])},running:()=>{try{return e("pgrep",["-x","iTerm2"])!==""}catch{return!1}}}}function te(t){return t.off?void 0:sn(t)}function hr(t,e){if(!t.terminals.includes("iterm2"))return t;let n=e.read();return n&&!n.startsWith("ttheme-")?{...t,itermBase:n}:t}function xe(t,e){if(!t.terminals.includes("iterm2"))return!1;let n=e.read(),r=te(t)?Dh:n===Dh?t.itermBase:void 0;if(!r||r===n)return!1;return e.write(r),!0}function Pt(){return process.env.XDG_CONFIG_HOME??mt(rn(),".config")}function ar(t){return mt(t,"Library","Application Support","iTerm2","DynamicProfiles","ttheme.json")}function ta(t){return mt(t,"ttheme","installed.json")}function Jt(t){let e=ta(t);if(!Dt(e))throw Error(`nothing installed yet at ${e} — run \`ttheme init\` first`);let n=JSON.parse(nn(e,"utf8"));if(!Array.isArray(n?.palettes)||!Array.isArray(n.terminals))throw Error(`${e} has no palettes or terminals`);return{terminals:n.terminals.filter((r)=>Wr.includes(r)),...n.startup?{startup:n.startup}:{},...n.off?{off:!0}:{},...n.itermBase?{itermBase:n.itermBase}:{},...n.wtHome?{wtHome:n.wtHome}:{},...n.wtProfile?{wtProfile:n.wtProfile}:{},palettes:n.palettes}}function fr(t,e){let n=ta(t);sr(ur(n),{recursive:!0}),cr(n,`${JSON.stringify(e,null,2)}
|
|
131
|
+
`)}function or(t){return{name:t.name,group:t.group,...t.native?{native:t.native}:{},lead:t.lead===!0,order:t.order,...t.default?{role:"default"}:{},ansiSource:t.ansiSource,...t.booru?{booru:t.booru}:{},...t.booruSites?{booruSites:t.booruSites}:{},background:t.background,foreground:t.foreground,cursor:t.cursor,selectionBackground:t.selection,ansi:t.ansi,signature:t.signature,signatureSlots:t.signatureSlots,ghostty:{iconGhost:t.cursor,iconScreen:[t.cursor,t.selection,t.background]},waive:t.waived??[]}}function ea(t,e){let n=new Map(t.palettes.map((o)=>[o.name,o])),r=e.filter((o)=>!n.has(o));if(r.length>0)throw Error(`not in the catalog: ${r.join(", ")} — ${ho(Pe(t.palettes),r)}`);let i=e.flatMap((o)=>{let s=Fh(n.get(o));return s.length>0?[`${o}: ${s.join(", ")}`]:[]});if(i.length>0)throw Error(`these palettes fail the contrast gate:
|
|
132
132
|
${i.join(`
|
|
133
|
-
`)}`);return t.palettes.filter((o)=>e.includes(o.name))}function
|
|
134
|
-
`).map((e)=>e.split(/[ =]/)[0]))].join(", ")}function
|
|
133
|
+
`)}`);return t.palettes.filter((o)=>e.includes(o.name))}function na(t,e){let n=t==="wezterm"?"colors":"themes";return(fp[t].emit?.(e)??[]).flatMap((r)=>{let[,i,o]=r.path.split("/");return i===n&&o!==void 0?[{file:o,content:r.content}]:[]})}function oi(t){return process.platform==="darwin"?mt(t,".warp","themes"):mt(process.env.XDG_DATA_HOME??mt(t,".local","share"),"warp-terminal","themes")}function Je(t,e,n){if(t==="warp")return oi(n);return mt(e,t,t==="wezterm"?"colors":"themes")}function si(t,e){return process.platform==="darwin"?mt(t,".warp","settings.toml"):mt(e,"warp-terminal","settings.toml")}var $o='"dark"';function ko(t){return mt(t,"ttheme","warp.base")}var lp="setTimeout(() => { const fs = require('node:fs'); const [file, next, seen] = process.argv.slice(-3); if (fs.readFileSync(file, 'utf8') !== seen) return; const tmp = file + '.ttheme-' + process.pid; fs.writeFileSync(tmp, next); fs.chmodSync(tmp, fs.statSync(file).mode & 0o7777); fs.renameSync(tmp, file) }, 1500)";function gp(t,e,n,r){let i=si(e,t);if(!Dt(i))return;let o=ko(t),s=nn(i,"utf8"),c=Qr(s),u=c?.includes(`path = "${ct("")}`)===!0,h;if(n){if(!u&&!Dt(o))sr(ur(o),{recursive:!0}),cr(o,c??"");h=nh(n)}else{if(!u)return;h=Dt(o)&&nn(o,"utf8")||$o,bo(o,{force:!0})}let a=Zr(s,h);if(a===s)return;if(r)wo(i),up(process.execPath,["-e",lp,hp(i),a,s],{detached:!0,stdio:"ignore"}).unref();else ir(i,a);return i}function ra(t){return mt(t,"ttheme","kitty.py")}function on(t,e){let n=mt(e,".wezterm.lua");return Dt(n)?n:mt(t,"wezterm","wezterm.lua")}function ci(t){return mt(t,"Microsoft","Windows Terminal","Fragments","ttheme","ttheme.json")}function Eo(t){return[mt(t,"Packages","Microsoft.WindowsTerminal_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Packages","Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe","LocalState","settings.json"),mt(t,"Microsoft","Windows Terminal","settings.json")].filter((e)=>Dt(e))}function dp(t){for(let e of t){let n=/"defaultProfile"\s*:\s*"(\{[0-9a-fA-F-]+\})"/.exec(nn(e,"utf8"))?.[1];if(n)return n}return}function sn(t){return t.startup&&t.palettes.includes(t.startup)?t.startup:t.palettes[0]}function We(t,e){return t==="ghostty"?mt(e,"ghostty","config"):mt(e,"kitty","kitty.conf")}function ia(t,e,n,r){return t==="ghostty"?Qu(mt(e,"ttheme"),n,r):Vu(n,ra(e),r)}function me(t){return Dt(t)?nn(t,"utf8"):""}function Qe(t){return mt(t,"alacritty","alacritty.toml")}function mp(t,e){return e?mt(t,"alacritty","themes",`${ct(e)}.toml`):void 0}function oa(t,e,n,r){let i=Ee(t),o=e.map(or),s=new Map;for(let u of o){let h=Bc(i,u.name,r);if(h)s.set(u.name,h)}let c=new Set(Pe(e).map((u)=>u.name));return Gs(o.filter((u)=>c.has(u.name)),s,o.find((u)=>u.name===te(n)),n.itermBase)}function cn(t,e=rn()){let n=Jt(t);if(!n.terminals.includes("iterm2"))return;let r=At(t),i=ar(e);sr(ur(i),{recursive:!0}),cr(i,oa(t,ea(r,n.palettes),n,e))}function lr(t,e,n,r=rn()){let i=ea(e,n.palettes),o=[],s=(a,f)=>{if(o.push(a),Dt(a)&&nn(a,"utf8")===f)return!1;return sr(ur(a),{recursive:!0}),cr(a,f),!0},c=(a,f)=>{o.push(a),ir(a,f)},u=te(n);for(let a of n.terminals){if(a==="iterm2"){s(ar(r),oa(t,i,n,r));continue}if(a==="windows-terminal"){if(n.wtHome){let g=Eo(n.wtHome),$=i.map(or),y=eo($,n.wtProfile??dp(g),u);if(s(ci(n.wtHome),y)){let F=new Date;for(let E of g)ap(E,F,F)}}continue}let f=u!==void 0&&a==="warp"&&!Dt(mt(oi(r),`ttheme-${u}.yaml`)),l=a==="warp"?gp(t,r,u,f):void 0;for(let g of i)for(let{file:$,content:y}of na(a,or(g)))s(mt(Je(a,t,r),$),y);if(a==="warp"){if(l)o.push(l);continue}if(a==="wezterm"){let g=mt(t,"ttheme","wezterm.lua");s(g,oh({path:g,colors:Je("wezterm",t,r),backgrounds:Ee(t),...u?{startup:u}:{},palettes:i.map(or)}));let $=on(t,r),y=Yn(me($),zu(g));if(y!==void 0)c($,y);continue}if(a==="alacritty"){let g=Qe(t),$=Vn(me(g),mp(t,u));if($!==void 0)c(g,$);continue}if(a==="kitty")s(ra(t),Ls({themes:Je("kitty",t,r),backgrounds:Ee(t)}));let m=We(a,t),b=me(m);c(m,_n(b,ia(a,t,u,b)))}let h=mt(t,"ttheme","palettes.zsh");return sr(ur(h),{recursive:!0}),cr(h,Di(i,u,n.terminals)),o.push(h),bo(`${h}.zwc`,{force:!0}),o}function sa(t,e){return t.startsWith(`${e}/`)?`~${t.slice(e.length)}`:t}function pp(t){return[...new Set(t.split(`
|
|
134
|
+
`).map((e)=>e.split(/[ =]/)[0]))].join(", ")}function ca(t,e,n=rn()){let r=te(e),i=(s)=>sa(s,n),o=[];for(let s of e.terminals){if(s==="iterm2"){o.push(`write ${i(ar(n))} — a "ttheme · <palette>" profile per palette`);continue}if(s==="windows-terminal"){if(e.wtHome)o.push(`write ${ci(e.wtHome)} — its schemes, and touch settings.json so it reloads`);continue}if(o.push(`write ${i(Je(s,t,n))}/${ct("*")} — a theme file per palette`),s==="warp"){let h=si(n,t);if(r&&Dt(h))o.push(`edit ${i(h)} — [appearance.themes] theme; \`ttheme off\` puts yours back`);continue}if(s==="wezterm"){let h=on(t,n);if(Yn(me(h),"")!==void 0)o.push(`edit ${i(h)} — a ttheme block before \`return config\`: color_scheme_dirs, color_scheme, pictures`);continue}if(s==="alacritty"){let h=Qe(t);if(Vn(me(h),void 0)!==void 0)o.push(`edit ${i(h)} — a ttheme block: general.import`);continue}let c=We(s,t),u=me(c);o.push(`edit ${i(c)} — a ttheme block: ${pp(ia(s,t,r,u))}`)}return o}function ua(t,e,n=rn()){let r=[],i=(o)=>sa(o,n);if(e.includes("ghostty")){let o=We("ghostty",t);if(Ue(me(o),"command"))r.push(`${i(o)} sets its own command — ttheme leaves it, so a new tab takes its palette once zsh starts`)}if(e.includes("kitty")){let o=me(We("kitty",t));if(Ue(o,"window_logo_scale")||Ue(o,"window_logo_alpha"))r.push("kitty.conf sets its own window_logo_scale or window_logo_alpha — pictures are drawn with them")}if(e.includes("alacritty")){let o=Qe(t);if(Yu(me(o)))r.push(`${i(o)} sets its own colors, which win over an imported palette — remove them to open with ttheme's`)}return r}function yo(t,e,n,r,i=rn()){let o=[];for(let s of n)for(let c of e.palettes.filter((u)=>r.includes(u.name)))for(let{file:u}of na(s,or(c))){let h=mt(Je(s,t,i),u);if(Dt(h))bo(h,{force:!0}),o.push(h)}return o}import{mkdirSync as ga,readFileSync as da,writeFileSync as ma}from"node:fs";import{dirname as pa}from"node:path";import{isMainThread as kp,parentPort as wa,Worker as Ep}from"node:worker_threads";var wp=/(?:^|[^0-9a-f])([0-9a-f]{32})(?:[^0-9a-f]|$)/i,bp=[[/yande\.re\/post\/show\/(\d+)/,"yande"],[/konachan\.(?:com|net)\/post\/show\/(\d+)/,"konachan"],[/danbooru\.donmai\.us\/(?:posts|post\/show)\/(\d+)/,"danbooru"]];function Mo(t){let e=/(\d+)_p(\d+)/.exec(t.source);return[...t.md5?[`md5:${t.md5}`]:[],...e&&t.source.includes("pximg")?[`pixiv:${e[1]}_p${e[2]}`]:[]]}function ha(t,e){let n=wp.exec(e.source)?.[1]?.toLowerCase();return[`post:${t.key}:${e.id}`,...e.md5?[`md5:${e.md5}`]:[],...n&&n!==e.md5?[`md5:${n}`]:[],...bp.flatMap(([r,i])=>{let o=r.exec(e.source)?.[1];return o?[`post:${i}:${Number(o)}`]:[]}),...e.family?[`family:${t.key}:${e.family}`]:[]]}function aa(t,e){let n=t.owner||t.artist;return n!==""&&n===(e.owner||e.artist)&&t.width===e.width&&t.height===e.height}function fa(t){let r=[];for(let o=0;o<8;o++){let s=Math.floor(o*t.height/8),c=Math.max(s+1,Math.floor((o+1)*t.height/8));for(let u=0;u<9;u++){let h=Math.floor(u*t.width/9),a=Math.max(h+1,Math.floor((u+1)*t.width/9)),f=0;for(let l=s;l<c;l++)for(let m=h;m<a;m++){let b=(l*t.width+m)*4,g=t.data[b+3]/255,$=0.299*t.data[b]+0.587*t.data[b+1]+0.114*t.data[b+2];f+=$*g+255*(1-g)}r.push(f/((a-h)*(c-s)))}}let i=0n;for(let o=0;o<8;o++)for(let s=0;s<8;s++)i=i<<1n|(r[o*9+s]>r[o*9+s+1]?1n:0n);return i.toString(16).padStart(16,"0")}function $p(t,e){let n=BigInt(`0x${t}`)^BigInt(`0x${e}`),r=0;while(n>0n)r+=Number(n&1n),n>>=1n;return r}function la(t,e){if(t.width<=0||t.height<=0||e.width<=0||e.height<=0)return!1;return Math.abs(Math.log(t.width/t.height/(e.width/e.height)))<0.01&&$p(t.hash,e.hash)<=2}var yp={thumb:"tile",match:"tile",show:"view",backdrop:"view"};function Mp(t){let e=Kc(new Uint8Array(da(t.from)),Te);if(t.job==="backdrop")return su(t.home,t.colors,t.tone,e,{...t.origin,bytes:new Uint8Array(da(t.source))},t),0;if(t.job==="match")return{match:Xh(e,t.colors),hash:fa(e)};if(t.job==="thumb")return ga(pa(t.to),{recursive:!0}),ma(t.to,ze(Wc(e,t.width,t.height))),0;let n=Ln(e);return ga(pa(t.to),{recursive:!0}),ma(t.to,ze(zc(e,t.colors,t.tone,t.width,t.height))),n}function vp(t){t.on("message",(e)=>{try{t.postMessage({id:e.id,value:Mp(e)})}catch(n){t.postMessage({id:e.id,error:n instanceof Error?n.message:String(n)})}})}class ba{worker;next=1;waiting=new Map;send(t){let e=this.next++;return new Promise((n,r)=>{let i=this.open();this.waiting.set(e,{ok:n,no:r}),i.ref(),i.postMessage({...t,id:e})})}close(){this.worker?.terminate(),this.worker=void 0,this.drop(Error("renderer closed"))}open(){if(this.worker)return this.worker;let t=new Ep(import.meta.filename);t.unref(),t.on("message",({id:n,value:r,error:i})=>{let o=this.waiting.get(n);if(this.waiting.delete(n),this.waiting.size===0)t.unref();if(i!==void 0)o?.no(Error(i));else o?.ok(r)});let e=(n)=>{if(this.worker===t)this.worker=void 0;this.drop(n instanceof Error?n:Error("renderer stopped"))};return t.on("error",e),t.on("exit",()=>e(void 0)),this.worker=t,t}drop(t){for(let e of this.waiting.values())e.no(t);this.waiting.clear()}}class vo{lines=new Map;run(t){let e=yp[t.job],n=this.lines.get(e);if(!n)n=new ba,this.lines.set(e,n);return n.send(t)}close(){for(let t of this.lines.values())t.close();this.lines.clear()}}if(!kp&&wa)vp(wa);import{connect as Sp,createServer as Ip}from"node:net";var Fp=20,$a=22;function So(t){let e=new Uint8Array(t.reduce((r,i)=>r+i.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Np(t,e=Fp){let n=t.subarray(5);if(t[0]!==$a||n.length<2)return[t];let r=Math.max(1,Math.min(e,n.length-1)),i=(o)=>So([Uint8Array.from([t[0],t[1],t[2],o.length>>8,o.length&255]),o]);return[i(n.subarray(0,r)),i(n.subarray(r))]}function Rp(t,e,n,r){let i=Sp(n,e,()=>{i.setNoDelay(!0),t.write(`HTTP/1.1 200 Connection Established\r
|
|
135
135
|
\r
|
|
136
|
-
`);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=
|
|
136
|
+
`);let o=r,s=!1,c=(u)=>{if(s){i.write(u);return}if(o=So([o,u]),o.length<5)return;let h=o[3]*256+o[4];if(o[0]!==$a){s=!0,i.write(o);return}if(o.length<5+h)return;s=!0;let[a,f]=Np(o.subarray(0,5+h));i.write(a),setTimeout(()=>{if(f)i.write(f);i.write(o.subarray(5+h))},10)};if(t.on("data",c),o.length>0){let u=o;o=new Uint8Array(0),c(u)}i.pipe(t)});i.on("error",()=>t.destroy()),i.on("close",()=>t.destroy()),t.on("error",()=>i.destroy()),t.on("close",()=>i.destroy())}function Op(t){t.setNoDelay(!0);let e=new Uint8Array(0),n=(r)=>{e=So([e,r]);let i=Buffer.from(e).toString("latin1"),o=i.indexOf(`\r
|
|
137
137
|
\r
|
|
138
138
|
`);if(o===-1)return;t.off("data",n);let s=/^CONNECT ([^ :]+):(\d+)/.exec(i);if(!s){t.end(`HTTP/1.1 405 Method Not Allowed\r
|
|
139
139
|
\r
|
|
140
|
-
`);return}
|
|
141
|
-
`)}class ba{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(un.map((t)=>[t.name,pp(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new $o;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new ro((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=lp(he(dp(),"ttheme-find-"));home;catalog;entry;constructor(t,e,n,r){this.home=t,this.catalog=e,this.entry=n,this.tone=jr(n,n.signatureSlots),this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:sa(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Gr(this.setting("TTHEME_FIND_RATING")),block:Lr(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:un.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:n.cursor,selection:n.selection,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=ci(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:lt[this.tab-1]}get sites(){return this.site?[this.site]:lt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??$p}get nextTabName(){let t=(this.tab+1)%(lt.length+1);return t===0?"all":lt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,e,n){return he(ve(t),"orig",`${e}.${n}`)}previewPath(t){return he(ve(t.site),"thumb",`${ga(t.post)}.${An(t.post.preview)}`)}tileOf(t,e){let{site:n,post:r}=t,i=oe(n,r.id),o=Wn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:n===Yr?nh(r.source):r.artist,score:r.score,variants:e,origin:qi(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,e=this.board;t.tiles=e.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),t.checked=e.checked,t.total=e.total,t.searching=e.searching,t.note=e.note,t.focus=Math.max(0,Math.min(e.focus,t.tiles.length-1)),t.top=e.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:e}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),e.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await n;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),e.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),Eo(this.scratch,{recursive:!0,force:!0}),hu(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let e=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(n)=>{clearTimeout(e),this.probeWait=void 0,t(n)},this.write(Eh)})}onData=(t)=>{this.input+=t.toString("utf8");for(let n=uo(this.input);n;n=uo(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let e=uh(this.input);if(this.input=e.pending,this.view.editing===void 0&&e.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(e.keys))this.pasted(e.keys),e.keys="";this.typed+=e.keys;for(let n of e.events)this.inbound(n);if(clearTimeout(this.partial),Op(this.typed)){this.partial=setTimeout(this.flushKeys,vp);return}this.flushKeys()};flushKeys=()=>{let t=kh(this.typed);this.typed="";for(let e of t)this.key(e)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let e=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(e),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let e=this.view;if(e.editing!==void 0&&t.trim()!==""&&!this.picture(t)){e.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(e.installing!==void 0||e.asking!==void 0||e.panel!==void 0||e.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let e=t.trim();if(/^https?:\/\/\S+$/i.test(e))return!Tr(e,this.site??lt[0]);return Vr(e).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${aa}`);return}this.pasted(t.text);return}await this.bring(()=>Xr(t.bytes,t.source))}notice(t,e=Mp){let n=this.view;n.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===t)n.error=void 0,this.draw()},e),this.draw()}async peek(){let t=this.view,e;try{e=await ch()}catch{return}if(!e||e.stamp===this.peeked)return;if(this.peeked=e.stamp,!e.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${Ip} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Sp),this.draw()}async fromClipboard(){let t=this.view;if(no()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let e;try{e=await sh(he(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${hn(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in e){await this.bring(async(r)=>({...await eo(e.image,r),source:"clipboard"}));return}let n=e.text.trim();if(!n){this.notice(`no picture on the clipboard — ${aa}`);return}if(this.picture(n)){await this.attach(n);return}if(t.editing===void 0)t.editing="";this.pasted(n)}async attach(t){let e=t.trim();if(/^https?:\/\//i.test(e)){let i=Tr(e,this.site??lt[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=Vr(e).sort((i,o)=>Number(!ha.test(i))-Number(!ha.test(o)));if(!n){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>eo(n,i),r.length)}async bring(t,e=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)n.note=void 0,this.notice(hn(l),8000);return}if(r.signal.aborted)return;n.note=e>0?`the first picture of ${e+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let o=ih(i.bytes);rh(o,i.source);let s=this.origPath(Yr,o,i.ext);lr(si(s),{recursive:!0}),gr(s,i.bytes);let c=mp(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:pa("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Yr,post:u},a=this.previewPath(h);lr(si(a),{recursive:!0}),gr(a,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=ci(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,h)}single(t,e){t.searching=!1,this.posts.set(oe(e.site,e.post.id),e),t.groups=[{posts:[e],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(e),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>Ee(i)>Ee(r)?i:r),e=Math.ceil((Ee(t)-Date.now())/1000),n=e>0?e:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let e=this.view;if(t==="ctrl-c"){this.finish(2);return}if(e.installing!==void 0)return;if(e.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&e.panel===void 0){this.fromClipboard();return}if(e.editing!==void 0){this.editKey(t);return}if(e.panel!==void 0){this.panelKey(t);return}if(e.help){if(t==="?"||t==="esc")e.help=!1,this.draw();return}if(this.cols<Ke.cols||this.rows<Ke.rows){if(t==="esc")this.finish(2);return}if(t==="?"){e.help=!0,this.draw();return}if(e.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let e=this.view,{perRow:n,rowsVis:r}=De(this.cols,this.rows),o={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-e.focus,end:e.tiles.length}[t];if(o!==void 0){this.focus(e.focus+o);return}if(t==="enter"&&e.tiles[e.focus]){e.mode="try",e.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){e.preset=e.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(lt.length+1),this.syncSite(),this.turn();return}if(t==="/"){e.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){e.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let e=this.view,n=e.panel??0,r=e.settings[n];if(t==="up"||t==="down"){e.panel=Math.max(0,Math.min(e.settings.length-1,n+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){e.settings.forEach((i,o)=>{i.value=this.setting(un[o]?.name??"")}),e.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")e.panel=void 0,this.adopt()}adopt(){let t=this.view,e=un.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=un[i];if(o)this.values.set(o.name,r.value)});let n=un.filter((r,i)=>this.setting(r.name)!==e[i]);if(n.length===0){this.draw();return}this.save(n),t.rating=Gr(this.setting("TTHEME_FIND_RATING")),t.block=Lr(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=sa(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((e)=>[e.name,this.setting(e.name)]))}store(t){let e=he(this.home,"ttheme","config.zsh");try{let n=cn(e)?wa(e,"utf8"):"";return gr(e,t.reduce((r,[i,o])=>Ru(r,i,o),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}askKey(t){let e=this.view;if(t==="y"){if(e.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")e.asking=void 0,this.draw()}editKey(t){let e=this.view,n=e.editing??"",r=e.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=e.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;e.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(e.editing=void 0,e.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=e.pick===void 0?void 0:r[e.pick],o=i?n.replace(/\S*$/,i.value):n;if(e.editing=void 0,e.suggest=void 0,e.pick=void 0,o.trim()){this.commit(o.trim());return}if(e.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){e.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")e.editing=n+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let e=/\S*$/.exec(t.editing??"")?.[0]??"";if(!bp(e)){t.suggest=void 0;return}let n=[...new Map(dh(this.catalog.palettes,this.entry,e).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Np);t.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await du(e,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(n.map((c)=>c.value));t.suggest=[...n.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Hp),t.pick=t.pick!==void 0&&t.pick<n.length?t.pick:void 0,this.draw()}}catch{}},kp)}async commit(t){let e=Tr(t,this.site??lt[0]);if(e){await this.jump(e.site,e.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,e){let n=++this.gen;this.tab=lt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=ci(`${t.key}|post:${e}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await xi(t,e,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${e}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(n,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,e=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(t.focus<e+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=e;for(let i of n.posts)if(!this.thumbPath.has(oe(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}e+=r}}openPage(){let t=this.view.tiles[this.view.focus],e=t&&this.posts.get(t.key);if(!e)return;let n=process.platform==="darwin"?"open":"xdg-open";try{ma(n,[e.site.pageUrl(e.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let e=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(e.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid",e.error=void 0,this.draw()}focus(t){let e=this.view;if(e.tiles.length===0)return;let n=Math.max(0,Math.min(e.tiles.length-1,t));if(n===e.focus)return;if(e.focus=n,this.board.focus=n,this.scroll(),this.pump(),e.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:e,rowsVis:n}=De(this.cols,this.rows),r=Math.floor(t.focus/e);if(r<t.top)t.top=r;if(r>t.top+n-1)t.top=r-n+1;this.board.top=t.top}query(t){let e=this.view,n=e.tag===this.entry.booru?mh(this.entry,t.key):[e.tag];if(n.length===0)return;let r=n.length>1,i=e.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?n.map((h)=>`~${h}`).join(" "):n[0],t.rate(this.view.rating),o?"":i,e.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Zi([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,e=ci(this.boardKey,!0);this.board=e,this.boards.set(e.key,e),this.view.error=void 0;let n=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!n.some((s)=>s.site===o)),i=[...n.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(e.note=i.length>0?i.join(" · "):void 0,n.length===0)e.searching=!1;this.show(),this.draw(),this.tally(t,e,n);try{let o=await Promise.all(n.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;e.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Zi(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,e,n){let r=await Promise.allSettled(n.map(({site:i,tags:o})=>fu(i,o,this.signal)));if(t===this.gen)e.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,e,n=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=yo(n?.name??this.tabName,e),this.board.searching=!1,this.view.error=this.board.error,this.offer(n,e),this.show(),this.draw()}offer(t,e){if(t&&!this.view.unblocked&&$a()&&hn(e)==="ECONNRESET")this.view.asking=t.name}drop(t,e,n){for(let r of t.sources)if(r.site===e)r.done=!0;t.note=[t.note,yo(e.name,n)].filter(Boolean).join(" · "),this.offer(e,n)}wants(){let{perRow:t,rowsVis:e}=De(this.cols,this.rows);return this.view.tiles.length<(this.board.top+e+fa)*t}need(){let{perRow:t,rowsVis:e}=De(this.cols,this.rows);return(e+fa)*t}live(t){return this.boards.get(t.key)===t}page(t,e,n){let r=`${t.key}|${e}|${n}`,i=this.pages.get(r);if(!i)i=au(t,e,n,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let e=t.filter((n)=>n.solo===void 0&&n.md5!=="");if(e.length>0)try{lu(e,await gu(e.map((n)=>n.md5),this.signal))}catch{}return t}async round(t){let e=lt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),n=await Promise.all(e.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of n){if(!u)continue;c.page++,c.done=u.length<Pe;let h=t.last.get(c);for(let a of u){let f=h&&Vh(h.post,a)?h.set:`set:${c.site.key}:${a.id}`;h={post:a,set:f};let l=oe(c.site,a.id);if(t.seen.has(l))continue;t.seen.add(l);let m={site:c.site,post:a};if(this.eligible(m))t.kin.set(m,[f,...Ch(c.site,a)]),r.push(m);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=e.length>1?Rh(i):i;else{let c=ni(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...ni(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let e=t.queue.slice(0,this.need()).filter((n)=>!this.looking.has(oe(n.site,n.post.id)));if(e.length===0)return;this.aheading=!0,this.looks(e).then(()=>{this.aheading=!1;for(let n of new Set(e.map((r)=>t.roundOf.get(r)??0)))this.resort(t,n);this.ahead(t)})}resort(t,e){let n=t.queue.flatMap((i,o)=>t.roundOf.get(i)===e?[o]:[]),r=ni(n.map((i)=>t.queue[i]),this.frame(),this.matched);n.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,e){let n=[];for(let r of e){let i=bo(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);n.push(r);continue}if(t.checked++,la(r.post)<=la(o.post))continue;for(let c of[...i,...bo(o.post)])t.same.set(c,r);let s=n.indexOf(o);if(s>=0){n[s]=r;continue}this.replace(t,o,r)}return n}replace(t,e,n){t.roundOf.set(n,t.roundOf.get(e)??0);let r=t.queue.indexOf(e);if(r>=0){t.queue[r]=n;return}for(let i of t.groups){let o=i.posts.indexOf(e);if(o>=0){i.posts[o]=n,this.posts.set(oe(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(t){let e=0;await Promise.all(Array.from({length:ua},async()=>{while(e<t.length)await this.look(t[e++])}))}look(t){let e=oe(t.site,t.post.id),n=this.looking.get(e);if(!n)n=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(e,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(e,n);return n}async pump(){let t=this.gen,e=this.board;if(this.pumping===t||e.sources.length===0)return;this.pumping=t;let n=[],r;try{e.searching=!0;while(t===this.gen){while(n.length<ca&&e.queue.length>0&&this.wants()){let s=e.queue.shift();n.push({pick:s,passed:this.vet(s)})}if(this.ahead(e),!r&&e.queue.length<ca&&e.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(e).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(e.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)e.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:e}){let n=Wn(e);if(!cu(t,e,this.view.rating)||su(e,this.view.block).length>0||!n)return!1;if(this.view.solo&&e.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(n.ext):e.ext==="png"}async vet(t){let[e]=await Promise.all([this.passes(t),this.look(t)]);return e}async passes({site:t,post:e}){return this.view.preset==="all"||t.vouched||this.transparent(t,e)}probes(t){let e=this.probed.get(t.key);if(!e)e=vo(t,"probes.json"),this.probed.set(t.key,e);return e}async transparent(t,e){let n=this.probes(t),r=n[e.id];if(r!==void 0)return r;try{let i=(await mu(t,e.file,this.signal))?.alpha===!0;return n[e.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let e=lt.find((n)=>n.key===t);if(e)Mo(e,"probes.json",this.probes(e))}this.unsaved.clear()}admit(t){let{site:e,post:n}=t,r=this.board,i=oe(e,n.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,e,n){for(let r of e){let i=t.kindred.get(r);if(i)return i}return n&&t.shapes.find((r)=>zh(r.shape,n))?.group}register(t,e,n,r){for(let i of n)if(!t.kindred.has(i))t.kindred.set(i,e);if(r)t.shapes.push({shape:r,group:e})}async mateOwners(t){let e=this.owners.get(t.key);if(e)return e;let n=_c(this.home),r=vo(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await xi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);Mo(t,"owners.json",r);let c=uu(s);return this.owners.set(t.key,c),c}async cached(t,e,n,r){if(cn(e))return gp(e).size;let i=this.inflight.get(e);if(i)return i;let o=(async()=>{let s=await pu(t,n,this.signal,r);return lr(si(e),{recursive:!0}),gr(e,s),s.length})();this.inflight.set(e,o);try{return await o}finally{this.inflight.delete(e)}}thumbs(){while(this.thumbing<ua&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:e,post:n}=t,r=At.cols*this.cell.w,i=At.rows*this.cell.h,o=he(ve(e),"tile",`${ga(n)}-${r}x${i}.png`);if(!cn(o)){let s=this.previewPath(t);await this.cached(e,s,n.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(oe(e,n.id),o),this.show(),this.draw()}select(){let t=this.view,e=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!e)return;if(this.current?.key===e.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(e),yp),this.draw()}async load(t){let e=this.view,n=this.posts.get(t.key),r=n&&Wn(n.post);if(!n||!r)return;let{site:i}=n,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!cn(c))e.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(f,l)=>{if(e.fetching?.id===t.key)e.fetching={id:t.key,got:f,size:l},this.draw()});if(s.signal.aborted)return;if(e.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};e.preparing=t.key,this.flush();let a=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(a.clear===0&&oo()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(e.preparing=void 0,e.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(e.cutting=void 0,h.cut){e.preparing=t.key,this.flush();let f=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(f&&ph(f.clear))h.using="cut";else Eo(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,e.tiles[e.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)e.error=yo(i.name,c)}finally{if(e.fetching?.id===t.key)e.fetching=void 0;if(e.preparing===t.key)e.preparing=void 0;if(e.cutting===t.key)e.cutting=void 0;this.draw()}}async cutOut(t,e,n,r){let i=he(ve(t),"cut",`${e}.png`);if(cn(i))return i;try{return lr(si(i),{recursive:!0}),await wh(n,i,r),i}catch{Eo(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let e of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Ep)return;let n=t.tiles[e],r=n&&this.posts.get(n.key),i=r&&Wn(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:n.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,e){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,Fp),o=Math.max(1,Math.round(r*i/n)),s=he(this.scratch,`${t.site.key}-${t.id}${e==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${e}`,u=this.clarity.get(c);if(u!==void 0&&cn(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:e==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let e=t.using,{clear:n,path:r}=await this.render(t,e);if(this.current!==t||t.using!==e)return;this.view.shown={id:t.key,clear:n,bytes:t.size,path:r,cut:t.cut?e==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((e)=>{t.error=e instanceof Error?e.message:String(e)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,e=t.tiles[t.focus],n=this.current;if(!e||n?.key!==e.key||t.preparing!==void 0||t.shown?.id!==e.key)return;t.installing=e.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=vo(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",Mo(n.site,"owners.json",r),sn(this.home),t.saved=`background · ${this.entry.name} ← ${n.site.name} ${n.id}`,t.installed.push(e.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=Oh(this.view,this.cols,this.rows),e="\x1B[?2026h";t.lines.forEach((r,i)=>{e+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of t.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)e+=yh(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)e+=vh(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))e+=Mh(r),this.sent.delete(r),this.placed.delete(r);this.write(`${e}\x1B[?2026l`)}}function $a(){if(process.versions.bun)return!0;let[t=0,e=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&e>=21}async function da(){if(!$a())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
142
|
-
`),1;let t=await
|
|
143
|
-
`),0;return s}function
|
|
144
|
-
`),0}if(e==="drop"){let{key:r,left:i}=
|
|
145
|
-
`),0}if(e==="tuned")return
|
|
146
|
-
`),a=!1;for(let f=0;f<h.length;f++){let l=h[f];if(r+=l,!a){if(a=l>="\uD800"&&l<="\uDBFF",a)continue}else a=!1;if(l===
|
|
147
|
-
`){if(o)r+=
|
|
148
|
-
`){if(i&&
|
|
149
|
-
`)}var
|
|
150
|
-
`),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+n)),s=Math.min(s,i[o].length)+e;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var
|
|
140
|
+
`);return}Rp(t,s[1],Number(s[2]),e.subarray(o+4))};t.on("data",n),t.on("error",()=>t.destroy())}function ka(){let t=Ip(Op);return new Promise((e,n)=>{t.once("error",n),t.listen(0,"127.0.0.1",()=>{e({port:t.address().port,close:()=>{t.close(),t.unref()}})})})}var hn=[{name:"TTHEME_FIND_RATING",label:"rating",choices:Kn,multi:{read:Tr}},{name:"TTHEME_FIND_BLOCK",label:"block",choices:Le,multi:{read:Ar,none:"none"}},{name:"TTHEME_FIND_POSTS",label:"posts",choices:["all","cutouts"]},{name:"TTHEME_FIND_SOLO",label:"solo",choices:["on","off"]},{name:"TTHEME_FIND_ORDER",label:"order",choices:["fit","newest","score"]},{name:"TTHEME_FIND_SETS",label:"sets",choices:["fold","show"]},...ao()?[{name:"TTHEME_FIND_REMOVE_BG",label:"remove bg",choices:["on","off"]}]:[]];function Lp(t,e){if(t.multi)return t.multi.read(e).join(" ")||t.multi.none;return t.choices.find((n)=>n===e)??t.choices[0]}var Tp=["fit","newest","score"];function Ea(t){return Tp.find((e)=>e===t)??"fit"}function Ap(t){return t.length>=2&&!/^\d+$/.test(t)&&!t.includes("://")&&!/^[\w.]+:\d+$/.test(t)}var ya=12,Up=4,Kp=150,Ma=12,Jp=2,Wp=150,xp=30,Qp=4000,Zp=8000,va=/\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i,qp=process.platform==="win32"?"alt+v":"ctrl+v",Sa=process.platform==="darwin"?"ctrl+shift+cmd+4 copies a screenshot":"copy a picture first",_p=1280,Ia=2,Cp=3,Xp=8;function hi(t,e){return{key:t,groups:[],sources:[],queue:[],rounds:0,roundOf:new Map,last:new Map,kin:new Map,kindred:new Map,shapes:[],seen:new Set,same:new Map,checked:0,total:0,focus:0,top:0,searching:e}}function an(t){if(!(t instanceof Error))return String(t);if(t instanceof AggregateError&&t.errors[0])return an(t.errors[0]);if(t.cause)return an(t.cause);let e=t.code;if(typeof e==="string")return e;let n=(t.message||t.name).split(".")[0]??"";return n.length>56?`${n.slice(0,55)}…`:n}function Fo(t,e){return`${t}: ${an(e)}`}function Fa(t){return t.width*t.height}function Na(t){return`${t.id}-${Ha("sha1").update(t.preview).digest("hex").slice(0,8)}`}function Vp(t){let e=t.lastIndexOf("\x1B");return e!==-1&&/^\[?[0-9;]*$/.test(t.slice(e+1))}function No(t,e){try{return JSON.parse(ja(he(ve(t),e),"utf8"))}catch{return{}}}function Ro(t,e,n){gr(ve(t),{recursive:!0}),dr(he(ve(t),e),`${JSON.stringify(n)}
|
|
141
|
+
`)}class Pa{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(hn.map((t)=>[t.name,Lp(t,process.env[t.name])]));direction=1;prefetching=0;inflight=new Map;owners=new Map;probed=new Map;unsaved=new Set;thumbQueue=[];thumbing=0;clarity=new Map;renders=new vo;sent=new Map;placed=new Map;current;fetch;settle;partial;suggestTimer;suggesting;input="";typed="";grabber=new uo((t)=>this.write(t),(t)=>void this.got(t));featureWait;noticeTimer;peekTimer;peeked;attaching;probeWait;done;dirty=!1;unblock=!1;scratch=Hp(he(Pp(),"ttheme-find-"));home;catalog;entry;constructor(t,e,n,r){this.home=t,this.catalog=e,this.entry=n,this.tone=Pr(n,n.signatureSlots),this.view={palette:n.name,tag:r,site:this.tabName,siteAnsi:this.tabAnsi,nextSite:this.nextTabName,preset:this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",order:Ea(this.setting("TTHEME_FIND_ORDER")),solo:this.setting("TTHEME_FIND_SOLO")==="on",rating:Tr(this.setting("TTHEME_FIND_RATING")),block:Ar(this.setting("TTHEME_FIND_BLOCK")),sets:this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",unblocked:process.env.TTHEME_FIND_PROXY!==void 0,settings:hn.map((i)=>({label:i.label,choices:[...i.choices],value:this.setting(i.name),multi:i.multi&&{none:i.multi.none},cursor:0})),colors:{cursor:n.cursor,selection:n.selection,ansi:n.ansi},tiles:[],installed:[],checked:0,total:0,searching:r!=="",focus:0,top:0,mode:"grid",help:!1,editing:r===""?"":void 0},this.board=hi(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:lt[this.tab-1]}get sites(){return this.site?[this.site]:lt}get tabName(){return this.site?.name??"all"}get tabAnsi(){return this.site?.ansi??Up}get nextTabName(){let t=(this.tab+1)%(lt.length+1);return t===0?"all":lt[t-1].name}frame(){return{w:this.cols*(this.cell.w||10),h:this.rows*(this.cell.h||20)}}setting(t){return this.values.get(t)}get boardKey(){return`${this.site?.key??"all"}|${this.view.preset}|${this.view.order}`}origPath(t,e,n){return he(ve(t),"orig",`${e}.${n}`)}previewPath(t){return he(ve(t.site),"thumb",`${Na(t.post)}.${Jn(t.post.preview)}`)}tileOf(t,e){let{site:n,post:r}=t,i=oe(n,r.id),o=xn(r)??r;return{id:r.id,key:i,site:n.name,siteAnsi:n.ansi,width:o.width,height:o.height,reduced:o!==r,owner:r.owner,artist:n===Br?wh(r.source):r.artist,score:r.score,variants:e,origin:Vi(r.source),mates:this.owners.get(n.key)?.get(r.owner)??[],thumb:this.thumbPath.get(i)}}show(){let t=this.view,e=this.board;t.tiles=e.groups.flatMap((n)=>n.open?n.posts.map((r)=>this.tileOf(r,0)):[this.tileOf(n.posts[0],n.posts.length)]),t.checked=e.checked,t.total=e.total,t.searching=e.searching,t.note=e.note,t.focus=Math.max(0,Math.min(e.focus,t.tiles.length-1)),t.top=e.top}syncSite(){let t=this.view;t.site=this.tabName,t.siteAnsi=this.tabAnsi,t.nextSite=this.nextTabName}async run(){let{stdin:t,stdout:e}=process;t.setRawMode(!0),t.resume(),t.on("data",this.onData),e.on("resize",this.onResize),this.write("\x1B[?25l\x1B[?7l\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H");let n=new Promise((s)=>{this.done=s}),r=setInterval(this.onClock,250),i=await this.probe();if(i){if(this.cell=i,this.view.tag)this.search()}else this.view.searching=!1,this.view.error="this terminal does not report its cell size — find needs kitty graphics";await this.features(),this.grabber.start(),this.write("\x1B[?1004h"),this.peek(),this.draw();let o=await n;return this.grabber.stop(),this.write("\x1B[?1004l"),this.attaching?.abort(),clearTimeout(this.noticeTimer),clearTimeout(this.peekTimer),this.session.abort(),this.fetch?.abort(),clearTimeout(this.settle),clearTimeout(this.partial),this.quietSuggest(),clearInterval(r),t.off("data",this.onData),e.off("resize",this.onResize),this.write("\x1B_Ga=d,d=A,q=2\x1B\\\x1B[H\x1B[K\x1B[2H\x1B[J\x1B[H"),t.setRawMode(!1),t.pause(),this.saveProbes(),this.renders.close(),Io(this.scratch,{recursive:!0,force:!0}),vu(),o}write(t){process.stdout.write(t)}get saved(){return this.view.saved}finish(t){this.done?.(t===2&&this.saved?0:t)}probe(){return new Promise((t)=>{let e=setTimeout(()=>{this.probeWait=void 0,t(null)},1000);this.probeWait=(n)=>{clearTimeout(e),this.probeWait=void 0,t(n)},this.write(Th)})}onData=(t)=>{this.input+=t.toString("utf8");for(let n=go(this.input);n;n=go(this.input))this.input=n.rest,this.probeWait?.(n.cell);if(this.probeWait)return;let e=Mh(this.input);if(this.input=e.pending,this.view.editing===void 0&&e.keys.length>8&&/^(?:\/|~\/|file:|https?:)/.test(e.keys))this.pasted(e.keys),e.keys="";this.typed+=e.keys;for(let n of e.events)this.inbound(n);if(clearTimeout(this.partial),Vp(this.typed)){this.partial=setTimeout(this.flushKeys,xp);return}this.flushKeys()};flushKeys=()=>{let t=Lh(this.typed);this.typed="";for(let e of t)this.key(e)};features(){if(process.env.TMUX)return Promise.resolve();return new Promise((t)=>{let e=setTimeout(()=>{this.featureWait=void 0,t()},500);this.featureWait=()=>{clearTimeout(e),this.featureWait=void 0,t()},this.write("\x1B[?5522$p\x1B]72;t=q\x1B\\\x1B[c")})}inbound(t){if(t.kind==="mode"){if(t.mode===5522)this.grabber.clipboard=t.value!==0&&t.value!==4;return}if(t.kind==="attributes"){this.featureWait?.();return}if(t.kind==="osc"){if(t.code==="72"&&t.meta.t==="q"){this.grabber.drops=!0;return}this.grabber.take(t);return}this.pasted(t.text)}pasted(t){let e=this.view;if(e.editing!==void 0&&t.trim()!==""&&!this.picture(t)){e.editing+=t.replace(/[\r\n]+/g," "),this.suggest(),this.draw();return}if(e.installing!==void 0||e.asking!==void 0||e.panel!==void 0||e.help)return;if(t.trim()===""){this.fromClipboard();return}this.attach(t)}picture(t){let e=t.trim();if(/^https?:\/\/\S+$/i.test(e))return!Ur(e,this.site??lt[0]);return zr(e).length>0}async got(t){if(t.kind==="error"){this.notice(t.message);return}if(t.kind==="text"){if(t.text.trim()===""){this.notice(`no picture on the clipboard — ${Sa}`);return}this.pasted(t.text);return}await this.bring(()=>Vr(t.bytes,t.source))}notice(t,e=Qp){let n=this.view;n.error=t,clearTimeout(this.noticeTimer),this.noticeTimer=setTimeout(()=>{if(n.error===t)n.error=void 0,this.draw()},e),this.draw()}async peek(){let t=this.view,e;try{e=await yh()}catch{return}if(!e||e.stamp===this.peeked)return;if(this.peeked=e.stamp,!e.picture||t.installing!==void 0||t.asking!==void 0)return;t.hint=`picture on the clipboard · ${qp} uses it`,clearTimeout(this.peekTimer),this.peekTimer=setTimeout(()=>{t.hint=void 0,this.draw()},Zp),this.draw()}async fromClipboard(){let t=this.view;if(co()){if(this.grabber.clipboard){this.grabber.ask();return}this.notice("over ssh the clipboard is not here — drop the file");return}let e;try{e=await Eh(he(this.scratch,`clipboard-${Date.now()}.png`))}catch(r){this.notice(`could not read the clipboard: ${an(r)}`);return}if(clearTimeout(this.peekTimer),t.hint=void 0,"image"in e){await this.bring(async(r)=>({...await so(e.image,r),source:"clipboard"}));return}let n=e.text.trim();if(!n){this.notice(`no picture on the clipboard — ${Sa}`);return}if(this.picture(n)){await this.attach(n);return}if(t.editing===void 0)t.editing="";this.pasted(n)}async attach(t){let e=t.trim();if(/^https?:\/\//i.test(e)){let i=Ur(e,this.site??lt[0]);if(i){await this.jump(i.site,i.id);return}}let[n,...r]=zr(e).sort((i,o)=>Number(!va.test(i))-Number(!va.test(o)));if(!n){this.notice("nothing to use in that — drop a picture, or paste one or its link");return}await this.bring((i)=>so(n,i),r.length)}async bring(t,e=0){let n=this.view;this.attaching?.abort();let r=new AbortController;this.attaching=r,n.error=void 0,n.saved=void 0,n.note="reading the picture…",this.draw();let i;try{i=await t(AbortSignal.any([r.signal,this.signal]))}catch(l){if(!r.signal.aborted)n.note=void 0,this.notice(an(l),8000);return}if(r.signal.aborted)return;n.note=e>0?`the first picture of ${e+1} — drop one at a time to try the others`:void 0,this.quietSuggest(),n.editing=void 0,n.suggest=void 0,n.pick=void 0;let o=$h(i.bytes);bh(o,i.source);let s=this.origPath(Br,o,i.ext);gr(ui(s),{recursive:!0}),dr(s,i.bytes);let c=Gp(s).href,u={id:o,file:c,width:i.width,height:i.height,ext:i.ext,preview:c,owner:"",artist:"",score:0,rating:"s",md5:Ha("md5").update(i.bytes).digest("hex"),source:i.source,tags:[],solo:void 0,family:0,smaller:[]},h={site:Br,post:u},a=this.previewPath(h);gr(ui(a),{recursive:!0}),dr(a,i.bytes),++this.gen,this.current=void 0,n.shown=void 0;let f=hi(`local|post:${o}`,!1);this.board=f,this.boards.set(f.key,f),this.single(f,h)}single(t,e){t.searching=!1,this.posts.set(oe(e.site,e.post.id),e),t.groups=[{posts:[e],open:!1}],t.checked=1,t.total=1,this.thumbQueue.push(e),this.thumbs(),this.view.mode="try",this.show(),this.select(),this.draw()}onClock=()=>{let t=this.sites.reduce((r,i)=>ye(i)>ye(r)?i:r),e=Math.ceil((ye(t)-Date.now())/1000),n=e>0?e:void 0;if(n!==this.view.waiting)this.view.waiting=n,this.view.slow=t.name,this.draw()};onResize=()=>{if(this.cols=process.stdout.columns||this.cols,this.rows=process.stdout.rows||this.rows,this.scroll(),this.view.mode==="try"&&this.current)this.reveal();this.pump(),this.draw()};key(t){let e=this.view;if(t==="ctrl-c"){this.finish(2);return}if(e.installing!==void 0)return;if(e.asking!==void 0){this.askKey(t);return}if(t==="focus-in"){this.peek();return}if(t==="focus-out"||t==="nop")return;if((t==="ctrl-v"||t==="alt-v")&&e.panel===void 0){this.fromClipboard();return}if(e.editing!==void 0){this.editKey(t);return}if(e.panel!==void 0){this.panelKey(t);return}if(e.help){if(t==="?"||t==="esc")e.help=!1,this.draw();return}if(this.cols<Ke.cols||this.rows<Ke.rows){if(t==="esc")this.finish(2);return}if(t==="?"){e.help=!0,this.draw();return}if(e.mode==="try"){this.tryKey(t);return}this.gridKey(t)}gridKey(t){let e=this.view,{perRow:n,rowsVis:r}=tn(this.cols,this.rows),o={left:-1,right:1,up:-n,down:n,pgup:-n*r,pgdn:n*r,home:-e.focus,end:e.tiles.length}[t];if(o!==void 0){this.focus(e.focus+o);return}if(t==="enter"&&e.tiles[e.focus]){e.mode="try",e.error=void 0,this.select();return}if(t==="v"){this.fromClipboard();return}if(t==="c"){e.preset=e.preset==="cutouts"?"all":"cutouts",this.turn();return}if(t==="tab"){this.tab=(this.tab+1)%(lt.length+1),this.syncSite(),this.turn();return}if(t==="/"){e.editing="",this.draw();return}if(t===" "){this.unfold();return}if(t==="o"){this.openPage();return}if(t==="s"){e.panel=0,this.draw();return}if(t==="esc")this.finish(2)}panelKey(t){let e=this.view,n=e.panel??0,r=e.settings[n];if(t==="up"||t==="down"){e.panel=Math.max(0,Math.min(e.settings.length-1,n+(t==="up"?-1:1))),this.draw();return}if((t==="left"||t==="right")&&r){let i=t==="left"?-1:1;if(r.multi)r.cursor=(r.cursor+i+r.choices.length)%r.choices.length;else{let o=r.choices.indexOf(r.value);r.value=r.choices[(o+i+r.choices.length)%r.choices.length]}this.draw();return}if(t===" "&&r?.multi){let i=r.value.split(" "),o=r.choices.filter((c,u)=>u===r.cursor?!i.includes(c):i.includes(c)),s=r.multi.none;if(o.length>0||s!==void 0)r.value=o.length>0?o.join(" "):s,this.draw();return}if(t==="esc"){e.settings.forEach((i,o)=>{i.value=this.setting(hn[o]?.name??"")}),e.panel=void 0,this.draw();return}if(t==="enter"||t==="alt-c")e.panel=void 0,this.adopt()}adopt(){let t=this.view,e=hn.map((r)=>this.setting(r.name));t.settings.forEach((r,i)=>{let o=hn[i];if(o)this.values.set(o.name,r.value)});let n=hn.filter((r,i)=>this.setting(r.name)!==e[i]);if(n.length===0){this.draw();return}this.save(n),t.rating=Tr(this.setting("TTHEME_FIND_RATING")),t.block=Ar(this.setting("TTHEME_FIND_BLOCK")),t.sets=this.setting("TTHEME_FIND_SETS")==="show"?"show":"fold",t.preset=this.setting("TTHEME_FIND_POSTS")==="all"?"all":"cutouts",t.order=Ea(this.setting("TTHEME_FIND_ORDER")),t.solo=this.setting("TTHEME_FIND_SOLO")==="on",this.boards.clear(),this.current=void 0,t.shown=void 0,t.mode="grid",this.search()}save(t){this.store(t.map((e)=>[e.name,this.setting(e.name)]))}store(t){let e=he(this.home,"ttheme","config.zsh");try{let n=un(e)?ja(e,"utf8"):"";return dr(e,t.reduce((r,[i,o])=>Cu(r,i,o),n)),!0}catch(n){return this.view.error=n instanceof Error?n.message:String(n),!1}}askKey(t){let e=this.view;if(t==="y"){if(e.asking=void 0,this.store([["TTHEME_FIND_UNBLOCK","1"]])){this.unblock=!0,this.finish(0);return}this.draw();return}if(t==="n"||t==="esc")e.asking=void 0,this.draw()}editKey(t){let e=this.view,n=e.editing??"",r=e.suggest??[];if((t==="up"||t==="down")&&r.length>0){let i=e.pick??-1,o=t==="down"?Math.min(r.length-1,i+1):i-1;e.pick=o<0?void 0:o,this.draw();return}if(t==="esc"||t==="enter")this.quietSuggest();if(t==="esc"){if(e.editing=void 0,e.tag===""){this.finish(2);return}this.draw();return}if(t==="enter"){let i=e.pick===void 0?void 0:r[e.pick],o=i?n.replace(/\S*$/,i.value):n;if(e.editing=void 0,e.suggest=void 0,e.pick=void 0,o.trim()){this.commit(o.trim());return}if(e.tag===""){this.finish(2);return}this.draw();return}if(t==="backspace"){e.editing=n.slice(0,-1),this.suggest(),this.draw();return}if(t.length===1&&t>=" ")e.editing=n+t,this.suggest(),this.draw()}quietSuggest(){clearTimeout(this.suggestTimer),this.suggesting?.abort(),this.suggesting=void 0}suggest(){this.quietSuggest();let t=this.view;t.pick=void 0;let e=/\S*$/.exec(t.editing??"")?.[0]??"";if(!Ap(e)){t.suggest=void 0;return}let n=[...new Map(Rh(this.catalog.palettes,this.entry,e).map((i)=>[i.booru,{value:i.booru,count:0,palette:i.name}])).values()].slice(0,Cp);t.suggest=n.length>0?n:void 0;let r=new AbortController;this.suggesting=r,this.suggestTimer=setTimeout(async()=>{try{let i=await Ru(e,AbortSignal.any([this.signal,r.signal]));if(this.suggesting===r&&t.editing!==void 0){let o=new Map(i.map((c)=>[c.value,c.count])),s=new Set(n.map((c)=>c.value));t.suggest=[...n.map((c)=>({...c,count:o.get(c.value)??0})),...i.filter((c)=>!s.has(c.value))].slice(0,Xp),t.pick=t.pick!==void 0&&t.pick<n.length?t.pick:void 0,this.draw()}}catch{}},Kp)}async commit(t){let e=Ur(t,this.site??lt[0]);if(e){await this.jump(e.site,e.id);return}if(this.picture(t)){await this.attach(t);return}this.view.tag=t,this.boards.clear(),await this.search()}async jump(t,e){let n=++this.gen;this.tab=lt.indexOf(t)+1,this.syncSite(),this.current=void 0,this.view.shown=void 0,this.view.error=void 0;let r=hi(`${t.key}|post:${e}`,!0);this.board=r,this.boards.set(r.key,r),this.show(),this.draw();try{let i=await Yi(t,e,this.signal);if(n!==this.gen)return;if(!i){r.searching=!1,r.error=`${t.name} has no post ${e}`,this.view.error=r.error,this.show(),this.draw();return}this.single(r,{site:t,post:i})}catch(i){this.fail(n,i,t)}}async turn(){this.fetch?.abort(),this.current=void 0,this.view.shown=void 0;let t=this.boards.get(this.boardKey);if(!t){await this.search();return}this.gen++,this.board=t,this.view.error=t.error,this.show(),this.draw(),await this.pump()}unfold(){let t=this.view,e=0;for(let n of this.board.groups){let r=n.open?n.posts.length:1;if(t.focus<e+r){if(n.posts.length<2)return;n.open=!n.open,this.board.focus=e;for(let i of n.posts)if(!this.thumbPath.has(oe(i.site,i.post.id)))this.thumbQueue.push(i);this.thumbs(),this.show(),this.scroll(),this.draw();return}e+=r}}openPage(){let t=this.view.tiles[this.view.focus],e=t&&this.posts.get(t.key);if(!e)return;let n=process.platform==="darwin"?"open":"xdg-open";try{Oa(n,[e.site.pageUrl(e.post.id)],{stdio:"ignore",detached:!0}).unref()}catch{}}tryKey(t){let e=this.view;if(t==="left"||t==="right"){this.direction=t==="left"?-1:1,this.focus(e.focus+this.direction);return}if(t==="o"){this.openPage();return}if(t==="x"){this.swap();return}if(t==="v"){this.fromClipboard();return}if(t==="enter"){this.install();return}if(t==="esc")this.fetch?.abort(),clearTimeout(this.settle),e.fetching=void 0,e.mode="grid",e.error=void 0,this.draw()}focus(t){let e=this.view;if(e.tiles.length===0)return;let n=Math.max(0,Math.min(e.tiles.length-1,t));if(n===e.focus)return;if(e.focus=n,this.board.focus=n,this.scroll(),this.pump(),e.mode==="try")this.select();this.draw()}scroll(){let t=this.view,{perRow:e,rowsVis:n}=tn(this.cols,this.rows),r=Math.floor(t.focus/e);if(r<t.top)t.top=r;if(r>t.top+n-1)t.top=r-n+1;this.board.top=t.top}query(t){let e=this.view,n=e.tag===this.entry.booru?Oh(this.entry,t.key):[e.tag];if(n.length===0)return;let r=n.length>1,i=e.preset==="cutouts"?t.cutouts:"",o=r&&i.includes("~"),s=[r?n.map((h)=>`~${h}`).join(" "):n[0],t.rate(this.view.rating),o?"":i,e.order==="score"?t.best:""].filter(Boolean),c=[],u=[];for(let h of s)if(Xi([...c,h].join(" "))<=t.tagBudget)c.push(h);else u.push(h);return{tags:c.join(" "),notes:[...u.length>0?[`${t.name} takes ${t.tagBudget} tags — ${u.join(" ")} left out`]:[],...o?[`${t.name} ORs the names, so cutouts are told by the file`]:[]]}}async search(){let t=++this.gen,e=hi(this.boardKey,!0);this.board=e,this.boards.set(e.key,e),this.view.error=void 0;let n=this.sites.flatMap((o)=>{let s=this.query(o);return s?[{site:o,...s}]:[]}),r=this.sites.filter((o)=>!n.some((s)=>s.site===o)),i=[...n.flatMap(({notes:o})=>o),...r.length>0?[`${this.entry.name} has no tag on ${r.map((o)=>o.name).join(", ")}`]:[]];if(e.note=i.length>0?i.join(" · "):void 0,n.length===0)e.searching=!1;this.show(),this.draw(),this.tally(t,e,n);try{let o=await Promise.all(n.map(async(s)=>({plan:s,owners:await this.mateOwners(s.site)})));if(t!==this.gen)return;e.sources=o.flatMap(({plan:{site:s,tags:c},owners:u})=>[...Xi(c)+1<=s.tagBudget?[...u.keys()].map((h)=>({site:s,tags:`${c} user:${h}`,page:0,done:!1})):[],{site:s,tags:c,page:0,done:!1}]),this.show(),this.draw(),await this.pump()}catch(o){this.fail(t,o)}}async tally(t,e,n){let r=await Promise.allSettled(n.map(({site:i,tags:o})=>Iu(i,o,this.signal)));if(t===this.gen)e.total=r.reduce((i,o)=>i+(o.status==="fulfilled"?o.value:0),0),this.show(),this.draw()}fail(t,e,n=this.site){if(t!==this.gen||this.signal.aborted)return;this.board.error=Fo(n?.name??this.tabName,e),this.board.searching=!1,this.view.error=this.board.error,this.offer(n,e),this.show(),this.draw()}offer(t,e){if(t&&!this.view.unblocked&&Ga()&&an(e)==="ECONNRESET")this.view.asking=t.name}drop(t,e,n){for(let r of t.sources)if(r.site===e)r.done=!0;t.note=[t.note,Fo(e.name,n)].filter(Boolean).join(" · "),this.offer(e,n)}wants(){let{perRow:t,rowsVis:e}=tn(this.cols,this.rows);return this.view.tiles.length<(this.board.top+e+Ia)*t}need(){let{perRow:t,rowsVis:e}=tn(this.cols,this.rows);return(e+Ia)*t}live(t){return this.boards.get(t.key)===t}page(t,e,n){let r=`${t.key}|${e}|${n}`,i=this.pages.get(r);if(!i)i=Su(t,e,n,this.signal).then((o)=>this.borrow(o)),this.pages.set(r,i),i.catch(()=>this.pages.delete(r));return i}async borrow(t){let e=t.filter((n)=>n.solo===void 0&&n.md5!=="");if(e.length>0)try{Fu(e,await Nu(e.map((n)=>n.md5),this.signal))}catch{}return t}async round(t){let e=lt.flatMap((c)=>{let u=t.sources.find((h)=>h.site===c&&!h.done);return u?[u]:[]}),n=await Promise.all(e.map(async(c)=>{try{return{source:c,posts:await this.page(c.site,c.tags,c.page)}}catch(u){if(t.sources.every((h)=>h.site===c.site)||this.signal.aborted)throw u;return this.drop(t,c.site,u),{source:c,posts:void 0}}}));if(!this.live(t))return;let r=[];for(let{source:c,posts:u}of n){if(!u)continue;c.page++,c.done=u.length<Ge;let h=t.last.get(c);for(let a of u){let f=h&&aa(h.post,a)?h.set:`set:${c.site.key}:${a.id}`;h={post:a,set:f};let l=oe(c.site,a.id);if(t.seen.has(l))continue;t.seen.add(l);let m={site:c.site,post:a};if(this.eligible(m))t.kin.set(m,[f,...ha(c.site,a)]),r.push(m);else t.checked++}if(h)t.last.set(c,h)}let i=this.dedupe(t,r),o=++t.rounds,s;if(this.view.order!=="fit")s=e.length>1?Ch(i):i;else{let c=ii(i,this.frame(),this.matched),u=c.slice(0,this.need());if(await this.looks(u),!this.live(t))return;s=[...ii(u,this.frame(),this.matched),...c.slice(u.length)]}for(let c of s)t.roundOf.set(c,o);t.queue.push(...s),this.ahead(t)}ahead(t){if(this.aheading||this.view.order!=="fit"||!this.live(t))return;let e=t.queue.slice(0,this.need()).filter((n)=>!this.looking.has(oe(n.site,n.post.id)));if(e.length===0)return;this.aheading=!0,this.looks(e).then(()=>{this.aheading=!1;for(let n of new Set(e.map((r)=>t.roundOf.get(r)??0)))this.resort(t,n);this.ahead(t)})}resort(t,e){let n=t.queue.flatMap((i,o)=>t.roundOf.get(i)===e?[o]:[]),r=ii(n.map((i)=>t.queue[i]),this.frame(),this.matched);n.forEach((i,o)=>{t.queue[i]=r[o]})}dedupe(t,e){let n=[];for(let r of e){let i=Mo(r.post),o=i.map((c)=>t.same.get(c)).find(Boolean);if(!o){for(let c of i)t.same.set(c,r);n.push(r);continue}if(t.checked++,Fa(r.post)<=Fa(o.post))continue;for(let c of[...i,...Mo(o.post)])t.same.set(c,r);let s=n.indexOf(o);if(s>=0){n[s]=r;continue}this.replace(t,o,r)}return n}replace(t,e,n){t.roundOf.set(n,t.roundOf.get(e)??0);let r=t.queue.indexOf(e);if(r>=0){t.queue[r]=n;return}for(let i of t.groups){let o=i.posts.indexOf(e);if(o>=0){i.posts[o]=n,this.posts.set(oe(n.site,n.post.id),n),this.thumbQueue.push(n),this.thumbs();return}}}async looks(t){let e=0;await Promise.all(Array.from({length:Ma},async()=>{while(e<t.length)await this.look(t[e++])}))}look(t){let e=oe(t.site,t.post.id),n=this.looking.get(e);if(!n)n=(async()=>{let r=this.previewPath(t);await this.cached(t.site,r,t.post.preview);let i=await this.renders.run({job:"match",from:r,colors:this.entry.signature});return this.looked.set(e,i),this.matched.set(t.post,i.match),i})().catch(()=>{return}),this.looking.set(e,n);return n}async pump(){let t=this.gen,e=this.board;if(this.pumping===t||e.sources.length===0)return;this.pumping=t;let n=[],r;try{e.searching=!0;while(t===this.gen){while(n.length<ya&&e.queue.length>0&&this.wants()){let s=e.queue.shift();n.push({pick:s,passed:this.vet(s)})}if(this.ahead(e),!r&&e.queue.length<ya&&e.sources.some((s)=>!s.done)&&this.wants()){let s=this.round(e).then(()=>{if(r===s)r=void 0});s.catch(()=>{}),r=s}let i=n.shift();if(!i){if(!r)break;await r,this.show(),this.draw();continue}let o=await i.passed;if(t!==this.gen)return;if(e.checked++,o)this.admit(i.pick);this.show(),this.draw()}if(t===this.gen)e.searching=!1,this.show(),this.draw()}catch(i){this.fail(t,i)}finally{if(this.saveProbes(),this.pumping===t)this.pumping=0}}eligible({site:t,post:e}){let n=xn(e);if(!yu(t,e,this.view.rating)||Eu(e,this.view.block).length>0||!n)return!1;if(this.view.solo&&e.solo===!1)return!1;return this.view.preset==="all"?["png","jpg","jpeg"].includes(n.ext):e.ext==="png"}async vet(t){let[e]=await Promise.all([this.passes(t),this.look(t)]);return e}async passes({site:t,post:e}){return this.view.preset==="all"||t.vouched||this.transparent(t,e)}probes(t){let e=this.probed.get(t.key);if(!e)e=No(t,"probes.json"),this.probed.set(t.key,e);return e}async transparent(t,e){let n=this.probes(t),r=n[e.id];if(r!==void 0)return r;try{let i=(await Ou(t,e.file,this.signal))?.alpha===!0;return n[e.id]=i,this.unsaved.add(t.key),i}catch{return!1}}saveProbes(){for(let t of this.unsaved){let e=lt.find((n)=>n.key===t);if(e)Ro(e,"probes.json",this.probes(e))}this.unsaved.clear()}admit(t){let{site:e,post:n}=t,r=this.board,i=oe(e,n.id);this.posts.set(i,t);let o=r.kin.get(t)??[],s=this.looked.get(i),c=s&&{hash:s.hash,width:n.width,height:n.height},u=this.view.sets==="fold"?this.kindred(r,o,c):void 0;if(u){if(u.posts.push(t),this.register(r,u,o,c),u.open)this.thumbQueue.push(t),this.thumbs();return}let h={posts:[t],open:!1};r.groups.push(h),this.register(r,h,o,c),this.thumbQueue.push(t),this.thumbs()}kindred(t,e,n){for(let r of e){let i=t.kindred.get(r);if(i)return i}return n&&t.shapes.find((r)=>la(r.shape,n))?.group}register(t,e,n,r){for(let i of n)if(!t.kindred.has(i))t.kindred.set(i,e);if(r)t.shapes.push({shape:r,group:e})}async mateOwners(t){let e=this.owners.get(t.key);if(e)return e;let n=cu(this.home),r=No(t,"owners.json"),i=this.catalog.palettes.flatMap((u)=>{let h=n.get(u.name);return u.group===this.entry.group&&u.name!==this.entry.name&&h?.site===t.key?[{name:u.name,id:h.id}]:[]}),o=await Promise.all(i.map(async(u)=>{let h=r[u.id];if(h!==void 0)return{...u,owner:h};try{return{...u,owner:(await Yi(t,u.id,this.signal))?.owner??""}}catch{return}})),s=new Map;for(let u of o)if(u)r[u.id]=u.owner,s.set(u.name,u.owner);Ro(t,"owners.json",r);let c=Mu(s);return this.owners.set(t.key,c),c}async cached(t,e,n,r){if(un(e))return jp(e).size;let i=this.inflight.get(e);if(i)return i;let o=(async()=>{let s=await Hu(t,n,this.signal,r);return gr(ui(e),{recursive:!0}),dr(e,s),s.length})();this.inflight.set(e,o);try{return await o}finally{this.inflight.delete(e)}}thumbs(){while(this.thumbing<Ma&&this.thumbQueue.length>0){let t=this.thumbQueue.shift();this.thumbing++,this.thumb(t).catch(()=>{}).finally(()=>{this.thumbing--,this.thumbs()})}}async thumb(t){let{site:e,post:n}=t,r=Kt.cols*this.cell.w,i=Kt.rows*this.cell.h,o=he(ve(e),"tile",`${Na(n)}-${r}x${i}.png`);if(!un(o)){let s=this.previewPath(t);await this.cached(e,s,n.preview),await this.renders.run({job:"thumb",from:s,to:o,width:r,height:i})}this.thumbPath.set(oe(e,n.id),o),this.show(),this.draw()}select(){let t=this.view,e=t.tiles[t.focus];if(this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,!e)return;if(this.current?.key===e.key){this.reveal();return}this.settle=setTimeout(()=>void this.load(e),Wp),this.draw()}async load(t){let e=this.view,n=this.posts.get(t.key),r=n&&xn(n.post);if(!n||!r)return;let{site:i}=n,o=this.board,s=new AbortController;this.fetch=s;try{let c=this.origPath(i,t.id,r.ext);if(!un(c))e.fetching={id:t.key,got:0,size:0},this.draw();let u=await this.cached(i,c,r.file,(f,l)=>{if(e.fetching?.id===t.key)e.fetching={id:t.key,got:f,size:l},this.draw()});if(s.signal.aborted)return;if(e.fetching=void 0,o!==this.board)return;let h={site:i,id:t.id,key:t.key,path:c,ext:r.ext,size:u,using:"plain",failed:!1};e.preparing=t.key,this.flush();let a=await this.render(h,"plain");if(s.signal.aborted||o!==this.board)return;if(a.clear===0&&ao()&&this.setting("TTHEME_FIND_REMOVE_BG")!=="off"){if(e.preparing=void 0,e.cutting=t.key,this.flush(),h.cut=await this.cutOut(i,t.id,c,s.signal),s.signal.aborted||o!==this.board)return;if(e.cutting=void 0,h.cut){e.preparing=t.key,this.flush();let f=await this.render(h,"cut").catch(()=>{return});if(s.signal.aborted||o!==this.board)return;if(f&&Hh(f.clear))h.using="cut";else Io(h.cut,{force:!0}),h.cut=void 0,h.failed=!0}else h.failed=!0}if(this.current=h,e.tiles[e.focus]?.key===t.key)await this.present();this.preload()}catch(c){if(!s.signal.aborted&&!this.signal.aborted)e.error=Fo(i.name,c)}finally{if(e.fetching?.id===t.key)e.fetching=void 0;if(e.preparing===t.key)e.preparing=void 0;if(e.cutting===t.key)e.cutting=void 0;this.draw()}}async cutOut(t,e,n,r){let i=he(ve(t),"cut",`${e}.png`);if(un(i))return i;try{return gr(ui(i),{recursive:!0}),await jh(n,i,r),i}catch{Io(i,{force:!0});return}}swap(){let t=this.current;if(!t?.cut||this.view.shown?.id!==t.key)return;t.using=t.using==="cut"?"plain":"cut",this.reveal()}preload(){let t=this.view;if(t.mode!=="try")return;for(let e of[t.focus+this.direction,t.focus-this.direction]){if(this.prefetching>=Jp)return;let n=t.tiles[e],r=n&&this.posts.get(n.key),i=r&&xn(r.post);if(!r||!i)continue;let{site:o,post:s}=r,c=this.origPath(o,s.id,i.ext);this.prefetching++,this.cached(o,c,i.file).then(()=>this.render({site:o,id:s.id,key:n.key,path:c,ext:i.ext,size:0,using:"plain",failed:!1},"plain")).catch(()=>{}).finally(()=>{this.prefetching--})}}async render(t,e){let n=this.cols*this.cell.w,r=this.rows*this.cell.h,i=Math.min(n,_p),o=Math.max(1,Math.round(r*i/n)),s=he(this.scratch,`${t.site.key}-${t.id}${e==="cut"?"c":""}-${i}x${o}.png`),c=`${t.site.key}:${t.id}:${e}`,u=this.clarity.get(c);if(u!==void 0&&un(s))return{clear:u,path:s};let h=await this.renders.run({job:"show",from:e==="cut"?t.cut:t.path,to:s,width:i,height:o,colors:this.entry,tone:this.tone});return this.clarity.set(c,h),{clear:h,path:s}}async present(){let t=this.current;if(!t)return;let e=t.using,{clear:n,path:r}=await this.render(t,e);if(this.current!==t||t.using!==e)return;this.view.shown={id:t.key,clear:n,bytes:t.size,path:r,cut:t.cut?e==="cut"?"on":"off":t.failed?"failed":"none"}}reveal(){let t=this.view;t.preparing=this.current?.key,this.flush(),this.present().catch((e)=>{t.error=e instanceof Error?e.message:String(e)}).finally(()=>{if(t.preparing===this.current?.key)t.preparing=void 0;this.draw()})}async install(){let t=this.view,e=t.tiles[t.focus],n=this.current;if(!e||n?.key!==e.key||t.preparing!==void 0||t.shown?.id!==e.key)return;t.installing=e.key,t.error=void 0,this.flush();try{await this.renders.run({job:"backdrop",from:n.using==="cut"?n.cut:n.path,source:n.path,home:this.home,colors:this.entry,tone:this.tone,origin:{site:n.site.key,id:n.id,ext:n.ext,from:`${n.site.name} ${n.id} ${n.site.pageUrl(n.id)}`},width:this.cols*this.cell.w,height:this.rows*this.cell.h});let r=No(n.site,"owners.json");r[n.id]=this.posts.get(n.key)?.post.owner??"",Ro(n.site,"owners.json",r),cn(this.home),t.saved=`background · ${this.entry.name} ← ${n.site.name} ${n.id}`,t.installed.push(e.key),this.fetch?.abort(),clearTimeout(this.settle),t.fetching=void 0,t.mode="grid"}catch(r){t.error=r instanceof Error?r.message:String(r)}t.installing=void 0,this.draw()}draw(){if(this.dirty)return;this.dirty=!0,setImmediate(()=>{this.dirty=!1,this.flush()})}flush(){let t=qh(this.view,this.cols,this.rows),e="\x1B[?2026h";t.lines.forEach((r,i)=>{e+=`\x1B[${i+1};1H\x1B[K${r}`});let n=new Set;for(let r of t.images){if(n.add(r.id),this.sent.get(r.id)!==r.path)e+=Ah(r),this.sent.set(r.id,r.path),this.placed.delete(r.id);let i=`${r.row};${r.col};${r.cols};${r.rows};${r.z}`;if(this.placed.get(r.id)!==i)e+=Uh(r),this.placed.set(r.id,i)}for(let r of this.sent.keys())if(!n.has(r))e+=Kh(r),this.sent.delete(r),this.placed.delete(r);this.write(`${e}\x1B[?2026l`)}}function Ga(){if(process.versions.bun)return!0;let[t=0,e=0]=process.versions.node.split(".").map(Number);return t>22||t===22&&e>=21}async function Ra(){if(!Ga())return process.stderr.write(`unblock needs node 22.21 or newer — this is ${process.versions.node}
|
|
142
|
+
`),1;let t=await ka(),e=Oa(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,NODE_USE_ENV_PROXY:"1",NODE_NO_WARNINGS:"1",HTTPS_PROXY:`http://127.0.0.1:${t.port}`,NO_PROXY:[process.env.NO_PROXY,ku()].filter(Boolean).join(","),TTHEME_FIND_PROXY:String(t.port)}}),n=await new Promise((r)=>e.on("exit",(i)=>r(i??1)));return t.close(),n}async function La(t){if(process.env.TTHEME_FIND_UNBLOCK==="1"&&!process.env.TTHEME_FIND_PROXY)return Ra();let e=Pt(),n=At(e),r=ei(n.palettes,t);if(!process.stdin.isTTY||!process.stdout.isTTY)throw Error("needs a terminal");let i=new Pa(e,n,r,r.booru??""),o=await i.run(),s=i.unblock?await Ra():o;if(i.saved&&s!==0)return process.stderr.write(`${i.saved}
|
|
143
|
+
`),0;return s}function Ta(t,e){let n=Pt();if(ei(At(n).palettes,t),e==="next"||e==="prev"){let{key:r,at:i,of:o}=iu(n,t,e==="next"?1:-1);return cn(n),process.stderr.write(`background · ${t} ${i}/${o} ${r}
|
|
144
|
+
`),0}if(e==="drop"){let{key:r,left:i}=ou(n,t);return cn(n),process.stderr.write(`background · ${t} removed ${r??"the picture"} · ${i} left
|
|
145
|
+
`),0}if(e==="tuned")return cn(n),0;throw Error(`unknown image action ${e} — next, prev, drop or tuned`)}import{execFileSync as Y0,spawnSync as z0}from"node:child_process";import{chmodSync as B0,copyFileSync as D0,existsSync as Zt,mkdirSync as Xo,readdirSync as tw,readFileSync as bn,rmSync as Af,writeFileSync as ew}from"node:fs";import{homedir as nw}from"node:os";import{dirname as wn,join as $t}from"node:path";import{styleText as To}from"node:util";import{stdout as tf,stdin as f0}from"node:process";import l0 from"node:readline";var Aa=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),Ua=(t)=>{return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510},Ka=(t)=>{return t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141};var Yp=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,zp=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ja=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Bp=/\t{1,1000}/y,Wa=/[\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,Dp=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,t0=/\p{M}+/gu,e0={limit:1/0,ellipsis:""},xa=(t,e={},n={})=>{let r=e.limit??1/0,i=e.ellipsis??"",o=e?.ellipsisWidth??(i?xa(i,e0,n).width:0),s=0,c=n.controlWidth??0,u=n.tabWidth??8,h=n.emojiWidth??2,a=2,f=n.regularWidth??1,l=n.wideWidth??2,m=[[Dp,f],[Yp,0],[zp,c],[Bp,u],[Wa,h],[Ja,l]],b=0,g=0,$=t.length,y=0,F=!1,E=$,v=Math.max(0,r-o),p=0,j=0,k=0,H=0;t:while(!0){if(j>p||g>=$&&g>b){let R=t.slice(p,j)||t.slice(b,g);y=0;for(let L of R.replaceAll(t0,"")){let P=L.codePointAt(0)||0;if(Ua(P))H=2;else if(Ka(P))H=l;else H=f;if(k+H>v)E=Math.min(E,Math.max(p,b)+y);if(k+H>r){F=!0;break t}y+=L.length,k+=H}p=j=0}if(g>=$)break t;for(let R=0,L=m.length;R<L;R++){let[P,C]=m[R];if(P.lastIndex=g,P.test(t)){if(y=P===Ja?Aa(t.slice(g,P.lastIndex)):P===Wa?1:P.lastIndex-g,H=y*C,k+H>v)E=Math.min(E,g+Math.floor((v-k)/C));if(k+H>r){F=!0;break t}k+=H,p=b,j=g,g=b=P.lastIndex;continue t}}g+=1}return{width:F?v:k,index:F?E:$,truncated:F,ellipsed:F&&r>=o}},Qa=xa;var n0={limit:1/0,ellipsis:"",ellipsisWidth:0},r0=(t,e={})=>{return Qa(t,n0,e).width},Ut=r0;var ai="\x1B",Xa="",i0=39,Ho="\x07",Va="[",o0="]",Ya="m",jo=`${o0}8;;`,Za=new RegExp(`(?:\\${Va}(?<code>\\d+)m|\\${jo}(?<uri>.*)${Ho})`,"y"),qa=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},_a=(t)=>`${ai}${Va}${t}${Ya}`,Ca=(t)=>`${ai}${jo}${t}${Ho}`,Oo=(t,e,n)=>{let r=e[Symbol.iterator](),i=!1,o=!1,s=t.at(-1),c=s===void 0?0:Ut(s),u=r.next(),h=r.next(),a=0;while(!u.done){let f=u.value,l=Ut(f);if(c+l<=n)t[t.length-1]+=f;else t.push(f),c=0;if(f===ai||f===Xa)i=!0,o=e.startsWith(jo,a+1);if(i){if(o){if(f===Ho)i=!1,o=!1}else if(f===Ya)i=!1}else if(c+=l,c===n&&!h.done)t.push(""),c=0;u=h,h=r.next(),a+=f.length}if(s=t.at(-1),!c&&s!==void 0&&s.length&&t.length>1)t[t.length-2]+=t.pop()},s0=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Ut(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},c0=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",i,o,s=t.split(" "),c=[""],u=0;for(let f=0;f<s.length;f++){let l=s[f];if(n.trim!==!1){let b=c.at(-1)??"",g=b.trimStart();if(b.length!==g.length)c[c.length-1]=g,u=Ut(g)}if(f!==0){if(u>=e&&(n.wordWrap===!1||n.trim===!1))c.push(""),u=0;if(u||n.trim===!1)c[c.length-1]+=" ",u++}let m=Ut(l);if(n.hard&&m>e){let b=e-u,g=1+Math.floor((m-b-1)/e);if(Math.floor((m-1)/e)<g)c.push("");Oo(c,l,e),u=Ut(c.at(-1)??"");continue}if(u+m>e&&u&&m){if(n.wordWrap===!1&&u<e){Oo(c,l,e),u=Ut(c.at(-1)??"");continue}c.push(""),u=0}if(u+m>e&&n.wordWrap===!1){Oo(c,l,e),u=Ut(c.at(-1)??"");continue}c[c.length-1]+=l,u+=m}if(n.trim!==!1)c=c.map((f)=>s0(f));let h=c.join(`
|
|
146
|
+
`),a=!1;for(let f=0;f<h.length;f++){let l=h[f];if(r+=l,!a){if(a=l>="\uD800"&&l<="\uDBFF",a)continue}else a=!1;if(l===ai||l===Xa){Za.lastIndex=f+1;let b=Za.exec(h)?.groups;if(b?.code!==void 0){let g=Number.parseFloat(b.code);i=g===i0?void 0:g}else if(b?.uri!==void 0)o=b.uri.length===0?void 0:b.uri}if(h[f+1]===`
|
|
147
|
+
`){if(o)r+=Ca("");let m=i?qa(i):void 0;if(i&&m)r+=_a(m)}else if(l===`
|
|
148
|
+
`){if(i&&qa(i))r+=_a(i);if(o)r+=Ca(o)}}return r},u0=/\r?\n/;function Fe(t,e,n){return String(t).normalize().split(u0).map((r)=>c0(r,e,n)).join(`
|
|
149
|
+
`)}var Qt=vr(Go(),1);function fn(t,e,n){if(!n.some((s)=>!s.disabled))return t;let r=t+e,i=Math.max(n.length-1,0),o=r<0?i:r>i?0:r;return n[o]?.disabled?fn(o,e<0?-1:1,n):o}function fi(t,e,n,r){let i=r.split(`
|
|
150
|
+
`),o=0,s=t;for(let u of i){if(s<=u.length)break;s-=u.length+1,o++}for(o=Math.max(0,Math.min(i.length-1,o+n)),s=Math.min(s,i[o].length)+e;s<0&&o>0;)o--,s+=i[o].length+1;for(;s>i[o].length&&o<i.length-1;)s-=i[o].length+1,o++;s=Math.max(0,Math.min(i[o].length,s));let c=0;for(let u=0;u<o;u++)c+=i[u].length+1;return c+s}var g0=["up","down","left","right","space","enter","cancel"],d0=["January","February","March","April","May","June","July","August","September","October","November","December"],Wt={actions:new Set(g0),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:[...d0],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function ef(t,e){if(typeof t=="string")return Wt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&ef(n,e))return!0;return!1}function m0(t,e){if(t===e)return;let n=t.split(`
|
|
151
151
|
`),r=e.split(`
|
|
152
|
-
`),i=Math.max(n.length,r.length),o=[];for(let s=0;s<i;s++)n[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var
|
|
152
|
+
`),i=Math.max(n.length,r.length),o=[];for(let s=0;s<i;s++)n[s]!==r[s]&&o.push(s);return{lines:o,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var n1=globalThis.process.platform.startsWith("win"),Ao=Symbol("clack:cancel");function Ne(t){return t===Ao}function li(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var di=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Ko=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function mr(t,e,n,r=n,i=n,o){let s=di(t??tf);return Fe(e,s-n.length,{hard:!0,trim:!1}).split(`
|
|
153
153
|
`).map((c,u,h)=>{let a=o?o(c,u):c;return u===0?`${r}${a}`:u===h.length-1?`${i}${a}`:`${n}${a}`}).join(`
|
|
154
|
-
`)}function
|
|
155
|
-
`),
|
|
156
|
-
`).length-1;this.output.write(
|
|
157
|
-
`);this.output.write(s[o]),this._prevFrame=t,this.output.write(
|
|
154
|
+
`)}function nf(t,e){if("~standard"in t){let n=t["~standard"].validate(e);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return t(e)}class pe{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=f0,output:r=tf,render:i,signal:o,...s}=t;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=e,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],r=[];for(let i of n)i.cb(...e),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ao);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=l0.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),li(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Qt.cursor.show),this.output.off("resize",this.render),li(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Qt.cursor.show),this.output.off("resize",this.render),li(this.input,!1),t(Ao)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&Wt.aliases.has(e.name)&&this.emit("cursor",Wt.aliases.get(e.name)),Wt.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=nf(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")}ef([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
155
|
+
`),li(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Fe(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
156
|
+
`).length-1;this.output.write(Qt.cursor.move(-999,t*-1))}render(){let t=Fe(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Qt.cursor.hide);else{let e=m0(this._prevFrame,t),n=Ko(this.output);if(this.restoreCursor(),e){let r=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),o=e.lines.find((s)=>s>=r);if(o===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(Qt.cursor.move(0,o-i)),this.output.write(Qt.erase.lines(1));let s=t.split(`
|
|
157
|
+
`);this.output.write(s[o]),this._prevFrame=t,this.output.write(Qt.cursor.move(0,s.length-o-1));return}else if(e.lines.length>1){if(r<i)o=r;else{let c=o-i;c>0&&this.output.write(Qt.cursor.move(0,c))}this.output.write(Qt.erase.down());let s=t.split(`
|
|
158
158
|
`).slice(o);this.output.write(s.join(`
|
|
159
|
-
`)),this._prevFrame=t;return}}this.output.write(Zt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function zp(t,e){if(t===void 0||e.length===0)return 0;let n=e.findIndex((r)=>r.value===t);return n!==-1?n:0}function Bp(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function Dp(t,e){if(e)return t?e:e[0]}var t0=class extends me{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#t;#o;#c;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return jo(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${e}${jo("inverse",n)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#c=e.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=e.multiple===!0,this.#t=typeof e.options=="function"?e.filter:e.filter??Bp;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=n.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#e=o)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,o)=>this.#n(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(e,n){return e==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&e!==void 0&&e!==""}#n(e,n){let r=n.name==="up",i=n.name==="down",o=n.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((a)=>!a.disabled&&(this.#t?this.#t(c,a):!0));if(n.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#e=an(this.#e,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=Dp(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((n)=>n!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#r(e){if(e!==this.#i){this.#i=e;let n=this.options;e&&this.#t?this.filteredOptions=n.filter((o)=>this.#t?.(e,o)):this.filteredOptions=[...n];let r=zp(this.focusedValue,this.filteredOptions);this.#e=an(r,0,this.filteredOptions);let i=this.filteredOptions[this.#e];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Lo extends me{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(Zt.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var e0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Ua(t){return[...t].map((e)=>e0[e])}function n0(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of e)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Oo(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function fi(t){return{year:Oo(t.year),month:Oo(t.month),day:Oo(t.day)}}function Po(t,e){return new Date(t||2001,e||1,0).getDate()}function Qa(t){let{year:e,month:n,day:r}=fi(t);if(!e||e<0||e>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(e,n-1,r));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:e,month:n,day:r}}function Ka(t){let e=Qa(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function r0(t,e,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&e.year===i.year?i.month:1,max:o&&e.year===o.year?o.month:12}:{min:i&&e.year===i.year&&e.month===i.month?i.day:1,max:o&&e.year===o.year&&e.month===o.month?o.day:Po(e.year,e.month)}}class Za extends me{#e;#i;#t;#o;#c;#n={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#t}}get segments(){return this.#e}get separator(){return this.#i}get formattedValue(){return this.#f(this.#t)}#f(t){return this.#e.map((e)=>t[e.type]).join(this.#i)}#u(){this._setUserInput(this.#f(this.#t)),this._setValue(Ka(this.#t)??void 0)}constructor(t){let e=t.format?{segments:Ua(t.format),separator:t.separator??"/"}:n0(t.locale),n=t.separator??e.separator,r=t.format?Ua(t.format):e.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(n);super({...t,initialUserInput:s},!1),this.#e=r,this.#i=n,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#n.segmentIndex,this.#e.length-1)),e=this.#e[t];if(e)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,e.len-1)),{segment:e,index:t}}#a(t){this.inlineError="",this.#s=null;let e=this.#h();e&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#e.length-1,e.index+t)),this.#n.positionInSegment=0,this.#r=!0)}#l(t){let e=this.#h();if(!e)return;let{segment:n}=e,r=this.#t[n.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=r0(n.type,fi(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[n.type]:c.toString().padStart(n.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#a(1);case"left":return this.#a(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(t,e){if(e?.name==="backspace"||e?.sequence===""||e?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let n=this.#h();if(!n)return;if(!this.#t[n.segment.type].replace(/_/g,"")){this.#a(-1);return}this.#t[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#u();return}if(e?.name==="tab"){this.inlineError="";let n=this.#h();if(!n)return;let r=e.shift?-1:1,i=n.index+r;i>=0&&i<this.#e.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#h();if(!n)return;let{segment:r}=n,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let l=this.#s+t,m={...this.#t,[r.type]:l},b=this.#g(m,r);if(b){this.inlineError=b,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=l,this.#s=null,this.#r=!1,this.#u(),n.index<this.#e.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#n.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(t,10);u=`0${t}`,h=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let l={...this.#t,[r.type]:u},m=this.#g(l,r);if(m){this.inlineError=m;return}}this.inlineError="",this.#t[r.type]=u;let a=u.includes("_")?void 0:Qa(this.#t);if(a){let{year:l,month:m}=a,b=Po(l,m);this.#t={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,m))).padStart(2,"0"),day:String(Math.max(1,Math.min(b,a.day))).padStart(2,"0")}}this.#u();let f=u.indexOf("_");h?(this.#r=!0,this.#s=t):f>=0?this.#n.positionInSegment=f:s>=0&&n.index<this.#e.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(c+1,r.len-1)}}#g(t,e){let{month:n,day:r}=fi(t);if(e.type==="month"&&(n<0||n>12))return Wt.date.messages.invalidMonth;if(e.type==="day"&&(r<0||r>31))return Wt.date.messages.invalidDay(31,"any month")}#p(t){let{year:e,month:n,day:r}=fi(this.#t);if(e&&n&&r){let i=Po(e,n);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Ka(this.#t)??t.defaultValue??void 0}}var i0=class extends me{options;cursor=0;#e;getGroupItems(e){return this.options.filter((n)=>n.group===e)}isGroupSelected(e){let n=this.getGroupItems(e),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let n=e.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(e.value);this.value=n?this.value.filter((r)=>r!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:n}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),this.#e?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},o0=new Set(["up","down","left","right"]);class qa extends me{#e=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return n===`
|
|
159
|
+
`)),this._prevFrame=t;return}}this.output.write(Qt.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}function p0(t,e){if(t===void 0||e.length===0)return 0;let n=e.findIndex((r)=>r.value===t);return n!==-1?n:0}function w0(t,e){return(e.label??String(e.value)).toLowerCase().includes(t.toLowerCase())}function b0(t,e){if(e)return t?e:e[0]}var $0=class extends pe{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#t;#o;#c;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return To(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let e=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${e}${To("inverse",n)}${r}`}get options(){return typeof this.#o=="function"?this.#o():this.#o}constructor(e){super(e),this.#o=e.options,this.#c=e.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=e.multiple===!0,this.#t=typeof e.options=="function"?e.filter:e.filter??w0;let r;if(e.initialValue&&Array.isArray(e.initialValue)?this.multiple?r=e.initialValue:r=e.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let o=n.findIndex((s)=>s.value===i);o!==-1&&(this.toggleSelected(i),this.#e=o)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(i,o)=>this.#n(i,o)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(e,n){return e==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&e!==void 0&&e!==""}#n(e,n){let r=n.name==="up",i=n.name==="down",o=n.name==="return",s=this.userInput===""||this.userInput==="\t",c=this.#c,u=this.options,h=c!==void 0&&c!==""&&u.some((a)=>!a.disabled&&(this.#t?this.#t(c,a):!0));if(n.name==="tab"&&s&&h){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(c,!0),this.isNavigating=!1;return}r||i?(this.#e=fn(this.#e,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):o?this.value=b0(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(e){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(e)?this.selectedValues=this.selectedValues.filter((n)=>n!==e):this.selectedValues=[...this.selectedValues,e]:this.selectedValues=[e])}#r(e){if(e!==this.#i){this.#i=e;let n=this.options;e&&this.#t?this.filteredOptions=n.filter((o)=>this.#t?.(e,o)):this.filteredOptions=[...n];let r=p0(this.focusedValue,this.filteredOptions);this.#e=fn(r,0,this.filteredOptions);let i=this.filteredOptions[this.#e];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class Jo extends pe{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(Qt.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var k0={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Ba(t){return[...t].map((e)=>k0[e])}function E0(t){let e=new Intl.DateTimeFormat(t,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of e)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Lo(t){return Number.parseInt((t||"0").replace(/_/g,"0"),10)||0}function gi(t){return{year:Lo(t.year),month:Lo(t.month),day:Lo(t.day)}}function Uo(t,e){return new Date(t||2001,e||1,0).getDate()}function rf(t){let{year:e,month:n,day:r}=gi(t);if(!e||e<0||e>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(e,n-1,r));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:e,month:n,day:r}}function Da(t){let e=rf(t);return e?new Date(Date.UTC(e.year,e.month-1,e.day)):void 0}function y0(t,e,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,o=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return t==="year"?{min:i?.year??1,max:o?.year??9999}:t==="month"?{min:i&&e.year===i.year?i.month:1,max:o&&e.year===o.year?o.month:12}:{min:i&&e.year===i.year&&e.month===i.month?i.day:1,max:o&&e.year===o.year&&e.month===o.month?o.day:Uo(e.year,e.month)}}class of extends pe{#e;#i;#t;#o;#c;#n={segmentIndex:0,positionInSegment:0};#r=!0;#s=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#t}}get segments(){return this.#e}get separator(){return this.#i}get formattedValue(){return this.#f(this.#t)}#f(t){return this.#e.map((e)=>t[e.type]).join(this.#i)}#u(){this._setUserInput(this.#f(this.#t)),this._setValue(Da(this.#t)??void 0)}constructor(t){let e=t.format?{segments:Ba(t.format),separator:t.separator??"/"}:E0(t.locale),n=t.separator??e.separator,r=t.format?Ba(t.format):e.segments,i=t.initialValue??t.defaultValue,o=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},s=r.map((c)=>o[c.type]).join(n);super({...t,initialUserInput:s},!1),this.#e=r,this.#i=n,this.#t=o,this.#o=t.minDate,this.#c=t.maxDate,this.#u(),this.on("cursor",(c)=>this.#d(c)),this.on("key",(c,u)=>this.#m(c,u)),this.on("finalize",()=>this.#p(t))}#h(){let t=Math.max(0,Math.min(this.#n.segmentIndex,this.#e.length-1)),e=this.#e[t];if(e)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,e.len-1)),{segment:e,index:t}}#a(t){this.inlineError="",this.#s=null;let e=this.#h();e&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#e.length-1,e.index+t)),this.#n.positionInSegment=0,this.#r=!0)}#l(t){let e=this.#h();if(!e)return;let{segment:n}=e,r=this.#t[n.type],i=!r||r.replace(/_/g,"")==="",o=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,s=y0(n.type,gi(this.#t),this.#o,this.#c),c;i?c=t===1?s.min:s.max:c=Math.max(Math.min(s.max,o+t),s.min),this.#t={...this.#t,[n.type]:c.toString().padStart(n.len,"0")},this.#r=!0,this.#s=null,this.#u()}#d(t){if(t)switch(t){case"right":return this.#a(1);case"left":return this.#a(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#m(t,e){if(e?.name==="backspace"||e?.sequence===""||e?.sequence==="\b"||t===""||t==="\b"){this.inlineError="";let n=this.#h();if(!n)return;if(!this.#t[n.segment.type].replace(/_/g,"")){this.#a(-1);return}this.#t[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#u();return}if(e?.name==="tab"){this.inlineError="";let n=this.#h();if(!n)return;let r=e.shift?-1:1,i=n.index+r;i>=0&&i<this.#e.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(t&&/^[0-9]$/.test(t)){let n=this.#h();if(!n)return;let{segment:r}=n,i=!this.#t[r.type].replace(/_/g,"");if(this.#r&&this.#s!==null&&!i){let l=this.#s+t,m={...this.#t,[r.type]:l},b=this.#g(m,r);if(b){this.inlineError=b,this.#s=null,this.#r=!1;return}this.inlineError="",this.#t[r.type]=l,this.#s=null,this.#r=!1,this.#u(),n.index<this.#e.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#t[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#s=null;let o=this.#t[r.type],s=o.indexOf("_"),c=s>=0?s:Math.min(this.#n.positionInSegment,r.len-1);if(c<0||c>=r.len)return;let u=o.slice(0,c)+t+o.slice(c+1),h=!1;if(c===0&&o==="__"&&(r.type==="month"||r.type==="day")){let l=Number.parseInt(t,10);u=`0${t}`,h=l<=(r.type==="month"?1:2)}if(r.type==="year"&&(u=(o.replace(/_/g,"")+t).padStart(r.len,"_")),!u.includes("_")){let l={...this.#t,[r.type]:u},m=this.#g(l,r);if(m){this.inlineError=m;return}}this.inlineError="",this.#t[r.type]=u;let a=u.includes("_")?void 0:rf(this.#t);if(a){let{year:l,month:m}=a,b=Uo(l,m);this.#t={year:String(Math.max(0,Math.min(9999,l))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,m))).padStart(2,"0"),day:String(Math.max(1,Math.min(b,a.day))).padStart(2,"0")}}this.#u();let f=u.indexOf("_");h?(this.#r=!0,this.#s=t):f>=0?this.#n.positionInSegment=f:s>=0&&n.index<this.#e.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(c+1,r.len-1)}}#g(t,e){let{month:n,day:r}=gi(t);if(e.type==="month"&&(n<0||n>12))return Wt.date.messages.invalidMonth;if(e.type==="day"&&(r<0||r>31))return Wt.date.messages.invalidDay(31,"any month")}#p(t){let{year:e,month:n,day:r}=gi(this.#t);if(e&&n&&r){let i=Uo(e,n);this.#t={...this.#t,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Da(this.#t)??t.defaultValue??void 0}}var M0=class extends pe{options;cursor=0;#e;getGroupItems(e){return this.options.filter((n)=>n.group===e)}isGroupSelected(e){let n=this.getGroupItems(e),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let e=this.options[this.cursor];if(e!==void 0)if(this.value===void 0&&(this.value=[]),e.group===!0){let n=e.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((o)=>o.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(e.value);this.value=n?this.value.filter((r)=>r!==e.value):[...this.value,e.value]}}constructor(e){super(e,!1);let{options:n}=e;this.#e=e.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((o)=>({...o,group:r}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===e.cursorAt),this.#e?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#e&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},v0=new Set(["up","down","left","right"]);class sf extends pe{#e=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${t}█`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return n===`
|
|
160
160
|
`?`${e}█
|
|
161
|
-
${r}`:`${e}${
|
|
161
|
+
${r}`:`${e}${To("inverse",n)}${r}`}get cursor(){return this._cursor}#t(t){if(this.userInput.length===0){this._setUserInput(t);return}this._setUserInput(this.userInput.slice(0,this.cursor)+t+this.userInput.slice(this.cursor))}#o(t){let e=this.value??"";switch(t){case"up":this._cursor=fi(this._cursor,0,-1,e);return;case"down":this._cursor=fi(this._cursor,0,1,e);return;case"left":this._cursor=fi(this._cursor,-1,0,e);return;case"right":this._cursor=fi(this._cursor,1,0,e);return}}_shouldSubmit(t,e){if(this.#i)return this.focused==="submit"?!0:(this.#t(`
|
|
162
162
|
`),this._cursor++,!1);let n=this.#e;return this.#e=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
163
163
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#t(`
|
|
164
|
-
`),this._cursor++,!1)}constructor(t){let e=t.initialUserInput??t.initialValue;super({...t,initialUserInput:e},!1),e!==void 0&&(this._cursor=e.length),this.#i=t.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&
|
|
165
|
-
`);$.push(
|
|
164
|
+
`),this._cursor++,!1)}constructor(t){let e=t.initialUserInput??t.initialValue;super({...t,initialUserInput:e},!1),e!==void 0&&(this._cursor=e.length),this.#i=t.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&v0.has(r.name)){this.#e=!1,this.#o(r.name);return}if(n==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#e=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#t(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}class Wo extends pe{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?fn(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=fn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=fn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}import{styleText as S,stripVTControlCharacters as l1}from"node:util";import Vt from"node:process";var df=vr(Go(),1);function S0(){if(Vt.platform!=="win32")return Vt.env.TERM!=="linux";return Boolean(Vt.env.CI)||Boolean(Vt.env.WT_SESSION)||Boolean(Vt.env.TERMINUS_SUBLIME)||Vt.env.ConEmuTask==="{cmd::Cmder}"||Vt.env.TERM_PROGRAM==="Terminus-Sublime"||Vt.env.TERM_PROGRAM==="vscode"||Vt.env.TERM==="xterm-256color"||Vt.env.TERM==="alacritty"||Vt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var I0=S0();var gt=(t,e)=>I0?t:e,F0=gt("◆","*"),N0=gt("■","x"),R0=gt("▲","x"),mf=gt("◇","o"),O0=gt("┌","T"),vt=gt("│","|"),ln=gt("└","—"),p1=gt("┐","T"),w1=gt("┘","—"),cf=gt("●",">"),uf=gt("○"," "),H0=gt("◻","[•]"),hf=gt("◼","[+]"),af=gt("◻","[ ]"),b1=gt("▪","•"),ff=gt("─","-"),j0=gt("╮","+"),P0=gt("├","+"),G0=gt("╯","+"),L0=gt("╰","+"),$1=gt("╭","+"),k1=gt("●","•"),E1=gt("◆","*"),y1=gt("▲","!"),M1=gt("■","x"),pf=(t)=>{switch(t){case"initial":case"active":return S("cyan",F0);case"cancel":return S("red",N0);case"error":return S("yellow",R0);case"submit":return S("green",mf)}},T0=(t)=>{switch(t){case"initial":case"active":return S("cyan",vt);case"cancel":return S("red",vt);case"error":return S("yellow",vt);case"submit":return S("green",vt)}};function A0(t,e){let n=[`${e?`${S("cyan",vt)} `:""}${t.join(" • ")}`];return e&&n.push(S("cyan",ln)),n}var lf=(t,e,n,r,i,o=!1)=>{let s=e,c=0;if(o)for(let u=r-1;u>=n;u--){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}else for(let u=n;u<r;u++){let h=t[u];if(h&&(s-=h.length),c++,s<=i)break}return{lineCount:s,removals:c}},gf=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:o=0,rowPadding:s=4})=>{let c=di(r)-o,u=Ko(r),h=S("dim","..."),a=Math.max(u-s,0),f=Math.max(Math.min(i,a),5),l=0;t>=f-3&&(l=Math.max(Math.min(t-f+3,e.length-f),0));let m=f<e.length&&l>0,b=f<e.length&&l+f<e.length,g=Math.min(l+f,e.length),$=[],y=0;m&&y++,b&&y++;let F=l+(m?1:0),E=g-(b?1:0);for(let p=F;p<E;p++){let j=e[p],k=j?n(j,p===t):"",H=Fe(k,c,{hard:!0,trim:!1}).split(`
|
|
165
|
+
`);$.push(H),y+=H.length}if(y>a){let p=0,j=0,k=y,H=t-F,R=a,L=()=>lf($,k,0,H,R),P=()=>lf($,k,H+1,$.length,R,!0);m?({lineCount:k,removals:p}=L(),k>R&&(b||(R-=1),{lineCount:k,removals:j}=P())):(b||(R-=1),{lineCount:k,removals:j}=P(),k>R&&(R-=1,{lineCount:k,removals:p}=L())),p>0&&(m=!0,$.splice(0,p)),j>0&&(b=!0,$.splice($.length-j,j))}let v=[];m&&v.push(h);for(let p of $)for(let j of p)v.push(j);return b&&v.push(h),v};var wr=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new Jo({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Wt.withGuide,i=`${pf(this.state)} `,o=r?`${S("gray",vt)} `:"",s=mr(t.output,t.message,o,i),c=`${r?`${S("gray",vt)}
|
|
166
166
|
`:""}${s}
|
|
167
|
-
`,u=this.value?e:n;switch(this.state){case"submit":{let h=r?`${S("gray",
|
|
168
|
-
${S("gray",
|
|
169
|
-
${S("cyan",
|
|
170
|
-
`:` ${S("dim","/")} `}${this.value?`${S("dim",
|
|
167
|
+
`,u=this.value?e:n;switch(this.state){case"submit":{let h=r?`${S("gray",vt)} `:"";return`${c}${h}${S("dim",u)}`}case"cancel":{let h=r?`${S("gray",vt)} `:"";return`${c}${h}${S(["strikethrough","dim"],u)}${r?`
|
|
168
|
+
${S("gray",vt)}`:""}`}default:{let h=r?`${S("cyan",vt)} `:"",a=r?S("cyan",ln):"";return`${c}${h}${this.value?`${S("green",cf)} ${e}`:`${S("dim",uf)} ${S("dim",e)}`}${t.vertical?r?`
|
|
169
|
+
${S("cyan",vt)} `:`
|
|
170
|
+
`:` ${S("dim","/")} `}${this.value?`${S("dim",uf)} ${S("dim",n)}`:`${S("green",cf)} ${n}`}
|
|
171
171
|
${a}
|
|
172
|
-
`}}}}).prompt()};var
|
|
172
|
+
`}}}}).prompt()};var U0=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Space:")} select`,`${S("dim","Enter:")} confirm`],pr=(t,e)=>t.split(`
|
|
173
173
|
`).map((n)=>e(n)).join(`
|
|
174
|
-
`),
|
|
175
|
-
${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??Wt.withGuide,o=
|
|
174
|
+
`),wf=(t)=>{let e=(i,o)=>{let s=i.label??String(i.value);return o==="disabled"?`${S("gray",af)} ${pr(s,(c)=>S(["strikethrough","gray"],c))}${i.hint?` ${S("dim",`(${i.hint??"disabled"})`)}`:""}`:o==="active"?`${S("cyan",H0)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="selected"?`${S("green",hf)} ${pr(s,(c)=>S("dim",c))}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="cancelled"?`${pr(s,(c)=>S(["strikethrough","dim"],c))}`:o==="active-selected"?`${S("green",hf)} ${s}${i.hint?` ${S("dim",`(${i.hint})`)}`:""}`:o==="submitted"?`${pr(s,(c)=>S("dim",c))}`:`${S("dim",af)} ${pr(s,(c)=>S("dim",c))}`},n=t.required??!0,r=t.showInstructions??!0;return new Wo({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
175
|
+
${S("reset",S("dim",`Press ${S(["gray","bgWhite","inverse"]," space ")} to select, ${S("gray",S("bgWhite",S("inverse"," enter ")))} to submit`))}`},render(){let i=t.withGuide??Wt.withGuide,o=mr(t.output,t.message,i?`${T0(this.state)} `:"",`${pf(this.state)} `),s=`${i?`${S("gray",vt)}
|
|
176
176
|
`:""}${o}
|
|
177
|
-
`,c=this.value??[],u=(h,a)=>{if(h.disabled)return e(h,"disabled");let f=c.includes(h.value);return a&&f?e(h,"active-selected"):f?e(h,"selected"):e(h,a?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:f})=>c.includes(f)).map((f)=>e(f,"submitted")).join(S("dim",", "))||S("dim","none"),a=
|
|
178
|
-
${S("gray",
|
|
179
|
-
`).map((m,b)=>b===0?`${i?`${S("yellow",
|
|
177
|
+
`,c=this.value??[],u=(h,a)=>{if(h.disabled)return e(h,"disabled");let f=c.includes(h.value);return a&&f?e(h,"active-selected"):f?e(h,"selected"):e(h,a?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:f})=>c.includes(f)).map((f)=>e(f,"submitted")).join(S("dim",", "))||S("dim","none"),a=mr(t.output,h,i?`${S("gray",vt)} `:"");return`${s}${a}`}case"cancel":{let h=this.options.filter(({value:f})=>c.includes(f)).map((f)=>e(f,"cancelled")).join(S("dim",", "));if(h.trim()==="")return`${s}${S("gray",vt)}`;let a=mr(t.output,h,i?`${S("gray",vt)} `:"");return`${s}${a}${i?`
|
|
178
|
+
${S("gray",vt)}`:""}`}case"error":{let h=i?`${S("yellow",vt)} `:"",a=this.error.split(`
|
|
179
|
+
`).map((m,b)=>b===0?`${i?`${S("yellow",ln)} `:""}${S("yellow",m)}`:` ${m}`).join(`
|
|
180
180
|
`),f=s.split(`
|
|
181
181
|
`).length,l=a.split(`
|
|
182
|
-
`).length+1;return`${s}${h}${
|
|
182
|
+
`).length+1;return`${s}${h}${gf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:f+l,style:u}).join(`
|
|
183
183
|
${h}`)}
|
|
184
184
|
${a}
|
|
185
|
-
`}default:{let h=i?`${S("cyan",
|
|
186
|
-
`).length,f=r?
|
|
187
|
-
`),m=f.length+1;return`${s}${h}${
|
|
185
|
+
`}default:{let h=i?`${S("cyan",vt)} `:"",a=s.split(`
|
|
186
|
+
`).length,f=r?A0(U0,i):i?[S("cyan",ln)]:[],l=f.join(`
|
|
187
|
+
`),m=f.length+1;return`${s}${h}${gf({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:a+m,style:u}).join(`
|
|
188
188
|
${h}`)}
|
|
189
189
|
${l}
|
|
190
|
-
`}}}}).prompt()};var
|
|
190
|
+
`}}}}).prompt()};var gn=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Wt.withGuide?`${S("gray",ln)} `:"";n.write(`${r}${S("red",t)}
|
|
191
191
|
|
|
192
|
-
`)},
|
|
193
|
-
`)},
|
|
194
|
-
${S("gray",
|
|
192
|
+
`)},mi=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Wt.withGuide?`${S("gray",O0)} `:"";n.write(`${r}${t}
|
|
193
|
+
`)},bf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Wt.withGuide?`${S("gray",vt)}
|
|
194
|
+
${S("gray",ln)} `:"";n.write(`${r}${t}
|
|
195
195
|
|
|
196
|
-
`)};var
|
|
197
|
-
`),o=i.reduce((u,h)=>Math.max(
|
|
198
|
-
`).map(o),""],c=
|
|
199
|
-
`),a=i?`${S("gray",
|
|
200
|
-
`:"",f=i?
|
|
196
|
+
`)};var K0=(t)=>t,J0=(t,e,n)=>{let r={hard:!0,trim:!1},i=Fe(t,e,r).split(`
|
|
197
|
+
`),o=i.reduce((u,h)=>Math.max(Ut(h),u),0),s=i.map(n).reduce((u,h)=>Math.max(Ut(h),u),0),c=e-(s-o);return Fe(t,c,r)},dn=(t="",e="",n)=>{let r=n?.output??Vt.stdout,i=n?.withGuide??Wt.withGuide,o=n?.format??K0,s=["",...J0(t,di(r)-6,o).split(`
|
|
198
|
+
`).map(o),""],c=Ut(e),u=Math.max(s.reduce((l,m)=>{let b=Ut(m);return b>l?b:l},0),c)+2,h=s.map((l)=>`${S("gray",vt)} ${l}${" ".repeat(u-Ut(l))}${S("gray",vt)}`).join(`
|
|
199
|
+
`),a=i?`${S("gray",vt)}
|
|
200
|
+
`:"",f=i?P0:L0;r.write(`${a}${S("green",mf)} ${S("reset",e)} ${S("gray",ff.repeat(Math.max(u-c-1,1))+j0)}
|
|
201
201
|
${h}
|
|
202
|
-
${S("gray",f+
|
|
203
|
-
`)};var
|
|
204
|
-
`)}}function
|
|
205
|
-
${t} palettes installed — open a new tab, or reload your terminal config`)}function
|
|
206
|
-
`))}function
|
|
207
|
-
`))}function
|
|
208
|
-
${u} palettes — ${s.filter((h)=>i.has(h.name)).length} installed`)}}async function
|
|
202
|
+
${S("gray",f+ff.repeat(u+2)+G0)}
|
|
203
|
+
`)};var v1={light:gt("─","-"),heavy:gt("━","="),block:gt("█","#")};var S1=[`${S("dim","↑/↓")} to navigate`,`${S("dim","Enter:")} confirm`];var I1=`${S("gray",vt)} `;import{existsSync as V0}from"node:fs";import{openSync as W0,writeSync as x0}from"node:fs";import{ReadStream as Q0}from"node:tty";var $f=["10","11","12","17",...Array.from({length:16},(t,e)=>`4;${e}`)];function br(t=process.env){return Boolean(t.NO_COLOR)||t.TERM==="dumb"}function pi(t){return[`\x1B]11;${t.background}\x1B\\`,`\x1B]10;${t.foreground}\x1B\\`,`\x1B]12;${t.cursor}\x1B\\`,`\x1B]17;${t.selection}\x1B\\`,...t.ansi.map((e,n)=>`\x1B]4;${n};${e}\x1B\\`)].join("")}function kf(t){let e=new Map;for(let n of t.split("\x1B")){let r=n.match(/^\](\d+(?:;\d+)?);(rgba?:[0-9a-fA-F/]+)/),[,i,o]=r??[];if(i&&o)e.set(i,o)}return e}function Ef(t){return[...t].map(([e,n])=>`\x1B]${e};${n}\x1B\\`).join("")}async function yf(){let t,e;try{t=W0("/dev/tty","r+"),e=new Q0(t),e.setRawMode(!0)}catch{return new Map}try{x0(t,$f.map((r)=>`\x1B]${r};?\x1B\\`).join(""));let n="";return await new Promise((r)=>{let i=setTimeout(r,120);e.on("data",(o)=>{if(n+=o.toString(),kf(n).size>=$f.length)clearTimeout(i),r()})}),kf(n)}finally{e.setRawMode(!1),e.destroy()}}function mn(t){let e=t.replace("#","");return[e.slice(0,2),e.slice(2,4),e.slice(4,6)].map((n)=>Number.parseInt(n,16)).join(";")}function Mf(t,e){return`\x1B[48;2;${mn(e)}m ${t} \x1B[0m`}function Qo(t,e){return`\x1B[48;2;${mn(t)};38;2;${mn(e)}m ● \x1B[0m`}function vf(t){return`\x1B[38;2;${mn(t)}m`}function Zo(t,e){return`\x1B[48;2;${mn(e)}m${t.map((n)=>`\x1B[38;2;${mn(n)}m▄`).join("")} \x1B[0m`}function wi(t,e){let n=e.toLowerCase();return[t.name,t.group,t.native??""].some((r)=>r.toLowerCase().includes(n))}function If(t,e,n){let r=n.trim(),i=[],o=new Set;for(let s of t){if(s.default||o.has(s.group))continue;o.add(s.group);let c=t.filter((a)=>!a.default&&a.group===s.group),u=r?c.filter((a)=>wi(a,r)):c;if(r&&u.length===0)continue;let h=r.length>0||e.has(s.group);if(i.push({kind:"group",name:s.group,native:s.native,lead:c.find((a)=>a.lead)??s,expanded:h,count:u.length}),h)i.push(...u.map((a)=>({kind:"palette",entry:a})))}return i}function Z0(t,e){let n=e.trim(),r=new Set(t.filter((i)=>!i.default&&(n===""||wi(i,n))).map((i)=>i.group));return If(t,new Set,"").filter((i)=>i.kind==="group"&&r.has(i.name))}function q0(t){let e=t.findIndex((n)=>n.kind==="palette");return e===-1?0:e}var ee="\x1B[0m",pn="\x1B[2m",_0="\x1B[1m",Sf="\x1B[1;7m",C0="\x1B[36m",X0="\x1B[33m";function Ff(t){return t==="decode"||t==="glitch"?t:"typewriter"}class qo extends pe{picked;scope;entries;named;series;seriesPad;expanded=new Set;rows=[];cursor=0;top=0;maxItems;color;lastInput="";lastFocused="";onFocus;example="";fx;fxStep=0;fxSeed=0;fxTimer;constructor(t){super({render:()=>this.draw(),input:t.input,output:t.output,validate:t.required?()=>this.picked.size===0?`pick at least one ${this.scope}`:void 0:void 0},!0);this.entries=t.entries,this.scope=t.scope??"palette",this.picked=new Set(t.installed??[]),this.named=t.entries.filter((n)=>!n.default),this.series=[...new Set(this.named.map((n)=>n.group))],this.seriesPad=Math.max(0,...this.series.map((n)=>n.length)),this.maxItems=t.maxItems??12,this.color=t.color??!0,this.fx=t.fx??"typewriter",this.onFocus=t.onFocus,this.rollExample();let e=setInterval(()=>{this.rollExample(),this.fxStep=8,this.output.emit("resize")},3000);e.unref?.(),this.once("finalize",()=>{clearInterval(e),clearTimeout(this.fxTimer)}),this.rebuild("first"),this.on("cursor",(n)=>{if(n==="up")this.move(-1);else if(n==="down")this.move(1);else if(n==="left")this.fold(!1);else if(n==="right")this.fold(!0)}),this.on("userInput",(n)=>{if(n!==this.lastInput)this.lastInput=n,this.rebuild("keep")}),this.on("key",(n,r)=>{if(r?.name==="space")this.pick(this.rows[this.cursor])})}_isActionKey(t){return t==="\t"||t===" "}members(t){let e=this.scope==="palette"?this.userInput.trim():"";return this.named.filter((n)=>n.group===t&&(e===""||wi(n,e)))}everyone(t){return t.flatMap((e)=>e.kind==="group"?this.members(e.name):[])}pick(t){let e=t?.kind==="palette"?[t.entry.name]:t?.kind==="group"?this.members(t.name).map((r)=>r.name):t?.kind==="all"?this.everyone(this.rows).map((r)=>r.name):[];if(e.length===0)return;let n=e.some((r)=>!this.picked.has(r));for(let r of e)if(n)this.picked.add(r);else this.picked.delete(r)}pickedIn(t){return this.members(t).filter((e)=>this.picked.has(e.name)).length}pickedCount(){if(this.scope==="palette")return this.picked.size;return this.series.filter((t)=>this.members(t).every((e)=>this.picked.has(e.name))).length}rollExample(){let t=this.named[Math.floor(Math.random()*this.named.length)],e=this.series[Math.floor(Math.random()*this.series.length)];if(!t||!e){this.example="";return}let n=`${t.name} | ${e}`;this.example=n.length>30?`${n.slice(0,29)}…`:n,this.fxSeed=Math.floor(Math.random()*997)}animatedExample(){if(this.fxStep===0)return this.example;if(!this.fxTimer)this.fxTimer=setTimeout(()=>{this.fxTimer=void 0,this.fxStep-=1,this.output.emit("resize")},60),this.fxTimer.unref?.();let t=Math.floor(this.example.length*(8-this.fxStep)/8);if(this.fx==="typewriter")return`${this.example.slice(0,t)}▏`;let e=this.fx==="decode"?"abcdefghijklmnopqrstuvwxyz":"▓▒░#*+=<>?/-_",n=this.fx==="decode"?(r)=>!/[a-z0-9]/i.test(r):(r)=>r===" ";return[...this.example].map((r,i)=>i+(i*7+this.fxSeed)%3<t||n(r)?r:e[Math.floor(Math.random()*e.length)]??r).join("")}sync(){let t=this.rows[this.cursor],e=t?.kind==="palette"?t.entry:t?.kind==="group"&&this.scope==="series"?t.lead:void 0;if(e&&e.name!==this.lastFocused)this.lastFocused=e.name,this.onFocus?.(e)}rebuild(t){let e=this.rows[this.cursor],n=this.scope==="series"?Z0(this.entries,this.userInput):If(this.entries,this.expanded,this.userInput),r=n.length>0?q0(n)+1:0;if(this.rows=n.length>0?[{kind:"all",count:this.allCount(n)},...n]:[],t==="first")this.cursor=r;else if(t==="keep"){let i=e?.kind==="palette"?e.entry.name:"",o=i?this.rows.findIndex((s)=>s.kind==="palette"&&s.entry.name===i):-1;this.cursor=o===-1?r:o}else if(this.cursor>=this.rows.length)this.cursor=Math.max(0,this.rows.length-1);this.sync()}allCount(t){return this.scope==="series"?t.length:this.everyone(t).length}move(t){let e=this.cursor+t;if(e>=0&&e<this.rows.length)this.cursor=e;this.sync()}toggle(t){if(this.expanded.has(t))this.expanded.delete(t);else this.expanded.add(t);this.rebuild("clamp")}fold(t){if(this.userInput||this.scope==="series")return;let e=this.rows[this.cursor];if(e?.kind==="group"){if(t!==e.expanded)this.toggle(e.name)}else if(e?.kind==="palette"&&!t&&!e.entry.default){let n=e.entry.group;if(this.expanded.delete(n),this.rebuild("clamp"),this.cursor=this.rows.findIndex((r)=>r.kind==="group"&&r.name===n),this.cursor===-1)this.cursor=0;this.sync()}}renderRow(t,e){let n=e?"▶ ":" ";if(t.kind==="all"){let o=this.everyone(this.rows).every((c)=>this.picked.has(c.name))?"● ":"○ ",s=`(${t.count})`;return`${n}${o}select all ${this.color?`${pn}${s}${ee}`:s}`}if(t.kind==="group"&&this.scope==="series"){let o=this.pickedIn(t.name)===t.count?"● ":"○ ",s=t.name.padEnd(this.seriesPad),c=`(${t.count})${t.native?` ${t.native}`:""}`;if(!this.color)return`${n}${o}${s} ${c}`;let u=t.lead;return`${n}${o}${s} ${Qo(u.background,u.cursor)}${Zo(u.ansi.slice(1,7),u.background)} ${pn}${c}${ee}`}if(t.kind==="group"){let o=t.expanded?"▾":"▸",s=this.rows[this.cursor],c=s?.kind==="palette"&&s.entry.group===t.name?s.entry:void 0,u=this.color?e?`${Sf} ${t.name} ${ee}`:c?`${Sf}${vf(c.cursor)} ${t.name} ${ee}`:` ${_0}${t.name}${ee} `:e?`[${t.name}]`:` ${t.name}`,h=this.color?Mf("●",t.lead.selection):"",a=`${this.pickedIn(t.name)}/${t.count}`,f=this.color?` ${pn}(${a})${ee}`:` (${a})`,l=t.native?this.color?` ${pn}${t.native}${ee}`:` ${t.native}`:"";return`${o}${u}${h}${f}${l}`}let r=t.entry,i=this.picked.has(r.name)?"● ":"○ ";if(!this.color)return` ${n}${i}${r.name.padEnd(13)} ● · ${r.ansiSource}`;return` ${n}${i}${r.name.padEnd(13)} ${Qo(r.background,r.cursor)}${Zo(r.ansi.slice(1,7),r.background)} ${pn}${r.ansiSource}${ee}`}draw(){let t=(g)=>this.color?`${pn}${g}${ee}`:g,e=(g)=>this.color?`${C0}${g}${ee}`:g,n=this.scope==="series"?"series":"catalog";if(this.state==="submit")return`${t("◇")} ${n} ${t(`· ${this.pickedCount()} picked`)}`;if(this.state==="cancel")return`${t(`◇ ${n} · cancelled`)}`;let r=this.userInput.trim(),i=this.scope==="series"?this.series.length:this.named.length,o=this.scope==="series"?this.rows.filter((g)=>g.kind==="group").length:r?this.named.filter((g)=>wi(g,r)).length:i,s=`${e("◆")} ${n} ${t(`(${o}/${i} · ${this.pickedCount()} picked)`)}`,c=`${e("│")} ${this.userInput?`⌕ ${this.userInput}_`:t(`⌕ search…${this.example?` e.g. ${this.animatedExample()}`:""}`)}`;if(this.cursor<this.top)this.top=this.cursor;if(this.cursor>=this.top+this.maxItems)this.top=this.cursor-this.maxItems+1;this.top=Math.min(this.top,Math.max(0,this.rows.length-this.maxItems));let u=this.rows.slice(this.top,this.top+this.maxItems),h=u.length>0?u.map((g,$)=>`${e("│")} ${this.renderRow(g,this.top+$===this.cursor)}`):[`${e("│")} ${t(`no ${this.scope==="series"?"series":"palettes"} match '${this.userInput}'`)}`];while(h.length<this.maxItems)h.push(e("│"));let a=this.rows.length-this.top-u.length,f=a>0?`${e("│")} ${t(`↓ ${a} more`)}`:e("│"),l=this.scope==="series"?"":" · ←→ fold",m=this.scope==="series"?"continue":"install",b=this.state==="error"?`${e("└")} ${this.color?`${X0}${this.error}${ee}`:this.error}`:`${e("└")} ${t(`↑↓ move${l} · space pick · type to filter · enter ${m} · esc cancel`)}`;return[s,c,...h,f,b].join(`
|
|
204
|
+
`)}}function $r(t,e,n,r){let i=Ie(),o=Boolean(te(n))!==Boolean(te(r)),s=o?hr(r,i):r;return lr(t,e,s),fr(t,s),o&&xe(s,i)&&i.running()}function _o(t){console.log(`
|
|
205
|
+
${t} palettes installed — open a new tab, or reload your terminal config`)}function Nf(t){let e=Pt(),n=At(e),r=Jt(e),i=t.filter((c)=>r.palettes.includes(c)),o=t.filter((c)=>!r.palettes.includes(c));if(o.length===0){console.log(`already installed: ${i.join(", ")}`);return}let s={...r,palettes:[...r.palettes,...o]};$r(e,n,r,s);for(let c of o)console.log(` + ${c}`);_o(s.palettes.length)}function Rf(t){let e=Pt(),n=At(e),r=Jt(e),i=t.filter((s)=>r.palettes.includes(s));if(i.length===0){console.log(`not installed: ${t.join(", ")}`);return}let o={...r,palettes:r.palettes.filter((s)=>!i.includes(s))};$r(e,n,r,o),yo(e,n,r.terminals,i);for(let s of i)console.log(` - ${s}`);_o(o.palettes.length)}function Of(t){let e=Pt(),n=At(e),r=Jt(e);if(!r.palettes.includes(t))throw Error(`${t} is not installed — \`ttheme add ${t}\` first`);let{off:i,...o}=r,s=Ie(),c=hr({...o,startup:t},s);lr(e,n,c),fr(e,c);let u=xe(c,s);console.log(Pf(t,c.terminals,u&&s.running()).join(`
|
|
206
|
+
`))}function Hf(){let t=Pt(),e=Jt(t),n=sn(e);if(!n)throw Error("no palettes installed — `ttheme browse` picks some");if(!e.off){console.log(`already on · ${n}`);return}let{off:r,...i}=e,o=$r(t,At(t),e,i);console.log(Pf(n,i.terminals,o).join(`
|
|
207
|
+
`))}function jf(){let t=Pt(),e=Jt(t);if(e.off){console.log("already off");return}let n=$r(t,At(t),e,{...e,off:!0}),r=sn(e);if(console.log(`off · new tabs open in the terminal's own colors${r?` — \`ttheme on\` wears ${r} again`:""}`),n)console.log("iterm2 new tabs open on your own profile once iTerm2 restarts")}function Pf(t,e,n){let r=e.filter((o)=>o!=="iterm2"),i=r.length>0?[`default ${t} · ${r.join(", ")} open new tabs with it once their config reloads`]:[];if(e.includes("iterm2"))i.push(n?'iterm2 new tabs open with it once iTerm2 restarts — "ttheme · default" is now its default profile':'iterm2 new tabs open with it — "ttheme · default" is its default profile');return i.length>0?i:[`default ${t} · no terminal is wired to open with it — \`ttheme init\` wires one`]}function Gf(t,e=!1){let n=Pt(),r=At(n),i=new Set(Jt(n).palettes),o=Pe(r.palettes),s=Zn(t?Nh(o,t):o);if(e){let u=s.map((h)=>({name:h.name,group:h.group,installed:i.has(h.name)}));console.log(JSON.stringify(u,null,2));return}let c=Math.max(...s.map((u)=>u.name.length),0);for(let u of s)console.log(` ${i.has(u.name)?"●":"○"} ${u.name.padEnd(c)} ${u.group}`);if(process.stdout.isTTY){let u=t?`${s.length} of ${o.length}`:`${o.length}`;console.log(`
|
|
208
|
+
${u} palettes — ${s.filter((h)=>i.has(h.name)).length} installed`)}}async function Lf(){let t=Pt(),e=V0(Dr(t))?At(t).palettes.length:0,n=await Ih(vh);ti(t,n);let r=n.palettes.length-e;console.log(`catalog ${n.version} — ${n.palettes.length} palettes${r>0?` (+${r})`:""}`)}async function Co(t,e,n,r=!1){let i=process.env.TTHEME_SORT==="series"?t.palettes:Zn(t.palettes),o=process.stdout.isTTY===!0&&!br(),s=o?await yf():new Map,c=new qo({entries:i,scope:n,installed:e,required:r,color:!br(),fx:Ff(process.env.TTHEME_FX),onFocus:o?(h)=>process.stdout.write(pi(h)):void 0}),u=await c.prompt();if(process.stdout.write(Ef(s)),Ne(u))return;return t.palettes.filter((h)=>c.picked.has(h.name)).map((h)=>h.name)}async function Tf(){let t=Pt(),e=At(t),n=Jt(t),r=await Co(e,n.palettes,"palette");if(!r){console.log("nothing changed");return}let i=n.palettes.filter((c)=>!r.includes(c)),o=r.filter((c)=>!n.palettes.includes(c));if(o.length===0&&i.length===0){console.log("nothing changed");return}let s={...n,palettes:r};$r(t,e,n,s),yo(t,e,n.terminals,i);for(let c of o)console.log(` + ${c}`);for(let c of i)console.log(` - ${c}`);_o(s.palettes.length)}function rw(t,e,n){for(let r of tw(e))t.push({from:$t(e,r),to:$t(n,r)})}function Wf(t){return JSON.parse(bn($t(t,"dist","manifest.json"),"utf8"))}function Uf(t,e){let n=$t(e.configHome,"ttheme"),r=[{from:$t(e.root,"bin","ttheme.js"),to:$t(n,"ttheme.js")},{from:$t(e.root,"bin","ttheme.js.map"),to:$t(n,"ttheme.js.map")},{from:$t(e.root,"shell","ttheme.zsh"),to:$t(n,"ttheme.zsh")},{from:$t(e.root,"shell","launch-tab.zsh"),to:$t(n,"launch-tab.zsh"),executable:!0}];rw(r,$t(e.root,"shell","adapters"),$t(n,"adapters"));let i=[{file:$t(e.zdotdir,".zshrc"),block:Zu(n)}],o=$t(n,"config.zsh"),s=Xu(Zt(o)?bn(o,"utf8"):""),c={file:o,content:s},u=[];if(t.terminals.includes("alacritty")){let f=Qe(e.configHome);if(Zt(f)&&Vn(bn(f,"utf8"),void 0)===void 0)u.push(`${f} already imports files under [general] — ttheme left it alone; add ${$t(e.configHome,"alacritty","themes")}/<palette>.toml to that import list yourself`)}if(t.terminals.includes("wezterm")){let f=on(e.configHome,e.home);if(Zt(f)&&Yn(bn(f,"utf8"),"")===void 0)u.push(`${f} has no \`return config\` line — ttheme left it alone; call \`dofile("${$t(n,"wezterm.lua")}")(config)\` from it yourself`)}let h=t.terminals.includes("windows-terminal");if(h&&!e.wtHome)u.push("windows terminal: %LOCALAPPDATA% was not found — drop the release fragment into its Fragments folder yourself");if(t.terminals.includes("warp"))u.push("warp: wears the default palette app-wide through its settings.toml — the shell layer stays off in it, since Warp paints no tab background of its own");let a={terminals:t.terminals,palettes:t.palettes,...h&&e.wtHome?{wtHome:e.wtHome}:{},...h&&e.wtProfile?{wtProfile:e.wtProfile}:{},...t.off?{off:!0}:{}};return u.push(...ua(e.configHome,t.terminals,e.home)),{home:e.home,copies:r,edits:i,settings:c,catalog:Wf(e.root),installed:a,notes:u}}function iw(t){try{return Jt(t).itermBase}catch{return}}function Kf(t,e=Ie()){for(let o of t.copies)if(Xo(wn(o.to),{recursive:!0}),Af(o.to,{force:!0}),Af(`${o.to}.zwc`,{force:!0}),D0(o.from,o.to),o.executable)B0(o.to,493);Xo(wn(t.settings.file),{recursive:!0}),ew(t.settings.file,t.settings.content);let n=wn(wn(t.settings.file)),r=iw(n),i=hr(r?{...t.installed,itermBase:r}:t.installed,e);ti(n,t.catalog),fr(n,i),lr(n,t.catalog,i,t.home);for(let o of t.edits){Xo(wn(o.file),{recursive:!0});let s=Zt(o.file)?bn(o.file,"utf8"):"";ir(o.file,_n(s,o.block))}return xe(i,e)}class Re extends Error{}function Vo(t){if(Ne(t))throw gn("nothing changed"),new Re;return t}function xf(t){return Wr.filter((e)=>{if(e==="iterm2")return process.platform==="darwin";if(e==="windows-terminal")return t.wtHome!==void 0;return e!=="warp"||process.platform!=="win32"})}function ow(t,e){if(t==="iterm2")return Zt($t(e.home,"Library","Application Support","iTerm2"));if(t==="windows-terminal")return e.wtHome!==void 0;if(t==="warp")return Zt(wn(oi(e.home)));if(t==="wezterm")return Zt($t(e.configHome,"wezterm"))||Zt($t(e.home,".wezterm.lua"));return Zt($t(e.configHome,t))}function sw(){if(process.platform==="win32")return process.env.LOCALAPPDATA;if(!process.env.WSL_DISTRO_NAME)return;let t=(e,n)=>Y0(e,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();try{return t("wslpath",["-u",t("cmd.exe",["/d","/c","echo %LOCALAPPDATA%"])])||void 0}catch{return}}async function cw(t,e,n){return Vo(await wf({message:"wire which terminals?",options:xf(n).map((r)=>({value:r,hint:r===t?"detected":void 0})),initialValues:e,required:!0}))}function Jf(t){let e=[...t.copies.filter((n)=>!Zt(n.to)).map((n)=>n.to),...Zt(t.settings.file)?[]:[t.settings.file],...t.edits.filter((n)=>!bn(n.file,"utf8").includes("# ttheme begin")).map((n)=>n.file)];if(e.length>0)throw Error(`init left gaps:
|
|
209
209
|
${e.join(`
|
|
210
|
-
`)}`)}function
|
|
211
|
-
`),`installed ${e.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(e.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(e.terminals.includes("kitty"))o.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(e.terminals.includes("alacritty"))o.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm"))o.push("wezterm reloads its config by itself");if(e.terminals.includes("windows-terminal"))o.push("windows terminal reloads its settings by itself");if(e.terminals.includes("iterm2"))o.push(...
|
|
212
|
-
`),"next"),
|
|
213
|
-
`))}async function
|
|
214
|
-
`),`wiring ${a.join(", ")}`),!
|
|
215
|
-
`),"uninstall");let i=await
|
|
216
|
-
`)}let e=
|
|
217
|
-
`)}async function
|
|
210
|
+
`)}`)}function Qf(t,e){return[...new Set(t.palettes.filter((n)=>e.includes(n.name)).map((n)=>n.group))]}function uw(t,e){let n=t.palettes.find((i)=>i.name===te(e)),r=process.stdout.isTTY===!0&&!br()&&!process.env.TMUX&&xr(process.env)!=="warp";if(!n||!r)return!1;return process.stdout.write(pi(n)),!0}function hw(t,e){let n=te(t);if(!n)return["default none — new tabs keep the terminal colors",`turn on \`ttheme on\` wears ${sn(t)}`];return[`default ${n}${e?" — this tab wears it already":""}`,"change it `ttheme preview`, enter on a palette, then default"]}function aw(t){z0("zsh",["-c",'source "$1" && __tt_preview init',"zsh",$t(t,"ttheme","ttheme.zsh")],{stdio:"inherit"})}function fw(t,e,n,r){let i=Qf(t.catalog,e.palettes);dn([`${i.join(", ")} (${e.palettes.length})`,...hw(t.installed,n)].join(`
|
|
211
|
+
`),`installed ${e.palettes.length} palettes`);let o=["exec zsh the ttheme command in this tab"];if(e.terminals.includes("ghostty"))o.push("restart ghostty new tabs pick up its config");if(e.terminals.includes("kitty"))o.push("new kitty window pictures follow it — kitty reloads its colors by itself");if(e.terminals.includes("alacritty"))o.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm"))o.push("wezterm reloads its config by itself");if(e.terminals.includes("windows-terminal"))o.push("windows terminal reloads its settings by itself");if(e.terminals.includes("iterm2"))o.push(...lw(te(t.installed),r));dn([...o,...t.notes].join(`
|
|
212
|
+
`),"next"),bf("done")}function lw(t,e){let n=['iterm2 profiles a "ttheme · <palette>" per palette in Settings › Profiles'];if(t)n.push(e?`restart iterm2 new tabs open on "ttheme · default", which wears ${t}`:`iterm2 default "ttheme · default" wears ${t} and follows \`ttheme default\``);return n}function gw(t,e){let n=[`placed ${t.copies.length} files`,`settings in ${t.settings.file} — edit later with \`ttheme config\``,...t.edits.map((r)=>`wired ${r.file}`)];if(e.terminals.includes("ghostty"))n.push("restart ghostty to pick up its config");if(e.terminals.includes("kitty"))n.push("kitty reloads its colors by itself; pictures show in kitty windows opened from now on");if(e.terminals.includes("alacritty"))n.push("alacritty reloads its config by itself");if(e.terminals.includes("wezterm")||e.terminals.includes("windows-terminal"))n.push("wezterm and windows terminal reload their config by themselves");if(e.terminals.includes("iterm2"))n.push('iterm2 gets a "ttheme · <palette>" profile per palette under Settings › Profiles');n.push(...t.notes),n.push("no palettes yet — open a new shell (`exec zsh`), then `ttheme browse` picks them from the catalog"),console.log(n.join(`
|
|
213
|
+
`))}async function Zf(t={}){let e=$t(import.meta.dirname,"..");if(!Zt($t(e,"bin","ttheme.js")))throw Error("bin/ttheme.js is missing — run `mise run bin:build` first");if(!Zt($t(e,"dist"))){if(typeof Bun>"u")throw Error("this package is missing dist/ — reinstall @kecan0406/ttheme");await _r()}let n=nw(),r=Pt(),i=process.env.ZDOTDIR??n,o=sw(),s=process.env.WT_PROFILE_ID,c={root:e,home:n,configHome:r,zdotdir:i,...o?{wtHome:o}:{},...s?{wtProfile:s}:{}},u=xr(process.env),h=xf(c).filter((p)=>p===u||ow(p,c));if(!t.yes&&(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0))throw Error("init asks before it edits your configs — run it in a terminal, or pass --yes to accept the defaults");if(t.yes){if(h.length===0)throw Error("no supported terminal detected — run this inside ghostty, kitty, alacritty, wezterm, iterm2, windows terminal or warp");let p={terminals:h,palettes:[]},j=Uf(p,c);Kf(j),Jf(j),gw(j,p);return}mi("ttheme init");let a=await cw(u,h,c),f=Wf(e),l=await Co(f,[],"series",!0);if(!l)throw gn("nothing changed"),new Re;let m=l[0],b=l.length>1&&xr(process.env)!=="warp",g=Vo(await wr({message:b?"pick a default palette in ttheme preview once installed?":`wear ${m} in every tab?`})),$={terminals:a,palettes:l,off:!g},y=Uf($,c);if(dn([`install ${l.length} palettes — ${Qf(y.catalog,l).join(", ")}`,`copy ${y.copies.length} files under ${r}`,`write ${y.settings.file}`,...y.edits.map((p)=>`edit ${p.file} — a ttheme block: source ttheme.zsh`),...ca(r,y.installed,n),"each config is backed up once to <file>.ttheme.bak before the first edit — `npx @kecan0406/ttheme uninstall` takes it all out",g?b?`open ttheme preview — every tab wears the palette picked there, ${m} until then`:`paint every tab with ${m}, this one now`:"leave the terminal colors as they are — `ttheme on` wears a palette later",...a.includes("iterm2")&&g?['make "ttheme · default" the iTerm2 default profile']:[]].join(`
|
|
214
|
+
`),`wiring ${a.join(", ")}`),!Vo(await wr({message:"apply these changes?"})))throw gn("nothing changed"),new Re;let F=Ie(),E=Kf(y,F);if(Jf(y),g&&b)aw(r);let v=Jt(r);fw({...y,installed:v},$,uw(y.catalog,v),E&&F.running())}import{existsSync as Yo,readdirSync as dw,readFileSync as mw,rmSync as pw,utimesSync as ww}from"node:fs";import{homedir as bw}from"node:os";import{dirname as $w,join as $n}from"node:path";function zo(t){return Yo(t)?mw(t,"utf8"):""}function kw(t){try{return Jt(t)}catch{return}}function Ew(t,e){let n=si(e,t),r=zo(n);if(!Qr(r)?.includes(`path = "${ct("")}`))return;return{file:n,content:Zr(r,zo(ko(t))||$o)}}function yw(t){let{home:e,configHome:n}=t,r=kw(n),i=[],o=(h,a)=>{let f=zo(h),l=a(f);if(l!==f)i.push({file:h,content:l})};o($n(t.zdotdir,".zshrc"),Cn),o(We("ghostty",n),Cn),o(We("kitty",n),Cn),o(Qe(n),Cn),o(on(n,e),Du);let s=Ew(n,e);if(s)i.push(s);let c=[];for(let h of["ghostty","kitty","alacritty","wezterm","warp"]){let a=Je(h,n,e);if(Yo(a))c.push(...dw(a).flatMap((f)=>f.startsWith(ct(""))?[$n(a,f)]:[]))}let u=[ar(e),...r?.wtHome?[$w(ci(r.wtHome))]:[],$n(n,"ttheme"),t.cacheDir,t.stateDir];return c.push(...u.filter((h)=>Yo(h))),{edits:i,removals:c,touches:r?.wtHome?Eo(r.wtHome):[],...r?{state:r}:{}}}function Mw(t,e=Ie()){let n=[];for(let{file:i,content:o}of t.edits){let s=Bh(i,o);n.push(s==="removed"?`removed ${i} — ttheme had created it`:s==="restored"?`took ttheme out of ${i}`:`took ttheme out of ${i} — kept ${i}.ttheme.bak, since the file changed after ttheme's first edit`)}if(t.state&&xe({...t.state,off:!0},e))n.push("gave iTerm2 its own default profile back — it takes it at its next start");for(let i of t.removals)pw(i,{recursive:!0,force:!0});if(t.removals.length>0)n.push(`deleted ${t.removals.length} files and folders ttheme wrote`);let r=new Date;for(let i of t.touches)ww(i,r,r);return n}function vw(){let t=bw();return{home:t,configHome:Pt(),zdotdir:process.env.ZDOTDIR??t,cacheDir:Kr(),stateDir:$n(process.env.XDG_STATE_HOME??$n(t,".local","state"),"ttheme")}}async function qf(t=!1){let e=vw(),n=yw(e);if(n.edits.length===0&&n.removals.length===0){console.log("nothing of ttheme is installed");return}if(!t){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)throw Error("uninstall asks before it deletes anything — run it in a terminal, or pass --yes");let r=$n(e.configHome,"ttheme");mi("ttheme uninstall"),dn([...n.edits.map((o)=>`take ttheme out of ${o.file}`),...n.removals.map((o)=>o===r?`delete ${o} — settings, pins and every installed picture`:`delete ${o}`)].join(`
|
|
215
|
+
`),"uninstall");let i=await wr({message:"remove ttheme?"});if(Ne(i)||!i)throw gn("nothing changed"),new Re}for(let r of Mw(n))console.log(r);console.log("open tabs keep their colors until they close — restart your terminal to drop ttheme everywhere")}var Iw={default:([t])=>Of(t),on:()=>Hf(),off:()=>jf(),browse:()=>Tf(),list:([t],{json:e})=>Gf(t,e),add:(t)=>Nf(t),remove:(t)=>Rf(t),update:()=>Lf(),init:(t,{yes:e})=>Zf({yes:e}),uninstall:(t,{yes:e})=>qf(e),build:(t,{only:e})=>_r({only:e}),find:([t])=>La(t),image:([t,e])=>Ta(t,e)},Xf=Jr.map((t)=>({...t,run:Iw[t.name]}));class Ze extends Error{verb;constructor(t,e){super(t);this.verb=e}}function _f(t){let e=Xf.find((n)=>n.name===t);if(!e)throw new Ze(t.startsWith("-")?`unknown option '${t}'`:`unknown command '${t}'`);return e}function Fw(t,e){let n={help:{type:"boolean",short:"h"}};for(let[r,{type:i,short:o,multiple:s}]of Object.entries(t.flags??{}))n[r]={type:i,multiple:s===!0,...o?{short:o}:{}};try{return Sw({args:e,options:n,allowPositionals:!0})}catch(r){let[i=""]=(r instanceof Error?r.message:String(r)).split(". ");throw new Ze(`${i.charAt(0).toLowerCase()}${i.slice(1)}`,t)}}function Nw(t){let[e,...n]=t;if(e===void 0)return{kind:"help",code:1};if(e==="-h"||e==="--help")return{kind:"help",code:0};if(e==="-V"||e==="--version")return{kind:"version"};if(e==="help")return n[0]===void 0?{kind:"help",code:0}:{kind:"help",verb:_f(n[0]),code:0};let r=_f(e),i=Fw(r,n);if(i.values.help)return{kind:"help",verb:r,code:0};for(let[a,{choices:f}]of Object.entries(r.flags??{}))for(let l of[i.values[a]??[]].flat())if(f&&!f.includes(String(l)))throw new Ze(`--${a} takes ${f.join(", ")} — not ${l}`,r);let o=i.positionals,s=r.args.filter((a)=>a.startsWith("<")).length,c=r.args.some((a)=>a.includes("..."))?Number.POSITIVE_INFINITY:r.args.length;if(o.length<s)throw new Ze(`missing ${r.args[o.length]}`,r);if(o.length>c)throw new Ze(`too many arguments: ${o.slice(c).join(" ")}`,r);let{help:u,...h}=i.values;return{kind:"run",verb:r,args:o,flags:h}}function Bo(t){let e=Object.entries(t.flags??{}).map(([n,{value:r}])=>`[--${n}${r?` ${r}`:""}]`);return[t.name,...e,...t.args].join(" ")}function Cf(t,e=Math.max(...t.map(([n])=>n.length))){return t.map(([n,r])=>` ${n.padEnd(e)} ${r}`)}var Rw=["tab","catalog","setup"];function Do(t){if(t){let i=Object.entries(t.flags??{}).map(([o,{short:s,value:c,about:u}])=>[`${s?`-${s}, `:""}--${o}${c?` ${c}`:""}`,u]);return[`Usage: ttheme ${Bo(t)}`,"",t.about,...i.length>0?["","Options:",...Cf(i)]:[]].join(`
|
|
216
|
+
`)}let e=Xf.filter((i)=>!i.hidden),n=(i)=>e.filter((o)=>o.section===i).map((o)=>[Bo(o),o.about]),r=Math.max(...e.map((i)=>Bo(i).length));return["Usage: ttheme <command>","",re.description,"","Commands:",...Rw.flatMap((i,o)=>[...o>0?[""]:[],...Cf(n(i),r)]),"","Examples:"," npx @kecan0406/ttheme init -y wire the terminals found here, no prompts"," ttheme add homura madoka install two palettes"," ttheme use homura paint this tab with one"," ttheme list --json madoka the madoka series as JSON","","ttheme <command> --help describes one command · ttheme --version prints the version","https://kecan0406.github.io/ttheme"].join(`
|
|
217
|
+
`)}async function Vf(t){let e;try{let n=Nw(t);if(n.kind==="version")return console.log(re.version),0;if(n.kind==="help"){if(n.code===0)console.log(Do(n.verb));else console.error(Do(n.verb));return n.code}if(e=n.verb,!n.verb.run)throw Error("runs in the shell layer — open a new tab once `ttheme init` has wired it");let r=await n.verb.run(n.args,n.flags);return typeof r==="number"?r:0}catch(n){if(n instanceof Ze)return console.error(`ttheme${n.verb?` ${n.verb.name}`:""}: ${n.message}
|
|
218
218
|
|
|
219
|
-
${
|
|
220
|
-
ttheme${e?` ${e.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(
|
|
219
|
+
${Do(n.verb)}`),1;if(n instanceof Re)return 1;let r=process.env.TTHEME_DEBUG&&n instanceof Error?n.stack:void 0;return console.error(`
|
|
220
|
+
ttheme${e?` ${e.name}`:""}: ${r??(n instanceof Error?n.message:String(n))}`),1}}if(Hw)if(process.env.TTHEME_DEBUG&&typeof Bun>"u"&&!process.sourceMapsEnabled){let t=Ow(process.execPath,["--enable-source-maps",...process.argv.slice(1)],{stdio:"inherit"});process.exitCode=t.status??1}else process.exitCode=await Vf(process.argv.slice(2));
|
|
221
221
|
|
|
222
|
-
//# debugId=
|
|
222
|
+
//# debugId=5394E729E31C45A464756E2164756E21
|
|
223
223
|
//# sourceMappingURL=ttheme.js.map
|