@stacksjs/bun-router 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/dist/chunk-03m2j6h7.js +2 -0
  2. package/dist/chunk-08cw7ejr.js +3 -0
  3. package/dist/chunk-0e4g0fyv.js +62 -0
  4. package/dist/chunk-0mmn02yw.js +2 -0
  5. package/dist/chunk-126c9qm3.js +2 -0
  6. package/dist/chunk-12p13817.js +2 -0
  7. package/dist/chunk-14v65c37.js +4 -0
  8. package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
  9. package/dist/chunk-1wenkmk0.js +2 -0
  10. package/dist/chunk-2152npfd.js +2 -0
  11. package/dist/chunk-26w23krx.js +2 -0
  12. package/dist/chunk-2g8m379z.js +10 -0
  13. package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
  14. package/dist/chunk-2w8f3swz.js +29 -0
  15. package/dist/chunk-3y4gaz7v.js +82 -0
  16. package/dist/chunk-4r1x4afz.js +12 -0
  17. package/dist/chunk-4wyw66zk.js +2 -0
  18. package/dist/chunk-4z5sf8ag.js +2 -0
  19. package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
  20. package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
  21. package/dist/chunk-5f0d9j9a.js +2 -0
  22. package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
  23. package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
  24. package/dist/chunk-6dmqtdnq.js +2 -0
  25. package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
  26. package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
  27. package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
  28. package/dist/chunk-7y72hm1x.js +2 -0
  29. package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
  30. package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
  31. package/dist/chunk-8wydx2we.js +2 -0
  32. package/dist/chunk-8zjnjvv7.js +2 -0
  33. package/dist/chunk-988h4bzr.js +2 -0
  34. package/dist/chunk-9b6a58ac.js +2 -0
  35. package/dist/chunk-a8fcaywb.js +2 -0
  36. package/dist/chunk-bfjwn7yg.js +2 -0
  37. package/dist/chunk-bp2522mm.js +2 -0
  38. package/dist/chunk-bswe62q4.js +48 -0
  39. package/dist/chunk-c3v796c8.js +943 -0
  40. package/dist/chunk-ccqmwdry.js +2 -0
  41. package/dist/chunk-ck0crwnx.js +2 -0
  42. package/dist/chunk-cqgkxcb4.js +2 -0
  43. package/dist/chunk-dntnakjy.js +2 -0
  44. package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
  45. package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
  46. package/dist/chunk-ezx3qsez.js +2 -0
  47. package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
  48. package/dist/chunk-fna5n0ey.js +246 -0
  49. package/dist/chunk-fqhckdt8.js +2 -0
  50. package/dist/chunk-fr6hbx25.js +2 -0
  51. package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
  52. package/dist/chunk-gd3za5x0.js +2 -0
  53. package/dist/chunk-gf28608k.js +2 -0
  54. package/dist/chunk-h1dj6v8q.js +3 -0
  55. package/dist/chunk-hjxe7k2g.js +2 -0
  56. package/dist/chunk-hrkgznbn.js +2 -0
  57. package/dist/chunk-j6h5v0br.js +2 -0
  58. package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
  59. package/dist/chunk-n24c9whp.js +2 -0
  60. package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
  61. package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
  62. package/dist/chunk-p0qhpnqh.js +70 -0
  63. package/dist/chunk-p0w1x8y2.js +3 -0
  64. package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
  65. package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
  66. package/dist/chunk-q5dv1kyy.js +2 -0
  67. package/dist/chunk-qnqgf9tq.js +2 -0
  68. package/dist/chunk-qvwy1808.js +898 -0
  69. package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
  70. package/dist/chunk-r63za1mr.js +2 -0
  71. package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
  72. package/dist/chunk-ryvmyskt.js +4211 -0
  73. package/dist/chunk-sa6mx308.js +2 -0
  74. package/dist/chunk-va0pc7hx.js +2 -0
  75. package/dist/chunk-vcp8dnjq.js +412 -0
  76. package/dist/chunk-vg1erq1q.js +2 -0
  77. package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
  78. package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
  79. package/dist/chunk-xj9h6mc9.js +2 -0
  80. package/dist/chunk-ytvzwrq3.js +51 -0
  81. package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
  82. package/dist/chunk-zmqsv2xy.js +2 -0
  83. package/dist/cli.js +57 -66
  84. package/dist/container/index.js +1 -1
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.js +29 -29
  87. package/dist/typed/client.d.ts +89 -0
  88. package/dist/typed/contract.d.ts +34 -0
  89. package/dist/typed/endpoint.d.ts +90 -0
  90. package/dist/typed/index.d.ts +14 -0
  91. package/dist/typed/router.d.ts +141 -0
  92. package/package.json +1 -1
  93. package/dist/chunk-30rkn2ym.js +0 -2
  94. package/dist/chunk-38cmrard.js +0 -2
  95. package/dist/chunk-3qna6dwd.js +0 -2
  96. package/dist/chunk-4d5fmta0.js +0 -2
  97. package/dist/chunk-4x3b4b4q.js +0 -2
  98. package/dist/chunk-6xed4va1.js +0 -2
  99. package/dist/chunk-748n6ydj.js +0 -2
  100. package/dist/chunk-7rsf8tes.js +0 -898
  101. package/dist/chunk-8aspmtf1.js +0 -2
  102. package/dist/chunk-8yfdg595.js +0 -2
  103. package/dist/chunk-90eze7av.js +0 -3
  104. package/dist/chunk-9dvwyej7.js +0 -2
  105. package/dist/chunk-a2w45krb.js +0 -2
  106. package/dist/chunk-a547f2ab.js +0 -48
  107. package/dist/chunk-bqdycvtc.js +0 -2
  108. package/dist/chunk-cd03rk3x.js +0 -2
  109. package/dist/chunk-ct0m17q5.js +0 -2
  110. package/dist/chunk-dhbvvr5h.js +0 -2
  111. package/dist/chunk-dhptcsya.js +0 -943
  112. package/dist/chunk-dq93zag9.js +0 -2
  113. package/dist/chunk-edrtesh7.js +0 -2
  114. package/dist/chunk-ejcws37w.js +0 -2
  115. package/dist/chunk-ex890p45.js +0 -51
  116. package/dist/chunk-f69cpnhw.js +0 -2
  117. package/dist/chunk-fjf53b44.js +0 -2
  118. package/dist/chunk-fjzye4qj.js +0 -2
  119. package/dist/chunk-gfd23b6t.js +0 -2
  120. package/dist/chunk-habv0vef.js +0 -12
  121. package/dist/chunk-hz6fc788.js +0 -2
  122. package/dist/chunk-jff6j9y3.js +0 -10
  123. package/dist/chunk-jmeb7n8k.js +0 -70
  124. package/dist/chunk-jy2jhcpy.js +0 -246
  125. package/dist/chunk-m249t3je.js +0 -3
  126. package/dist/chunk-m9yabnjx.js +0 -2
  127. package/dist/chunk-mekrq9wd.js +0 -2
  128. package/dist/chunk-mmxv535f.js +0 -82
  129. package/dist/chunk-mypn7jss.js +0 -2
  130. package/dist/chunk-n18x1k3c.js +0 -2
  131. package/dist/chunk-nkddjzsa.js +0 -2
  132. package/dist/chunk-pjmhqmr9.js +0 -2
  133. package/dist/chunk-qyrnsaq1.js +0 -2
  134. package/dist/chunk-r19ff2qm.js +0 -62
  135. package/dist/chunk-r338fssq.js +0 -2
  136. package/dist/chunk-s36z58x2.js +0 -29
  137. package/dist/chunk-s79dd325.js +0 -471
  138. package/dist/chunk-ta38j9em.js +0 -2
  139. package/dist/chunk-tpfgntwj.js +0 -4211
  140. package/dist/chunk-vw8rwv6e.js +0 -2
  141. package/dist/chunk-wcrqs5z9.js +0 -2
  142. package/dist/chunk-x6d1rmwa.js +0 -2
  143. package/dist/chunk-x7ft15zz.js +0 -2
  144. package/dist/chunk-x8trwn7j.js +0 -3
  145. package/dist/chunk-xhepdj1f.js +0 -2
  146. package/dist/chunk-xv2em0q4.js +0 -4
  147. package/dist/chunk-ypw6g0te.js +0 -2
  148. package/dist/chunk-z8szsm21.js +0 -2
  149. package/dist/chunk-zfbh14qe.js +0 -2
  150. /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
@@ -1,63 +1,63 @@
1
1
  // @bun
2
- import{a as rD,b as nD,c as oD,d as sD,e as iD,f as aD,g as cD,h as lD,i as dD,j as uD,k as pD,l as fD}from"./chunk-r19ff2qm.js";import{m as Yl,n as Kl}from"./chunk-x8trwn7j.js";import{o as jM,p as RM,q as MM,r as DM,s as PM,t as OM}from"./chunk-5ncn73tp.js";import{A as Ws,B as Vs,C as ul,D as pl,E as JM,F as YM,G as KM,H as GM,I as qr,J as Mi,K as Di,L as Sf,M as Pi,N as Oi,O as Ii,P as Li,Q as Fi,R as ZM,S as QM,T as eD,U as xi,V as tD,u as XM,v as tl,w as Hs,x as oo,y as zr,z as Ur}from"./chunk-a547f2ab.js";import"./chunk-vr10sbbh.js";import"./chunk-sw0chtw4.js";import"./chunk-xg9xscqz.js";import{Td as sM,Ud as iM,Vd as aM,Wd as cM,Xd as lM,Yd as dM}from"./chunk-9ght4n4r.js";import{$d as pM,_d as uM,ae as fM,be as mM,ce as hM,de as gM,ee as yM,fe as xM,ge as bM,he as wM,ie as vM,je as $M,ke as SM,le as kM}from"./chunk-ex5fkjah.js";import{ne as Rg,oe as Mg,pe as Dg,qe as Pg}from"./chunk-xv2em0q4.js";import{ve as Jl}from"./chunk-5s1pr62n.js";import{we as DR}from"./chunk-vv3gb1m5.js";import{xe as PR,ye as OR}from"./chunk-kjtjbcq4.js";import{Ae as LR,Be as FR,Ce as NR,De as BR,Ee as zR,ze as IR}from"./chunk-7qnxdedn.js";import{Fe as UR,Ge as HR,He as WR,Ie as VR,Je as qR}from"./chunk-9805tt8n.js";import{Ke as XR,Le as JR,Me as YR,Ne as KR,Oe as GR}from"./chunk-vsh4390q.js";import{Pe as ZR,Qe as QR,Re as eM,Se as tM,Te as rM,Ue as nM,Ve as oM}from"./chunk-8wpj3fqe.js";import{We as bR,Xe as wR}from"./chunk-6s1kbajm.js";import{$e as Ut,Ze as yr,_e as zt,af as Ln,bf as Fn,cf as Ko,df as FT,ef as Go,ff as NT,gf as BT,hf as zT,if as UT,jf as HT,kf as WT,lf as VT,mf as qT,nf as XT,of as JT,pf as YT}from"./chunk-m249t3je.js";import{Af as AR,qf as vR,rf as $R,sf as SR,tf as kR,uf as TR,vf as CR,wf as ER,xf as _R,yf as Ir,zf as Lr}from"./chunk-6sjvhy5f.js";import{Bf as Xg,Cf as Jg}from"./chunk-hmgedrmr.js";import{Ef as Yg}from"./chunk-zhx0hxdd.js";import"./chunk-e3qej0jr.js";import{Jf as Ct}from"./chunk-dxg045wj.js";import{Kf as xj,Lf as bj,Mf as wj,Nf as vj,Of as $j,Pf as Sj,Qf as kj,Rf as Tj,Sf as Cj,Tf as Ej,Uf as _j,Vf as Aj,Wf as jj,Xf as Rj}from"./chunk-zetqzgf3.js";import{$f as jg,$g as QC,$h as dE,$i as t_,$j as H_,$k as oj,$l as pR,Ag as kC,Ah as Fa,Ai as Ms,Aj as b_,Ak as gA,Al as Hj,Am as EM,Bg as TC,Bh as Na,Bi as jE,Bj as w_,Bk as yA,Bl as Wj,Bm as _M,Cg as CC,Ch as Ba,Ci as RE,Cj as v_,Ck as xA,Cl as qg,Cm as AM,Dg as EC,Dh as za,Di as ME,Dj as $_,Dk as bA,Dl as Vj,Dm as IM,Eg as _C,Eh as Ua,Ei as DE,Ej as S_,Ek as wA,El as qj,Em as LM,Fg as AC,Fh as Ha,Fi as PE,Fj as Re,Fk as vA,Fl as Xj,Fm as FM,Gg as jC,Gh as Wa,Gi as OE,Gj as k_,Gk as $A,Gl as Jj,Gm as NM,Hg as RC,Hh as Va,Hi as IE,Hj as T_,Hk as FA,Hl as Yj,Hm as BM,Ig as MC,Ih as qa,Ii as LE,Ij as C_,Ik as NA,Il as nl,Im as zM,Jg as DC,Jh as Xa,Ji as FE,Jj as E_,Jk as BA,Jl as Kj,Jm as UM,Kg as PC,Kh as Ja,Ki as NE,Kj as po,Kk as zA,Kl as Gj,Km as ws,Lg as OC,Lh as Ya,Li as BE,Lj as __,Lk as UA,Ll as Zj,Lm as Vt,Mg as IC,Mh as Ka,Mi as zE,Mj as yo,Mk as HA,Ml as Qj,Mm as HM,Ng as LC,Nh as Ga,Ni as UE,Nj as A_,Nk as WA,Nl as eR,Nm as WM,Og as FC,Oh as Za,Oi as HE,Oj as eo,Ok as VA,Ol as tR,Om as VM,Pg as NC,Ph as Qa,Pi as WE,Pj as Wg,Pk as qA,Pl as zs,Pm as ct,Qg as BC,Qh as ec,Qi as VE,Qj as j_,Qk as XA,Ql as Us,Qm as qM,Rg as zC,Rh as tc,Ri as qE,Rj as R_,Rk as JA,Rl as rR,Sg as UC,Sh as rc,Si as Or,Sj as M_,Sk as YA,Sl as nR,Tg as HC,Th as nc,Ti as XE,Tj as D_,Tk as KA,Tl as oR,Ug as WC,Uh as Lm,Ui as JE,Uj as P_,Uk as GA,Ul as sR,Vg as VC,Vh as Fm,Vi as YE,Vj as O_,Vk as ZA,Vl as iR,Wg as qC,Wh as Nm,Wi as KE,Wj as Bs,Wk as QA,Wl as aR,Xg as XC,Xh as Bm,Xi as GE,Xj as I_,Xk as ej,Xl as cR,Yf as Eg,Yg as JC,Yh as aE,Yi as ZE,Yj as $e,Yk as tj,Yl as lR,Zf as _g,Zg as YC,Zh as cE,Zi as QE,Zj as L_,Zk as rj,Zl as dR,_f as Ag,_g as KC,_h as lE,_i as e_,_j as F_,_k as nj,_l as uR,ag as KT,ah as eE,ai as uE,aj as r_,ak as W_,al as sj,am as fR,bg as GT,bh as tE,bi as pE,bj as n_,bk as V_,bl as ij,bm as mR,cg as ZT,ch as rE,ci as wr,cj as o_,ck as q_,cl as aj,cm as hR,dg as QT,dh as nE,di as fE,dj as Dt,dk as X_,dl as cj,dm as gR,eg as os,eh as oE,ei as mE,ej as s_,ek as J_,el as lj,em as yR,fg as eC,fh as Hc,fi as Rs,fj as it,fk as Y_,fl as dj,fm as no,gg as tC,gh as Wc,gi as hE,gj as je,gk as K_,gl as uj,gm as xR,hg as rC,hh as sE,hi as gE,hj as i_,hk as G_,hl as pj,hm as Wr,ig as nC,ih as iE,ii as yE,ij as a_,ik as Z_,il as fj,im as Fr,jg as oC,jh as va,ji as xE,jj as c_,jk as Q_,jl as mj,kg as sC,kh as $a,ki as bE,kj as l_,kk as eA,kl as hj,lg as iC,lh as Sa,li as wE,lj as d_,lk as tA,ll as gj,mg as aC,mh as ka,mi as vE,mj as u_,mk as rA,ml as yj,ng as cC,nh as Ta,ni as Gn,nj as p_,nk as nA,nl as kt,oh as Ca,oi as $E,oj as f_,ok as oA,ol as Vg,ph as Ea,pi as Zn,pj as Xc,pk as sA,qg as lC,qh as _a,qi as SE,qj as m_,qk as iA,rg as dC,rh as Aa,ri as kE,rj as sn,rk as aA,rl as Oj,sg as gC,sh as ja,si as vr,sj as h_,sk as cA,sl as Ij,tg as yC,th as Ra,ti as TE,tj as g_,tk as lA,tl as at,ug as xC,uh as Ma,ui as CE,uj as y_,uk as dA,ul as Lj,um as jR,vg as bC,vh as Da,vi as EE,vj as x_,vk as uA,vl as Fj,vm as RR,wg as wC,wh as Pa,wi as Qn,wj as go,wk as pA,wl as Nj,wm as MR,xg as vC,xh as Oa,xi as _E,xj as Gt,xk as fA,xl as Bj,xm as se,yg as $C,yh as Ia,yi as AE,yk as mA,yl as zj,ym as TM,zg as SC,zh as La,zi as Pr,zk as hA,zl as Uj,zm as CM}from"./chunk-tpfgntwj.js";import{Rm as uC,Sm as pC,Tm as fC,Um as mC,Vm as ke,Wm as hC,Xm as Ng,Ym as Bg,Zm as m,_m as zg,dn as Nr,en as Br,gn as Ug,hn as Hg,in as re}from"./chunk-jff6j9y3.js";import"./chunk-csfrpsp7.js";import{An as Mj,Cn as Dj,Dn as Pj,nn as bs,qn as N_,rn as B_,sn as z_,tn as U_,yn as te}from"./chunk-0t5vz87j.js";import{En as SA,Fn as kA,Gn as Tu,Hn as TA,In as CA,Jn as EA,Kn as _A,Ln as AA,Mn as jA,Nn as RA,On as MA,Pn as DA,Qn as PA,Rn as OA,Sn as IA,Tn as LA}from"./chunk-krkchy8v.js";import{Un as Ri}from"./chunk-brpgjyqg.js";import{Ao as id,Bo as ad,Co as cd,Do as Bn,Eo as zn,Fo as Un,Go as Hn,Ho as Wn,Io as Vn,Ko as Hr,eo as GC,fo as ZC,ho as xo,io as ro,jo as Os,no as Fs,oo as Ns,uo as ed,vo as td,wo as rd,xo as nd,yo as od,zo as sd}from"./chunk-5mxby3fd.js";import{Mo as Og,No as Ig}from"./chunk-5be9x5cq.js";import"./chunk-jmeb7n8k.js";import"./chunk-kc659vhx.js";import{ds as Ie,es as Le,fs as Fe,gs as Pn,hs as Ve,is as qe,js as ql,ls as Bt,ms as dr,ns as ur,os as pr,ps as mr,qs as We,rs as On,ss as In,ts as Xl}from"./chunk-90eze7av.js";import"./chunk-jy2jhcpy.js";import{lu as wm,mu as vm,nu as $m,ru as Sm,su as km,tu as Tm}from"./chunk-hz6fc788.js";import{Au as Mm,Bu as Dm,Cu as Pm,Du as Om,Eu as Im,uu as Cm,vu as Em,wu as _m,xu as Am,yu as jm,zu as Rm}from"./chunk-s36z58x2.js";import{Fu as dm,Gu as um,Hu as pm,Iu as fm,Ju as mm,Lu as hm,Mu as gm,Nu as ym,Ou as xm,Pu as bm}from"./chunk-5n0ckcmc.js";import{Qu as Lg,Su as Fg}from"./chunk-6bbmkwng.js";import{Zu as B}from"./chunk-a3wahyg7.js";import ht from"fs";import Sn from"path";var kn="_stx";function wl(e){return Bun.hash(e).toString(16).slice(0,8)}function vl(e){let t=[],r=(n)=>{for(let o of ht.readdirSync(n,{withFileTypes:!0})){let s=Sn.join(n,o.name);if(o.isDirectory())r(s);else if(o.isFile()&&s.endsWith(".html"))t.push(s)}};if(ht.existsSync(e))r(e);return t}var $l=[{pattern:/<script\b([^>]*\bdata-stx-runtime\b[^>]*)>([\s\S]*?)<\/script>/gi,prefix:"runtime",extension:"js",contentType:"text/javascript; charset=utf-8",replace:(e)=>`<script data-stx-runtime src="${e}"></script>`},{pattern:/<script\b([^>]*\bdata-stx-router\b[^>]*)>([\s\S]*?)<\/script>/gi,prefix:"router",extension:"js",contentType:"text/javascript; charset=utf-8",replace:(e)=>`<script data-stx-router src="${e}"></script>`},{pattern:/<style\b([^>]*\bdata-crosswind=(?:"generated"|'generated')[^>]*)>([\s\S]*?)<\/style>/gi,prefix:"crosswind",extension:"css",contentType:"text/css; charset=utf-8",replace:(e)=>`<link data-crosswind="generated" rel="stylesheet" href="${e}">`}];function Yo(e,t=`/${kn}`){let r=[],n=new Set,o=0,s=e;for(let i of $l)s=s.replace(i.pattern,(a,c,l)=>{if(/\b(?:src|href)\s*=/.test(c)||!l.trim())return a;let d=`${i.prefix}.${wl(l)}.${i.extension}`;if(!n.has(d))n.add(d),r.push({filename:d,contents:l,contentType:i.contentType});return o+=l.length,i.replace(`${t}/${d}`)});return{html:s,assets:r,bytesInlined:o}}function Tn(e){let t={pages:0,assets:0,bytesInlined:0},r=Sn.join(e,kn),n=new Set;for(let o of vl(e)){let s=ht.readFileSync(o,"utf8"),{html:i,assets:a,bytesInlined:c}=Yo(s);if(i===s)continue;for(let l of a){if(n.has(l.filename))continue;n.add(l.filename),ht.mkdirSync(r,{recursive:!0}),ht.writeFileSync(Sn.join(r,l.filename),l.contents),t.assets++}ht.writeFileSync(o,i),t.bytesInlined+=c,t.pages++}return t}var Zo={read:(e)=>{try{return JSON.parse(e)}catch{return e}},write:(e)=>{return JSON.stringify(e)}};function Sl(e,t,r={}){let{storage:n="local",serializer:o=Zo,mergeDefaults:s=!1,listenToStorageChanges:i=!0}=r,a=new Set,c=typeof window<"u",l=()=>{if(!c)return null;return n==="session"?sessionStorage:localStorage},d=()=>{let g=l();if(!g)return t;try{let x=g.getItem(e);if(x===null)return t;let y=o.read(x);if(s&&typeof t==="object"&&t!==null)return{...t,...y};return y}catch{return t}},u=(g)=>{let x=l();if(!x)return;try{if(g===null||g===void 0)x.removeItem(e);else x.setItem(e,o.write(g))}catch(y){console.warn(`[useStorage] Failed to write key "${e}":`,y)}},p=d(),h=(g,x)=>{for(let y of a)try{y(g,x)}catch(b){console.error("[useStorage] Subscriber error:",b)}};if(c&&i){let g=(y)=>{if(y.key===e&&y.storageArea===l()){let b=p;try{p=y.newValue?o.read(y.newValue):t}catch(w){console.warn(`[useStorage] Failed to read key "${e}" from a cross-tab update:`,w);return}h(p,b)}};window.addEventListener("storage",g);let x=globalThis.onDestroy;if(typeof x==="function")x(()=>window.removeEventListener("storage",g))}let f={get value(){return p},set value(g){let x=p;p=g,u(g),h(g,x)},get:()=>p,set:(g)=>{f.value=g},remove:()=>{let g=l();if(g){g.removeItem(e);let x=p;p=t,h(t,x)}},subscribe:(g)=>{return a.add(g),g(p,void 0),()=>a.delete(g)}};return f}function Qo(e,t,r,n,o={}){let{serializer:s=Zo,mergeDefaults:i=!1,listenToStorageChanges:a=!0}=o,c=typeof window<"u",l=()=>{if(!c)return null;return e==="session"?sessionStorage:localStorage},d=(p)=>{if(p===null||p===void 0)return n;try{let h=s.read(p);if(i&&typeof n==="object"&&n!==null)return{...n,...h};return h}catch(h){return console.warn(`[${t}] Failed to read key "${r}":`,h),n}},u=Ko((()=>{let p=l();if(!p)return n;try{return d(p.getItem(r))}catch(h){return console.warn(`[${t}] Cannot read "${r}":`,h),n}})());if(Go(()=>{let p=u(),h=l();if(!h)return;try{if(p===null||p===void 0)h.removeItem(r);else h.setItem(r,s.write(p))}catch(f){console.warn(`[${t}] Cannot persist "${r}":`,f)}}),c&&a){let p=(f)=>{if(f.key!==r)return;if(f.storageArea&&f.storageArea!==l())return;u.set(d(f.newValue))};window.addEventListener("storage",p);let h=globalThis.onDestroy;if(typeof h==="function")h(()=>window.removeEventListener("storage",p))}return u}function kl(e,t,r){return Qo("local","useLocalStorage",e,t,r)}function Tl(e,t,r){return Qo("session","useSessionStorage",e,t,r)}function Cl(e="local"){if(typeof window>"u")return;(e==="session"?sessionStorage:localStorage).clear()}function El(e="local"){if(typeof window>"u")return[];let t=e==="session"?sessionStorage:localStorage;return Object.keys(t)}function _l(e="local"){if(typeof window>"u")return 0;let t=e==="session"?sessionStorage:localStorage,r=0;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))r+=(n.length+(t.getItem(n)?.length||0))*2;return r}import ts from"fs";import Mn from"path";function Cn(e){let{token:t,baseUrl:r="https://api.netlify.com/api/v1"}=e;async function n(o,s,i={}){let a=`${r}${s}`,c={Authorization:`Bearer ${t}`,"User-Agent":"stx-deploy/1.0"},l;if(i.rawBody)c["Content-Type"]=i.contentType||"application/octet-stream",l=i.rawBody;else if(i.body)c["Content-Type"]="application/json",l=JSON.stringify(i.body);let d=await fetch(a,{method:o,headers:c,body:l});if(!d.ok){let p=Error(`Netlify API error: ${d.status} ${d.statusText}`);p.status=d.status;try{let h=await d.json();p.message=h.message||p.message,p.code=h.code,p.details=h}catch{}throw p}let u=await d.text();if(!u)return{};return JSON.parse(u)}return{async getSite(o){return n("GET",`/sites/${o}`)},async listSites(){return n("GET","/sites")},async createSite(o){let s={};if(o)s.name=o;return n("POST","/sites",{body:s})},async createDeploy(o,s){let i={files:s.files,draft:s.draft??!0,async:s.async??!0};if(s.title)i.title=s.title;if(s.branch)i.branch=s.branch;if(s.functions)i.functions=s.functions;return n("POST",`/sites/${o}/deploys`,{body:i})},async uploadFile(o,s,i){let a=s.startsWith("/")?s.slice(1):s;await n("PUT",`/deploys/${o}/files/${a}`,{rawBody:i,contentType:"application/octet-stream"})},async uploadFiles(o,s){let a=[...s],c=async()=>{while(a.length>0){let d=a.shift();if(d)await this.uploadFile(o,d.path,d.content)}},l=Array.from({length:Math.min(5,s.length)},()=>c());await Promise.all(l)},async getDeploy(o){return n("GET",`/deploys/${o}`)},async waitForDeploy(o,s={}){let{timeout:i=300000,pollInterval:a=2000,onProgress:c}=s,l=Date.now();while(!0){let d=await this.getDeploy(o);if(c)c(d);if(d.state==="ready")return d;if(d.state==="error"){let u=Error(`Deploy failed: ${d.error_message||"Unknown error"}`);throw u.status=500,u.details=d,u}if(Date.now()-l>i){let u=Error(`Deploy timed out after ${i}ms`);throw u.status=408,u.details=d,u}await new Promise((u)=>setTimeout(u,a))}},async lockDeploy(o){return n("POST",`/deploys/${o}/lock`)},async unlockDeploy(o){return n("POST",`/deploys/${o}/unlock`)}}}async function es(e){let t=await crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(t)).map((r)=>r.toString(16).padStart(2,"0")).join("")}async function ar(e,t={}){let{ignore:r=["node_modules",".git",".env*","*.map"]}=t,n=[],o=new Bun.Glob("**/*");for await(let s of o.scan({cwd:e,onlyFiles:!0,dot:!1})){if(r.some((l)=>{if(l.includes("*"))return new RegExp(`^${l.replace(/\*/g,".*")}$`).test(s);return s.includes(l)}))continue;let i=`${e}/${s}`,a=await Bun.file(i).arrayBuffer(),c=await es(a);n.push({path:s,content:new Uint8Array(a),sha1:c})}return n}function En(e){let t={};for(let r of e)t[`/${r.path}`]=r.sha1;return t}function _n(e,t){let r=new Set(t.map((n)=>n.startsWith("/")?n.slice(1):n));return e.filter((n)=>r.has(n.path))}function gt(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}function ot(e){return e.reduce((t,r)=>t+r.content.byteLength,0)}import Oe from"fs";import Ae from"path";function An(e){let t=[];if(t.push("[build]"),t.push(` command = "${Q(e.build.command)}"`),t.push(` publish = "${Q(e.build.publish)}"`),e.build.functions)t.push(` functions = "${Q(e.build.functions)}"`);if(e.build.edge_functions)t.push(` edge_functions = "${Q(e.build.edge_functions)}"`);if(e.build.environment&&Object.keys(e.build.environment).length>0){t.push(""),t.push("[build.environment]");for(let[r,n]of Object.entries(e.build.environment))t.push(` ${r} = "${Q(n)}"`)}if(e.functions){if(t.push(""),t.push("[functions]"),e.functions.directory)t.push(` directory = "${Q(e.functions.directory)}"`);if(e.functions.node_bundler)t.push(` node_bundler = "${e.functions.node_bundler}"`);if(e.functions.external_node_modules&&e.functions.external_node_modules.length>0)t.push(` external_node_modules = [${e.functions.external_node_modules.map((r)=>`"${r}"`).join(", ")}]`)}if(e.edge_functions&&e.edge_functions.length>0){t.push("");for(let r of e.edge_functions)t.push("[[edge_functions]]"),t.push(` function = "${Q(r.function)}"`),t.push(` path = "${Q(r.path)}"`)}if(e.redirects&&e.redirects.length>0){t.push("");for(let r of e.redirects){if(t.push("[[redirects]]"),t.push(` from = "${Q(r.from)}"`),t.push(` to = "${Q(r.to)}"`),r.status!==void 0)t.push(` status = ${r.status}`);if(r.force!==void 0)t.push(` force = ${r.force}`);if(r.conditions&&Object.keys(r.conditions).length>0){t.push(" [redirects.conditions]");for(let[n,o]of Object.entries(r.conditions))t.push(` ${n} = "${Q(o)}"`)}}}if(e.headers&&e.headers.length>0){t.push("");for(let r of e.headers){t.push("[[headers]]"),t.push(` for = "${Q(r.for)}"`),t.push(" [headers.values]");for(let[n,o]of Object.entries(r.values))t.push(` ${n} = "${Q(o)}"`)}}if(e.plugins&&e.plugins.length>0){t.push("");for(let r of e.plugins)if(t.push("[[plugins]]"),t.push(` package = "${Q(r.package)}"`),r.inputs&&Object.keys(r.inputs).length>0){t.push(" [plugins.inputs]");for(let[n,o]of Object.entries(r.inputs))if(typeof o==="string")t.push(` ${n} = "${Q(o)}"`);else if(typeof o==="boolean"||typeof o==="number")t.push(` ${n} = ${o}`)}}if(e.context&&Object.keys(e.context).length>0)for(let[r,n]of Object.entries(e.context)){if(t.push(""),t.push(`[context.${r}]`),n.command)t.push(` command = "${Q(n.command)}"`);if(n.publish)t.push(` publish = "${Q(n.publish)}"`);if(n.environment&&Object.keys(n.environment).length>0){t.push(` [context.${r}.environment]`);for(let[o,s]of Object.entries(n.environment))t.push(` ${o} = "${Q(s)}"`)}}return t.join(`
2
+ import{a as nD,b as oD,c as sD,d as iD,e as aD,f as cD,g as lD,h as dD,i as uD,j as pD,k as fD,l as mD}from"./chunk-0e4g0fyv.js";import{m as Kl,n as Gl}from"./chunk-08cw7ejr.js";import{o as RM,p as MM,q as DM,r as PM,s as OM,t as IM}from"./chunk-8kfzygg5.js";import{A as Vs,B as qs,C as pl,D as fl,E as YM,F as KM,G as GM,H as ZM,I as Xr,J as Di,K as Pi,L as kf,M as Oi,N as Ii,O as Li,P as Fi,Q as Ni,R as QM,S as eD,T as tD,U as bi,V as rD,u as JM,v as rl,w as Ws,x as so,y as Ur,z as Hr}from"./chunk-bswe62q4.js";import"./chunk-g9cwng6w.js";import"./chunk-sw0chtw4.js";import"./chunk-xg9xscqz.js";import{Td as iM,Ud as aM,Vd as cM,Wd as lM,Xd as dM,Yd as uM}from"./chunk-p3dk1w2w.js";import{$d as fM,_d as pM,ae as mM,be as hM,ce as gM,de as yM,ee as xM,fe as bM,ge as wM,he as vM,ie as $M,je as SM,ke as kM,le as TM}from"./chunk-5dp83qcx.js";import{ne as Mg,oe as Dg,pe as Pg,qe as Og}from"./chunk-14v65c37.js";import{ve as Yl}from"./chunk-6e91956t.js";import{we as PR}from"./chunk-nhmtg01n.js";import{xe as OR,ye as IR}from"./chunk-kjtjbcq4.js";import{Ae as FR,Be as NR,Ce as BR,De as zR,Ee as UR,ze as LR}from"./chunk-7qnxdedn.js";import{Fe as HR,Ge as WR,He as VR,Ie as qR,Je as XR}from"./chunk-9805tt8n.js";import{Ke as JR,Le as YR,Me as KR,Ne as GR,Oe as ZR}from"./chunk-vsh4390q.js";import{Pe as QR,Qe as eM,Re as tM,Se as rM,Te as nM,Ue as oM,Ve as sM}from"./chunk-8wpj3fqe.js";import{We as wR,Xe as vR}from"./chunk-rft8gw92.js";import{$e as Ht,Ze as xr,_e as Ut,af as Fn,bf as Nn,cf as Go,df as NT,ef as Zo,ff as BT,gf as zT,hf as UT,if as HT,jf as WT,kf as VT,lf as qT,mf as XT,nf as JT,of as YT,pf as KT}from"./chunk-p0w1x8y2.js";import{Af as jR,qf as $R,rf as SR,sf as kR,tf as TR,uf as CR,vf as ER,wf as _R,xf as AR,yf as Lr,zf as Fr}from"./chunk-q4e9pxs7.js";import{Bf as Jg,Cf as Yg}from"./chunk-w0jv49ch.js";import{Ef as Kg}from"./chunk-5z52b0fc.js";import"./chunk-e3qej0jr.js";import{Jf as Et}from"./chunk-dxg045wj.js";import{Kf as bj,Lf as wj,Mf as vj,Nf as $j,Of as Sj,Pf as kj,Qf as Tj,Rf as Cj,Sf as Ej,Tf as _j,Uf as Aj,Vf as jj,Wf as Rj,Xf as Mj}from"./chunk-8hbhfh6b.js";import{$f as Rg,$g as eE,$h as uE,$i as r_,$j as W_,$k as sj,$l as fR,Ag as TC,Ah as Na,Ai as Ds,Aj as w_,Ak as yA,Al as Wj,Am as _M,Bg as CC,Bh as Ba,Bi as RE,Bj as v_,Bk as xA,Bl as Vj,Bm as AM,Cg as EC,Ch as za,Ci as ME,Cj as $_,Ck as bA,Cl as Xg,Cm as jM,Dg as _C,Dh as Ua,Di as DE,Dj as S_,Dk as wA,Dl as qj,Dm as LM,Eg as AC,Eh as Ha,Ei as PE,Ej as k_,Ek as vA,El as Xj,Em as FM,Fg as jC,Fh as Wa,Fi as OE,Fj as Me,Fk as $A,Fl as Jj,Fm as NM,Gg as RC,Gh as Va,Gi as IE,Gj as T_,Gk as SA,Gl as Yj,Gm as BM,Hg as MC,Hh as qa,Hi as LE,Hj as C_,Hk as NA,Hl as Kj,Hm as zM,Ig as DC,Ih as Xa,Ii as FE,Ij as E_,Ik as BA,Il as ol,Im as UM,Jg as PC,Jh as Ja,Ji as NE,Jj as __,Jk as zA,Jl as Gj,Jm as HM,Kg as OC,Kh as Ya,Ki as BE,Kj as fo,Kk as UA,Kl as Zj,Km as vs,Lg as IC,Lh as Ka,Li as zE,Lj as A_,Lk as HA,Ll as Qj,Lm as qt,Mg as LC,Mh as Ga,Mi as UE,Mj as xo,Mk as WA,Ml as eR,Mm as WM,Ng as FC,Nh as Za,Ni as HE,Nj as j_,Nk as VA,Nl as tR,Nm as VM,Og as NC,Oh as Qa,Oi as WE,Oj as to,Ok as qA,Ol as rR,Om as qM,Pg as BC,Ph as ec,Pi as VE,Pj as Vg,Pk as XA,Pl as Us,Pm as lt,Qg as zC,Qh as tc,Qi as qE,Qj as R_,Qk as JA,Ql as Hs,Qm as XM,Rg as UC,Rh as rc,Ri as XE,Rj as M_,Rk as YA,Rl as nR,Sg as HC,Sh as nc,Si as Ir,Sj as D_,Sk as KA,Sl as oR,Tg as WC,Th as oc,Ti as JE,Tj as P_,Tk as GA,Tl as sR,Ug as VC,Uh as Fm,Ui as YE,Uj as O_,Uk as ZA,Ul as iR,Vg as qC,Vh as Nm,Vi as KE,Vj as I_,Vk as QA,Vl as aR,Wg as XC,Wh as Bm,Wi as GE,Wj as zs,Wk as ej,Wl as cR,Xg as JC,Xh as zm,Xi as ZE,Xj as L_,Xk as tj,Xl as lR,Yf as _g,Yg as YC,Yh as cE,Yi as QE,Yj as Se,Yk as rj,Yl as dR,Zf as Ag,Zg as KC,Zh as lE,Zi as e_,Zj as F_,Zk as nj,Zl as uR,_f as jg,_g as GC,_h as dE,_i as t_,_j as N_,_k as oj,_l as pR,ag as GT,ah as tE,ai as pE,aj as n_,ak as V_,al as ij,am as mR,bg as ZT,bh as rE,bi as fE,bj as o_,bk as q_,bl as aj,bm as hR,cg as QT,ch as nE,ci as vr,cj as s_,ck as X_,cl as cj,cm as gR,dg as eC,dh as oE,di as mE,dj as Pt,dk as J_,dl as lj,dm as yR,eg as ss,eh as sE,ei as hE,ej as i_,ek as Y_,el as dj,em as xR,fg as tC,fh as Wc,fi as Ms,fj as at,fk as K_,fl as uj,fm as oo,gg as rC,gh as Vc,gi as gE,gj as Re,gk as G_,gl as pj,gm as bR,hg as nC,hh as iE,hi as yE,hj as a_,hk as Z_,hl as fj,hm as Vr,ig as oC,ih as aE,ii as xE,ij as c_,ik as Q_,il as mj,im as Nr,jg as sC,jh as $a,ji as bE,jj as l_,jk as eA,jl as hj,kg as iC,kh as Sa,ki as wE,kj as d_,kk as tA,kl as gj,lg as aC,lh as ka,li as vE,lj as u_,lk as rA,ll as yj,mg as cC,mh as Ta,mi as $E,mj as p_,mk as nA,ml as xj,ng as lC,nh as Ca,ni as Zn,nj as f_,nk as oA,nl as Tt,oh as Ea,oi as SE,oj as m_,ok as sA,ol as qg,ph as _a,pi as Qn,pj as Jc,pk as iA,qg as dC,qh as Aa,qi as kE,qj as h_,qk as aA,rg as uC,rh as ja,ri as TE,rj as an,rk as cA,rl as Ij,sg as yC,sh as Ra,si as $r,sj as g_,sk as lA,sl as Lj,tg as xC,th as Ma,ti as CE,tj as y_,tk as dA,tl as ct,ug as bC,uh as Da,ui as EE,uj as x_,uk as uA,ul as Fj,um as RR,vg as wC,vh as Pa,vi as _E,vj as b_,vk as pA,vl as Nj,vm as MR,wg as vC,wh as Oa,wi as eo,wj as yo,wk as fA,wl as Bj,wm as DR,xg as $C,xh as Ia,xi as AE,xj as Zt,xk as mA,xl as zj,xm as ie,yg as SC,yh as La,yi as jE,yk as hA,yl as Uj,ym as CM,zg as kC,zh as Fa,zi as Or,zk as gA,zl as Hj,zm as EM}from"./chunk-ryvmyskt.js";import{Rm as pC,Sm as fC,Tm as mC,Um as hC,Vm as Te,Wm as gC,Xm as Bg,Ym as zg,Zm as m,_m as Ug,dn as Br,en as zr,gn as Hg,hn as Wg,in as ne}from"./chunk-2g8m379z.js";import"./chunk-ezqwq17j.js";import{An as Dj,Cn as Pj,Dn as Oj,nn as ws,qn as B_,rn as z_,sn as U_,tn as H_,yn as re}from"./chunk-wm805tte.js";import{En as kA,Fn as TA,Gn as Cu,Hn as CA,In as EA,Jn as _A,Kn as AA,Ln as jA,Mn as RA,Nn as MA,On as DA,Pn as PA,Qn as OA,Rn as IA,Sn as LA,Tn as FA}from"./chunk-58tfvayh.js";import{Un as Mi}from"./chunk-brpgjyqg.js";import{Ao as ad,Bo as cd,Co as ld,Do as zn,Eo as Un,Fo as Hn,Go as Wn,Ho as Vn,Io as qn,Ko as Wr,eo as ZC,fo as QC,ho as bo,io as no,jo as Is,no as Ns,oo as Bs,uo as td,vo as rd,wo as nd,xo as od,yo as sd,zo as id}from"./chunk-2rr178et.js";import{Mo as Ig,No as Lg}from"./chunk-5be9x5cq.js";import"./chunk-5zrnk2kq.js";import"./chunk-p0qhpnqh.js";import{ds as Le,es as Fe,fs as Ne,gs as On,hs as qe,is as Xe,js as Xl,ls as zt,ms as ur,ns as pr,os as fr,ps as hr,qs as Ve,rs as In,ss as Ln,ts as Jl}from"./chunk-h1dj6v8q.js";import"./chunk-fna5n0ey.js";import{lu as vm,mu as $m,nu as Sm,ru as km,su as Tm,tu as Cm}from"./chunk-126c9qm3.js";import{Au as Dm,Bu as Pm,Cu as Om,Du as Im,Eu as Lm,uu as Em,vu as _m,wu as Am,xu as jm,yu as Rm,zu as Mm}from"./chunk-2w8f3swz.js";import{Fu as um,Gu as pm,Hu as fm,Iu as mm,Ju as hm,Lu as gm,Mu as ym,Nu as xm,Ou as bm,Pu as wm}from"./chunk-6x1feysm.js";import{Qu as Fg,Su as Ng}from"./chunk-6bbmkwng.js";import{Zu as z}from"./chunk-nf3kv7kv.js";import gt from"fs";import kn from"path";var Tn="_stx";function vl(e){return Bun.hash(e).toString(16).slice(0,8)}function $l(e){let t=[],r=(n)=>{for(let o of gt.readdirSync(n,{withFileTypes:!0})){let s=kn.join(n,o.name);if(o.isDirectory())r(s);else if(o.isFile()&&s.endsWith(".html"))t.push(s)}};if(gt.existsSync(e))r(e);return t}var Sl=[{pattern:/<script\b([^>]*\bdata-stx-runtime\b[^>]*)>([\s\S]*?)<\/script>/gi,prefix:"runtime",extension:"js",contentType:"text/javascript; charset=utf-8",replace:(e)=>`<script data-stx-runtime src="${e}"></script>`},{pattern:/<script\b([^>]*\bdata-stx-router\b[^>]*)>([\s\S]*?)<\/script>/gi,prefix:"router",extension:"js",contentType:"text/javascript; charset=utf-8",replace:(e)=>`<script data-stx-router src="${e}"></script>`},{pattern:/<style\b([^>]*\bdata-crosswind=(?:"generated"|'generated')[^>]*)>([\s\S]*?)<\/style>/gi,prefix:"crosswind",extension:"css",contentType:"text/css; charset=utf-8",replace:(e)=>`<link data-crosswind="generated" rel="stylesheet" href="${e}">`}];function Ko(e,t=`/${Tn}`){let r=[],n=new Set,o=0,s=e;for(let i of Sl)s=s.replace(i.pattern,(a,c,l)=>{if(/\b(?:src|href)\s*=/.test(c)||!l.trim())return a;let d=`${i.prefix}.${vl(l)}.${i.extension}`;if(!n.has(d))n.add(d),r.push({filename:d,contents:l,contentType:i.contentType});return o+=l.length,i.replace(`${t}/${d}`)});return{html:s,assets:r,bytesInlined:o}}function Cn(e){let t={pages:0,assets:0,bytesInlined:0},r=kn.join(e,Tn),n=new Set;for(let o of $l(e)){let s=gt.readFileSync(o,"utf8"),{html:i,assets:a,bytesInlined:c}=Ko(s);if(i===s)continue;for(let l of a){if(n.has(l.filename))continue;n.add(l.filename),gt.mkdirSync(r,{recursive:!0}),gt.writeFileSync(kn.join(r,l.filename),l.contents),t.assets++}gt.writeFileSync(o,i),t.bytesInlined+=c,t.pages++}return t}var Qo={read:(e)=>{try{return JSON.parse(e)}catch{return e}},write:(e)=>JSON.stringify(e)};function kl(e,t,r={}){let{storage:n="local",serializer:o=Qo,mergeDefaults:s=!1,listenToStorageChanges:i=!0}=r,a=new Set,c=typeof window<"u",l=()=>{if(!c)return null;return n==="session"?sessionStorage:localStorage},d=()=>{let g=l();if(!g)return t;try{let x=g.getItem(e);if(x===null)return t;let y=o.read(x);if(s&&typeof t==="object"&&t!==null)return{...t,...y};return y}catch{return t}},u=(g)=>{let x=l();if(!x)return;try{if(g===null||g===void 0)x.removeItem(e);else x.setItem(e,o.write(g))}catch(y){console.warn(`[useStorage] Failed to write key "${e}":`,y)}},p=d(),h=(g,x)=>{for(let y of a)try{y(g,x)}catch(b){console.error("[useStorage] Subscriber error:",b)}};if(c&&i){let g=(y)=>{if(y.key===e&&y.storageArea===l()){let b=p;try{p=y.newValue?o.read(y.newValue):t}catch(w){console.warn(`[useStorage] Failed to read key "${e}" from a cross-tab update:`,w);return}h(p,b)}};window.addEventListener("storage",g);let x=globalThis.onDestroy;if(typeof x==="function")x(()=>window.removeEventListener("storage",g))}let f={get value(){return p},set value(g){let x=p;p=g,u(g),h(g,x)},get:()=>p,set:(g)=>{f.value=g},remove:()=>{let g=l();if(g){g.removeItem(e);let x=p;p=t,h(t,x)}},subscribe:(g)=>(a.add(g),g(p,void 0),()=>a.delete(g))};return f}function es(e,t,r,n,o={}){let{serializer:s=Qo,mergeDefaults:i=!1,listenToStorageChanges:a=!0}=o,c=typeof window<"u",l=()=>{if(!c)return null;return e==="session"?sessionStorage:localStorage},d=(p)=>{if(p===null||p===void 0)return n;try{let h=s.read(p);if(i&&typeof n==="object"&&n!==null)return{...n,...h};return h}catch(h){return console.warn(`[${t}] Failed to read key "${r}":`,h),n}},u=Go((()=>{let p=l();if(!p)return n;try{return d(p.getItem(r))}catch(h){return console.warn(`[${t}] Cannot read "${r}":`,h),n}})());if(Zo(()=>{let p=u(),h=l();if(!h)return;try{if(p===null||p===void 0)h.removeItem(r);else h.setItem(r,s.write(p))}catch(f){console.warn(`[${t}] Cannot persist "${r}":`,f)}}),c&&a){let p=(f)=>{if(f.key!==r)return;if(f.storageArea&&f.storageArea!==l())return;u.set(d(f.newValue))};window.addEventListener("storage",p);let h=globalThis.onDestroy;if(typeof h==="function")h(()=>window.removeEventListener("storage",p))}return u}function Tl(e,t,r){return es("local","useLocalStorage",e,t,r)}function Cl(e,t,r){return es("session","useSessionStorage",e,t,r)}function El(e="local"){if(typeof window>"u")return;(e==="session"?sessionStorage:localStorage).clear()}function _l(e="local"){if(typeof window>"u")return[];let t=e==="session"?sessionStorage:localStorage;return Object.keys(t)}function Al(e="local"){if(typeof window>"u")return 0;let t=e==="session"?sessionStorage:localStorage,r=0;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))r+=(n.length+(t.getItem(n)?.length||0))*2;return r}import rs from"fs";import Dn from"path";function En(e){let{token:t,baseUrl:r="https://api.netlify.com/api/v1"}=e;async function n(o,s,i={}){let a=`${r}${s}`,c={Authorization:`Bearer ${t}`,"User-Agent":"stx-deploy/1.0"},l;if(i.rawBody)c["Content-Type"]=i.contentType||"application/octet-stream",l=i.rawBody;else if(i.body)c["Content-Type"]="application/json",l=JSON.stringify(i.body);let d=await fetch(a,{method:o,headers:c,body:l});if(!d.ok){let p=Error(`Netlify API error: ${d.status} ${d.statusText}`);p.status=d.status;try{let h=await d.json();p.message=h.message||p.message,p.code=h.code,p.details=h}catch{}throw p}let u=await d.text();if(!u)return{};return JSON.parse(u)}return{async getSite(o){return n("GET",`/sites/${o}`)},async listSites(){return n("GET","/sites")},async createSite(o){let s={};if(o)s.name=o;return n("POST","/sites",{body:s})},async createDeploy(o,s){let i={files:s.files,draft:s.draft??!0,async:s.async??!0};if(s.title)i.title=s.title;if(s.branch)i.branch=s.branch;if(s.functions)i.functions=s.functions;return n("POST",`/sites/${o}/deploys`,{body:i})},async uploadFile(o,s,i){let a=s.startsWith("/")?s.slice(1):s;await n("PUT",`/deploys/${o}/files/${a}`,{rawBody:i,contentType:"application/octet-stream"})},async uploadFiles(o,s){let a=[...s],c=async()=>{while(a.length>0){let d=a.shift();if(d)await this.uploadFile(o,d.path,d.content)}},l=Array.from({length:Math.min(5,s.length)},()=>c());await Promise.all(l)},async getDeploy(o){return n("GET",`/deploys/${o}`)},async waitForDeploy(o,s={}){let{timeout:i=300000,pollInterval:a=2000,onProgress:c}=s,l=Date.now();while(!0){let d=await this.getDeploy(o);if(c)c(d);if(d.state==="ready")return d;if(d.state==="error"){let u=Error(`Deploy failed: ${d.error_message||"Unknown error"}`);throw u.status=500,u.details=d,u}if(Date.now()-l>i){let u=Error(`Deploy timed out after ${i}ms`);throw u.status=408,u.details=d,u}await new Promise((u)=>setTimeout(u,a))}},async lockDeploy(o){return n("POST",`/deploys/${o}/lock`)},async unlockDeploy(o){return n("POST",`/deploys/${o}/unlock`)}}}async function ts(e){let t=await crypto.subtle.digest("SHA-1",e);return Array.from(new Uint8Array(t)).map((r)=>r.toString(16).padStart(2,"0")).join("")}async function cr(e,t={}){let{ignore:r=["node_modules",".git",".env*","*.map"]}=t,n=[],o=new Bun.Glob("**/*");for await(let s of o.scan({cwd:e,onlyFiles:!0,dot:!1})){if(r.some((l)=>{if(l.includes("*"))return new RegExp(`^${l.replace(/\*/g,".*")}$`).test(s);return s.includes(l)}))continue;let i=`${e}/${s}`,a=await Bun.file(i).arrayBuffer(),c=await ts(a);n.push({path:s,content:new Uint8Array(a),sha1:c})}return n}function _n(e){let t={};for(let r of e)t[`/${r.path}`]=r.sha1;return t}function An(e,t){let r=new Set(t.map((n)=>n.startsWith("/")?n.slice(1):n));return e.filter((n)=>r.has(n.path))}function yt(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}function st(e){return e.reduce((t,r)=>t+r.content.byteLength,0)}import Ie from"fs";import je from"path";function jn(e){let t=[];if(t.push("[build]"),t.push(` command = "${ee(e.build.command)}"`),t.push(` publish = "${ee(e.build.publish)}"`),e.build.functions)t.push(` functions = "${ee(e.build.functions)}"`);if(e.build.edge_functions)t.push(` edge_functions = "${ee(e.build.edge_functions)}"`);if(e.build.environment&&Object.keys(e.build.environment).length>0){t.push(""),t.push("[build.environment]");for(let[r,n]of Object.entries(e.build.environment))t.push(` ${r} = "${ee(n)}"`)}if(e.functions){if(t.push(""),t.push("[functions]"),e.functions.directory)t.push(` directory = "${ee(e.functions.directory)}"`);if(e.functions.node_bundler)t.push(` node_bundler = "${e.functions.node_bundler}"`);if(e.functions.external_node_modules&&e.functions.external_node_modules.length>0)t.push(` external_node_modules = [${e.functions.external_node_modules.map((r)=>`"${r}"`).join(", ")}]`)}if(e.edge_functions&&e.edge_functions.length>0){t.push("");for(let r of e.edge_functions)t.push("[[edge_functions]]"),t.push(` function = "${ee(r.function)}"`),t.push(` path = "${ee(r.path)}"`)}if(e.redirects&&e.redirects.length>0){t.push("");for(let r of e.redirects){if(t.push("[[redirects]]"),t.push(` from = "${ee(r.from)}"`),t.push(` to = "${ee(r.to)}"`),r.status!==void 0)t.push(` status = ${r.status}`);if(r.force!==void 0)t.push(` force = ${r.force}`);if(r.conditions&&Object.keys(r.conditions).length>0){t.push(" [redirects.conditions]");for(let[n,o]of Object.entries(r.conditions))t.push(` ${n} = "${ee(o)}"`)}}}if(e.headers&&e.headers.length>0){t.push("");for(let r of e.headers){t.push("[[headers]]"),t.push(` for = "${ee(r.for)}"`),t.push(" [headers.values]");for(let[n,o]of Object.entries(r.values))t.push(` ${n} = "${ee(o)}"`)}}if(e.plugins&&e.plugins.length>0){t.push("");for(let r of e.plugins)if(t.push("[[plugins]]"),t.push(` package = "${ee(r.package)}"`),r.inputs&&Object.keys(r.inputs).length>0){t.push(" [plugins.inputs]");for(let[n,o]of Object.entries(r.inputs))if(typeof o==="string")t.push(` ${n} = "${ee(o)}"`);else if(typeof o==="boolean"||typeof o==="number")t.push(` ${n} = ${o}`)}}if(e.context&&Object.keys(e.context).length>0)for(let[r,n]of Object.entries(e.context)){if(t.push(""),t.push(`[context.${r}]`),n.command)t.push(` command = "${ee(n.command)}"`);if(n.publish)t.push(` publish = "${ee(n.publish)}"`);if(n.environment&&Object.keys(n.environment).length>0){t.push(` [context.${r}.environment]`);for(let[o,s]of Object.entries(n.environment))t.push(` ${o} = "${ee(s)}"`)}}return t.join(`
3
3
  `)+`
4
- `}function Q(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}async function cr(e){let t={framework:"stx",buildCommand:"bun run build",outputDir:"dist"},r=Ae.join(e,"package.json");if(await Bun.file(r).exists())try{let l=JSON.parse(await Bun.file(r).text());if(l.scripts?.build)t.buildCommand="bun run build";let d={...l.dependencies,...l.devDependencies};if(d["@stacksjs/stx"]||d.stx)t.framework="stx"}catch{}let n=Ae.join(e,"stx.config.ts"),o=Ae.join(e,".config","stx.config.ts");if(await Bun.file(n).exists()||await Bun.file(o).exists())t.framework="stx";let s=["dist","build","out","public",".output"];for(let l of s){let d=Ae.join(e,l);if(Oe.existsSync(d)&&Oe.statSync(d).isDirectory()){t.outputDir=l;break}}let i=["functions","netlify/functions","api"];for(let l of i){let d=Ae.join(e,l);if(Oe.existsSync(d)&&Oe.statSync(d).isDirectory()){t.functionsDir=l;break}}let a=Ae.join(e,"netlify","edge-functions");if(Oe.existsSync(a))t.edgeFunctionsDir="netlify/edge-functions";let c=Ae.join(e,t.outputDir||"dist");if(Oe.existsSync(c)){let l=Oe.existsSync(Ae.join(c,"index.html")),d=Oe.readdirSync(c).filter((u)=>u.endsWith(".html"));t.isSPA=l&&d.length===1}return t}function lr(e={}){let t={build:{command:e.buildCommand||"bun run build",publish:e.outputDir||"dist"}};if(e.functionsDir)t.build.functions=e.functionsDir,t.functions={directory:e.functionsDir,node_bundler:"esbuild"};if(e.edgeFunctionsDir)t.build.edge_functions=e.edgeFunctionsDir;if(t.headers=[{for:"/*",values:{"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"}},{for:"/assets/*",values:{"Cache-Control":"public, max-age=31536000, immutable"}}],e.isSPA!==!1)t.redirects=[{from:"/*",to:"/index.html",status:200}];return t.context={production:{environment:{NODE_ENV:"production"}},"deploy-preview":{environment:{NODE_ENV:"development"}}},t}async function jn(e,t){let r=await cr(e),n=t||lr(r),o=An(n),s=Ae.join(e,"netlify.toml");return await Bun.write(s,o),s}function Rn(e){return Oe.existsSync(Ae.join(e,"netlify.toml"))}async function ly(e={}){let t=Date.now(),r=[],n=e.cwd||process.cwd(),o=(y)=>{r.push(y)},s=(y)=>{if(e.onProgress)e.onProgress(y)},i=Mn.resolve(n,e.directory||"dist"),a=e.token||process.env.NETLIFY_AUTH_TOKEN,c=e.siteId||process.env.NETLIFY_SITE_ID;if(!a)throw new st(`No Netlify auth token found.
4
+ `}function ee(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}async function lr(e){let t={framework:"stx",buildCommand:"bun run build",outputDir:"dist"},r=je.join(e,"package.json");if(await Bun.file(r).exists())try{let l=JSON.parse(await Bun.file(r).text());if(l.scripts?.build)t.buildCommand="bun run build";let d={...l.dependencies,...l.devDependencies};if(d["@stacksjs/stx"]||d.stx)t.framework="stx"}catch{}let n=je.join(e,"stx.config.ts"),o=je.join(e,".config","stx.config.ts");if(await Bun.file(n).exists()||await Bun.file(o).exists())t.framework="stx";let s=["dist","build","out","public",".output"];for(let l of s){let d=je.join(e,l);if(Ie.existsSync(d)&&Ie.statSync(d).isDirectory()){t.outputDir=l;break}}let i=["functions","netlify/functions","api"];for(let l of i){let d=je.join(e,l);if(Ie.existsSync(d)&&Ie.statSync(d).isDirectory()){t.functionsDir=l;break}}let a=je.join(e,"netlify","edge-functions");if(Ie.existsSync(a))t.edgeFunctionsDir="netlify/edge-functions";let c=je.join(e,t.outputDir||"dist");if(Ie.existsSync(c)){let l=Ie.existsSync(je.join(c,"index.html")),d=Ie.readdirSync(c).filter((u)=>u.endsWith(".html"));t.isSPA=l&&d.length===1}return t}function dr(e={}){let t={build:{command:e.buildCommand||"bun run build",publish:e.outputDir||"dist"}};if(e.functionsDir)t.build.functions=e.functionsDir,t.functions={directory:e.functionsDir,node_bundler:"esbuild"};if(e.edgeFunctionsDir)t.build.edge_functions=e.edgeFunctionsDir;if(t.headers=[{for:"/*",values:{"X-Frame-Options":"DENY","X-Content-Type-Options":"nosniff","X-XSS-Protection":"1; mode=block","Referrer-Policy":"strict-origin-when-cross-origin"}},{for:"/assets/*",values:{"Cache-Control":"public, max-age=31536000, immutable"}}],e.isSPA!==!1)t.redirects=[{from:"/*",to:"/index.html",status:200}];return t.context={production:{environment:{NODE_ENV:"production"}},"deploy-preview":{environment:{NODE_ENV:"development"}}},t}async function Rn(e,t){let r=await lr(e),n=t||dr(r),o=jn(n),s=je.join(e,"netlify.toml");return await Bun.write(s,o),s}function Mn(e){return Ie.existsSync(je.join(e,"netlify.toml"))}async function dy(e={}){let t=Date.now(),r=[],n=e.cwd||process.cwd(),o=(y)=>{r.push(y)},s=(y)=>{if(e.onProgress)e.onProgress(y)},i=Dn.resolve(n,e.directory||"dist"),a=e.token||process.env.NETLIFY_AUTH_TOKEN,c=e.siteId||process.env.NETLIFY_SITE_ID;if(!a)throw new it(`No Netlify auth token found.
5
5
 
6
6
  To deploy to Netlify:
7
7
  1. Create account at https://app.netlify.com
8
8
  2. Get token at https://app.netlify.com/user/applications#personal-access-tokens
9
9
  3. Set NETLIFY_AUTH_TOKEN environment variable
10
10
 
11
- export NETLIFY_AUTH_TOKEN=your_token_here`,"NO_TOKEN");if(!c)throw new st(`No Netlify site ID found.
11
+ export NETLIFY_AUTH_TOKEN=your_token_here`,"NO_TOKEN");if(!c)throw new it(`No Netlify site ID found.
12
12
 
13
13
  Either:
14
14
  1. Set NETLIFY_SITE_ID environment variable
15
15
  2. Pass --site-id option
16
16
  3. Run \`stx deploy --init\` to set up
17
17
 
18
- Find your site ID at: https://app.netlify.com/sites/YOUR_SITE/settings/general`,"NO_SITE_ID");if(!ts.existsSync(i))throw new st(`Build directory not found: ${i}
18
+ Find your site ID at: https://app.netlify.com/sites/YOUR_SITE/settings/general`,"NO_SITE_ID");if(!rs.existsSync(i))throw new it(`Build directory not found: ${i}
19
19
 
20
- Run \`stx build\` first or specify a different directory with --directory`,"NO_BUILD_DIR");if(!(ts.readdirSync(i).length>0))throw new st(`Build directory is empty: ${i}
20
+ Run \`stx build\` first or specify a different directory with --directory`,"NO_BUILD_DIR");if(!(rs.readdirSync(i).length>0))throw new it(`Build directory is empty: ${i}
21
21
 
22
- Run \`stx build\` to generate files`,"EMPTY_BUILD_DIR");if(e.dryRun){s({stage:"collect",message:"Collecting files..."});let y=await ar(i),b=ot(y);return o(`Would deploy ${y.length} files (${gt(b)})`),o(`From: ${i}`),o(`To: Site ${c}`),o(`Mode: ${e.production?"production":"draft"}`),{success:!0,url:`https://${c}.netlify.app (dry-run)`,deployId:"dry-run",logs:r,duration:Date.now()-t,filesUploaded:y.length,totalSize:b}}let l=Cn({token:a});s({stage:"collect",message:"Verifying site..."});try{let y=await l.getSite(c);o(`Deploying to: ${y.name} (${y.url})`)}catch(y){if(y.status===404)throw new st(`Site not found: ${c}
22
+ Run \`stx build\` to generate files`,"EMPTY_BUILD_DIR");if(e.dryRun){s({stage:"collect",message:"Collecting files..."});let y=await cr(i),b=st(y);return o(`Would deploy ${y.length} files (${yt(b)})`),o(`From: ${i}`),o(`To: Site ${c}`),o(`Mode: ${e.production?"production":"draft"}`),{success:!0,url:`https://${c}.netlify.app (dry-run)`,deployId:"dry-run",logs:r,duration:Date.now()-t,filesUploaded:y.length,totalSize:b}}let l=En({token:a});s({stage:"collect",message:"Verifying site..."});try{let y=await l.getSite(c);o(`Deploying to: ${y.name} (${y.url})`)}catch(y){if(y.status===404)throw new it(`Site not found: ${c}
23
23
 
24
- Check your site ID or create a new site at https://app.netlify.com`,"SITE_NOT_FOUND");throw y}s({stage:"collect",message:"Collecting files..."});let d=await ar(i),u=ot(d);if(o(`Found ${d.length} files (${gt(u)})`),d.length===0)throw new st(`No files found in ${i}`,"NO_FILES");let p=En(d);s({stage:"upload",message:"Creating deploy...",percent:0});let h=await l.createDeploy(c,{title:e.message||"Deploy from stx CLI",draft:!e.production,files:p});o(`Created deploy: ${h.id}`);let f=_n(d,h.required||[]);if(o(`Uploading ${f.length} files...`),f.length>0){let y=0,b=ot(f);for(let w of f){await l.uploadFile(h.id,w.path,w.content),y++;let v=Math.round(y/f.length*100);s({stage:"upload",message:`Uploading: ${w.path}`,percent:v,details:{uploaded:y,total:f.length}})}o(`Uploaded ${gt(b)}`)}else o("All files already on CDN (no upload needed)");s({stage:"process",message:"Processing deploy..."});let g=await l.waitForDeploy(h.id,{onProgress:(y)=>{s({stage:"process",message:`Status: ${y.state}`,details:y})}}),x=Date.now()-t;if(s({stage:"done",message:"Deploy complete!"}),o(`Deploy complete in ${(x/1000).toFixed(1)}s`),o(`URL: ${g.deploy_ssl_url}`),e.production)o(`Site: ${g.ssl_url}`);if(e.open){let y=e.production?g.ssl_url:g.deploy_ssl_url;Al(y)}return{success:!0,url:g.deploy_ssl_url,siteUrl:e.production?g.ssl_url:void 0,deployId:g.id,logs:r,duration:x,filesUploaded:f.length,totalSize:ot(f)}}async function dy(e={}){let t=e.directory||process.cwd(),r;if(Rn(t))r=Mn.join(t,"netlify.toml");else{let n=await cr(t);r=await jn(t,lr(n))}if(e.siteId){let n=Mn.join(t,".env.local"),o="";if(await Bun.file(n).exists()){if(o=await Bun.file(n).text(),o=o.split(`
24
+ Check your site ID or create a new site at https://app.netlify.com`,"SITE_NOT_FOUND");throw y}s({stage:"collect",message:"Collecting files..."});let d=await cr(i),u=st(d);if(o(`Found ${d.length} files (${yt(u)})`),d.length===0)throw new it(`No files found in ${i}`,"NO_FILES");let p=_n(d);s({stage:"upload",message:"Creating deploy...",percent:0});let h=await l.createDeploy(c,{title:e.message||"Deploy from stx CLI",draft:!e.production,files:p});o(`Created deploy: ${h.id}`);let f=An(d,h.required||[]);if(o(`Uploading ${f.length} files...`),f.length>0){let y=0,b=st(f);for(let w of f){await l.uploadFile(h.id,w.path,w.content),y++;let v=Math.round(y/f.length*100);s({stage:"upload",message:`Uploading: ${w.path}`,percent:v,details:{uploaded:y,total:f.length}})}o(`Uploaded ${yt(b)}`)}else o("All files already on CDN (no upload needed)");s({stage:"process",message:"Processing deploy..."});let g=await l.waitForDeploy(h.id,{onProgress:(y)=>{s({stage:"process",message:`Status: ${y.state}`,details:y})}}),x=Date.now()-t;if(s({stage:"done",message:"Deploy complete!"}),o(`Deploy complete in ${(x/1000).toFixed(1)}s`),o(`URL: ${g.deploy_ssl_url}`),e.production)o(`Site: ${g.ssl_url}`);if(e.open){let y=e.production?g.ssl_url:g.deploy_ssl_url;jl(y)}return{success:!0,url:g.deploy_ssl_url,siteUrl:e.production?g.ssl_url:void 0,deployId:g.id,logs:r,duration:x,filesUploaded:f.length,totalSize:st(f)}}async function uy(e={}){let t=e.directory||process.cwd(),r;if(Mn(t))r=Dn.join(t,"netlify.toml");else{let n=await lr(t);r=await Rn(t,dr(n))}if(e.siteId){let n=Dn.join(t,".env.local"),o="";if(await Bun.file(n).exists()){if(o=await Bun.file(n).text(),o=o.split(`
25
25
  `).filter((s)=>!s.startsWith("NETLIFY_SITE_ID=")).join(`
26
26
  `),o&&!o.endsWith(`
27
27
  `))o+=`
28
28
  `}o+=`NETLIFY_SITE_ID=${e.siteId}
29
- `,await Bun.write(n,o)}return{configPath:r,siteId:e.siteId}}class st extends Error{code;constructor(e,t){super(e);this.name="DeployError",this.code=t}}function Al(e){let t=process.platform,r=t==="darwin"?"open":t==="win32"?"start":"xdg-open";Bun.spawn([r,e],{stdio:["ignore","ignore","ignore"]})}function jl(e,t={}){let{src:r,alt:n,width:o,height:s,sizes:i="100vw",loading:a="lazy",priority:c=!1,quality:l=Fe,placeholder:d="none",formats:u=Le,widths:p=Ie,decoding:h="async",fetchpriority:f,objectFit:g,objectPosition:x}=e,y=e.class,b=e.style,{processedImage:w,variants:v,optimize:S=!0,isDev:T=!1}=t;if(v&&v.length>0)return Rl(e,v,w);if(T||!S)return Ml(e);return Dl(e)}function Rl(e,t,r){let{src:n,alt:o,width:s,height:i,sizes:a="100vw",loading:c="lazy",priority:l=!1,decoding:d="async",fetchpriority:u,objectFit:p,objectPosition:h,placeholder:f="none"}=e,g=e.class,x=e.style,y=pr(t),b=ur(t),w=typeof a==="object"?dr(a):a,v=r?r.aspectRatio:s&&i?Number(s)/Number(i):void 0,S=[];if(v)S.push(`aspect-ratio: ${v}`);if(p)S.push(`object-fit: ${p}`);if(h)S.push(`object-position: ${h}`);if(x)S.push(x);let T=S.length>0?` style="${S.join("; ")}"`:"",C=g?` class="${g}"`:"",j=l?"":` loading="${c}"`,k=` decoding="${d}"`,L=u?` fetchpriority="${u}"`:l?' fetchpriority="high"':"",X=["avif","webp","jpeg","png"],K=[];for(let R of X){let M=y.get(R);if(M&&M.length>0){let N=Bt(M),Z=We(R);K.push(` <source type="${Z}" srcset="${N}" sizes="${w}" />`)}}let ne="",ye="",oe;if(f!=="none"&&r?.placeholder){let R=`img-${Math.random().toString(36).slice(2,8)}`;if(ne=`<div class="stx-image-wrapper" id="${R}">`,ye="</div>",f==="blur")oe=`
30
- #${R} {
29
+ `,await Bun.write(n,o)}return{configPath:r,siteId:e.siteId}}class it extends Error{code;constructor(e,t){super(e);this.name="DeployError",this.code=t}}function jl(e){let t=process.platform,r=t==="darwin"?"open":t==="win32"?"start":"xdg-open";Bun.spawn([r,e],{stdio:["ignore","ignore","ignore"]})}function Rl(e,t={}){let{src:r,alt:n,width:o,height:s,sizes:i="100vw",loading:a="lazy",priority:c=!1,quality:l=Ne,placeholder:d="none",formats:u=Fe,widths:p=Le,decoding:h="async",fetchpriority:f,objectFit:g,objectPosition:x}=e,y=e.class,b=e.style,{processedImage:w,variants:v,optimize:k=!0,isDev:C=!1}=t;if(v&&v.length>0)return Ml(e,v,w);if(C||!k)return Dl(e);return Pl(e)}function Ml(e,t,r){let{src:n,alt:o,width:s,height:i,sizes:a="100vw",loading:c="lazy",priority:l=!1,decoding:d="async",fetchpriority:u,objectFit:p,objectPosition:h,placeholder:f="none"}=e,g=e.class,x=e.style,y=fr(t),b=pr(t),w=typeof a==="object"?ur(a):a,v=r?r.aspectRatio:s&&i?Number(s)/Number(i):void 0,k=[];if(v)k.push(`aspect-ratio: ${v}`);if(p)k.push(`object-fit: ${p}`);if(h)k.push(`object-position: ${h}`);if(x)k.push(x);let C=k.length>0?` style="${k.join("; ")}"`:"",E=g?` class="${g}"`:"",R=l?"":` loading="${c}"`,T=` decoding="${d}"`,F=u?` fetchpriority="${u}"`:l?' fetchpriority="high"':"",J=["avif","webp","jpeg","png"],G=[];for(let M of J){let D=y.get(M);if(D&&D.length>0){let B=zt(D),Q=Ve(M);G.push(` <source type="${Q}" srcset="${B}" sizes="${w}" />`)}}let oe="",xe="",se;if(f!=="none"&&r?.placeholder){let M=`img-${Math.random().toString(36).slice(2,8)}`;if(oe=`<div class="stx-image-wrapper" id="${M}">`,xe="</div>",f==="blur")se=`
30
+ #${M} {
31
31
  position: relative;
32
32
  background-image: url('${r.placeholder}');
33
33
  background-size: cover;
34
34
  background-position: center;
35
35
  }
36
- #${R} img {
36
+ #${M} img {
37
37
  transition: opacity 0.3s ease;
38
38
  }
39
- #${R}.loaded img {
39
+ #${M}.loaded img {
40
40
  opacity: 1;
41
41
  }
42
- `.trim();else if(f==="color")oe=`
43
- #${R} {
42
+ `.trim();else if(f==="color")se=`
43
+ #${M} {
44
44
  background-color: ${r.placeholder};
45
45
  }
46
- `.trim()}let G=s?` width="${s}"`:r?` width="${r.width}"`:"",_=i?` height="${i}"`:r?` height="${r.height}"`:"",E=`${ne}<picture>
47
- ${K.join(`
46
+ `.trim()}let Z=s?` width="${s}"`:r?` width="${r.width}"`:"",A=i?` height="${i}"`:r?` height="${r.height}"`:"",_=`${oe}<picture>
47
+ ${G.join(`
48
48
  `)}
49
49
  <img
50
50
  src="${b?.url||n}"
51
- alt="${Dn(o)}"${G}${_}${C}${T}${j}${k}${L}
51
+ alt="${Pn(o)}"${Z}${A}${E}${C}${R}${T}${F}
52
52
  />
53
- </picture>${ye}`,A;if(l&&b){let R=y.get("webp"),M=R?.[Math.floor(R.length/2)]||b,N=We(M.format);A=`<link rel="preload" as="image" href="${M.url}" type="${N}" />`}return{html:E,preloadLink:A,placeholderCss:oe}}function Ml(e){let{src:t,alt:r,width:n,height:o,loading:s="lazy",decoding:i="async",priority:a=!1,fetchpriority:c,objectFit:l,objectPosition:d}=e,u=e.class,p=e.style,h=[];if(l)h.push(`object-fit: ${l}`);if(d)h.push(`object-position: ${d}`);if(p)h.push(p);let f=h.length>0?` style="${h.join("; ")}"`:"",g=u?` class="${u}"`:"",x=n?` width="${n}"`:"",y=o?` height="${o}"`:"",b=a?"":` loading="${s}"`,w=` decoding="${i}"`,v=c?` fetchpriority="${c}"`:a?' fetchpriority="high"':"";return{html:`<img src="${t}" alt="${Dn(r)}"${x}${y}${g}${f}${b}${w}${v} />`}}function Dl(e){let{src:t,alt:r,width:n,height:o,sizes:s="100vw",loading:i="lazy",priority:a=!1,quality:c=Fe,formats:l=Le,widths:d=Ie,decoding:u="async",fetchpriority:p,objectFit:h,objectPosition:f}=e,g=e.class,x=e.style,y=[];if(h)y.push(`object-fit: ${h}`);if(f)y.push(`object-position: ${f}`);if(x)y.push(x);let b=y.length>0?` style="${y.join("; ")}"`:"",w=g?` class="${g}"`:"",v=n?` width="${n}"`:"",S=o?` height="${o}"`:"",T=a?"":` loading="${i}"`,C=` decoding="${u}"`,j=p?` fetchpriority="${p}"`:a?' fetchpriority="high"':"",k=typeof s==="object"?dr(s):s,L=`
53
+ </picture>${xe}`,j;if(l&&b){let M=y.get("webp"),D=M?.[Math.floor(M.length/2)]||b,B=Ve(D.format);j=`<link rel="preload" as="image" href="${D.url}" type="${B}" />`}return{html:_,preloadLink:j,placeholderCss:se}}function Dl(e){let{src:t,alt:r,width:n,height:o,loading:s="lazy",decoding:i="async",priority:a=!1,fetchpriority:c,objectFit:l,objectPosition:d}=e,u=e.class,p=e.style,h=[];if(l)h.push(`object-fit: ${l}`);if(d)h.push(`object-position: ${d}`);if(p)h.push(p);let f=h.length>0?` style="${h.join("; ")}"`:"",g=u?` class="${u}"`:"",x=n?` width="${n}"`:"",y=o?` height="${o}"`:"",b=a?"":` loading="${s}"`,w=` decoding="${i}"`,v=c?` fetchpriority="${c}"`:a?' fetchpriority="high"':"";return{html:`<img src="${t}" alt="${Pn(r)}"${x}${y}${g}${f}${b}${w}${v} />`}}function Pl(e){let{src:t,alt:r,width:n,height:o,sizes:s="100vw",loading:i="lazy",priority:a=!1,quality:c=Ne,formats:l=Fe,widths:d=Le,decoding:u="async",fetchpriority:p,objectFit:h,objectPosition:f}=e,g=e.class,x=e.style,y=[];if(h)y.push(`object-fit: ${h}`);if(f)y.push(`object-position: ${f}`);if(x)y.push(x);let b=y.length>0?` style="${y.join("; ")}"`:"",w=g?` class="${g}"`:"",v=n?` width="${n}"`:"",k=o?` height="${o}"`:"",C=a?"":` loading="${i}"`,E=` decoding="${u}"`,R=p?` fetchpriority="${p}"`:a?' fetchpriority="high"':"",T=typeof s==="object"?ur(s):s,F=`
54
54
  data-stx-image
55
55
  data-src="${t}"
56
- data-sizes="${k}"
56
+ data-sizes="${T}"
57
57
  data-quality="${c}"
58
58
  data-formats="${l.join(",")}"
59
59
  data-widths="${d.join(",")}"
60
- `.replace(/\s+/g," ").trim();return{html:`<img src="${t}" alt="${Dn(r)}"${v}${S}${w}${b}${T}${C}${j} ${L} />`}}function rs(e){let t=e.match(/<Image\s+([^>]*?)\/?>/);if(!t)return null;let r=t[1],n={},o=/(\w+)(?:=(?:"([^"]*)"|'([^']*)'|(\{[^}]+\})))?/g,s;while((s=o.exec(r))!==null){let[,i,a,c,l]=s,d=a??c??l??!0;switch(i){case"src":n.src=String(d);break;case"alt":n.alt=String(d);break;case"width":n.width=Number(d)||d;break;case"height":n.height=Number(d)||d;break;case"sizes":n.sizes=String(d);break;case"loading":n.loading=d;break;case"priority":n.priority=d===!0||d==="true";break;case"quality":n.quality=Number(d);break;case"placeholder":n.placeholder=d;break;case"class":n.class=String(d);break;case"style":n.style=String(d);break;case"decoding":n.decoding=d;break;case"fetchpriority":n.fetchpriority=d;break;case"objectFit":n.objectFit=d;break;case"objectPosition":n.objectPosition=String(d);break}}if(!n.src||!n.alt)return null;return n}async function Pl(e,t){let r=/<Image\s+[^>]*?\/?>/g,n=[],o=[],s=e,i,a=[];while((i=r.exec(e))!==null)a.push({match:i[0],index:i.index});for(let c=a.length-1;c>=0;c--){let{match:l}=a[c],d=rs(l);if(d){let u=await t(d);if(s=s.replace(l,u.html),u.preloadLink)n.push(u.preloadLink);if(u.placeholderCss)o.push(u.placeholderCss)}}return{html:s,preloadLinks:n,styles:o}}function Dn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var fr=new Map;function ss(){fr.clear()}async function Ol(e,t){let r=`${e}:${JSON.stringify(t)}`;if(fr.has(r))return fr.get(r);try{let n=await qe(e,t);return fr.set(r,n),n}catch{return null}}function is(){return os({name:"image",hasEndTag:!1,description:"Render an optimized image with responsive variants",transform:async(e,t,r)=>{let{src:n,alt:o,options:s}=Il(e,t,r);if(!n)return console.warn("@image directive: missing src argument"),"<!-- @image: missing src -->";let i={widths:s.widths||(s.width?[s.width]:Ie),formats:s.formats||Le,quality:s.quality||Fe,placeholder:(s.placeholder==="color"?"dominant-color":s.placeholder)||"none"};if(!await Ve())return ns(n,o||"",s);let a=await Ol(n,i);if(!a)return ns(n,o||"",s);return Fl(a,o||"",s)}})}function Il(e,t,r){if(t.src)return{src:String(t.src),alt:String(t.alt||""),options:t.options||{}};let n=e.trim();if(n.startsWith("@image(")||n.startsWith("("))n=n.replace(/^@image\(/,"").replace(/^\(/,"").replace(/\)$/,"");let o=Ll(n),s=o[0]||"",i=o[1]||"",a={};if(s&&!s.startsWith("/")&&!s.startsWith(".")&&!s.startsWith("http")){let c=r[s];if(typeof c==="string")s=c}if(o[2])try{if(typeof o[2]==="string")a=JSON.parse(o[2]);else a=o[2]}catch{}return{src:s,alt:i,options:a}}function Ll(e){let t=[],r="",n=!1,o="",s=0,i=0;for(let a=0;a<e.length;a++){let c=e[a],l=a>0?e[a-1]:"";if((c==='"'||c==="'")&&l!=="\\"){if(!n)n=!0,o=c;else if(c===o)n=!1,o="";else r+=c;continue}if(!n){if(c==="{")s++;if(c==="}")s--;if(c==="[")i++;if(c==="]")i--;if(c===","&&s===0&&i===0){t.push(r.trim()),r="";continue}}r+=c}if(r.trim())t.push(r.trim());return t}function ns(e,t,r){let n=[`src="${Ne(e)}"`];if(t)n.push(`alt="${Ne(t)}"`);if(r.width)n.push(`width="${r.width}"`);if(r.height)n.push(`height="${r.height}"`);if(r.class)n.push(`class="${Ne(r.class)}"`);if(r.style)n.push(`style="${Ne(r.style)}"`);if(r.lazy!==!1)n.push('loading="lazy"');return n.push('decoding="async"'),`<img ${n.join(" ")} />`}function Fl(e,t,r){let{variants:n,placeholder:o,width:s,height:i,aspectRatio:a}=e,c=new Map;for(let x of n){let y=c.get(x.format)||[];y.push(x),c.set(x.format,y)}let l=["avif","webp","jpeg","png"],d=[];for(let x of l){let y=c.get(x);if(y&&y.length>0){let b=Bt(y),w=We(x),v=r.sizes||"100vw";d.push(` <source type="${w}" srcset="${Ne(b)}" sizes="${Ne(v)}" />`)}}let u=c.get("jpeg")||[],p=u.length>0?u[Math.floor(u.length/2)]:n[Math.floor(n.length/2)],h=[`src="${p?.url||e.src}"`,`alt="${Ne(t)}"`];if(r.width||s)h.push(`width="${r.width||s}"`);if(r.height||i)h.push(`height="${r.height||i}"`);if(r.class)h.push(`class="${Ne(r.class)}"`);let f=[];if(a)f.push(`aspect-ratio: ${a.toFixed(4)}`);if(r.style)f.push(r.style);if(f.length>0)h.push(`style="${f.join("; ")}"`);if(r.lazy!==!1&&!r.priority)h.push('loading="lazy"');if(h.push('decoding="async"'),r.priority)h.push('fetchpriority="high"');let g=`<picture>
60
+ `.replace(/\s+/g," ").trim();return{html:`<img src="${t}" alt="${Pn(r)}"${v}${k}${w}${b}${C}${E}${R} ${F} />`}}function ns(e){let t=e.match(/<Image\s+([^>]*?)\/?>/);if(!t)return null;let r=t[1],n={},o=/(\w+)(?:=(?:"([^"]*)"|'([^']*)'|(\{[^}]+\})))?/g,s;while((s=o.exec(r))!==null){let[,i,a,c,l]=s,d=a??c??l??!0;switch(i){case"src":n.src=String(d);break;case"alt":n.alt=String(d);break;case"width":n.width=Number(d)||d;break;case"height":n.height=Number(d)||d;break;case"sizes":n.sizes=String(d);break;case"loading":n.loading=d;break;case"priority":n.priority=d===!0||d==="true";break;case"quality":n.quality=Number(d);break;case"placeholder":n.placeholder=d;break;case"class":n.class=String(d);break;case"style":n.style=String(d);break;case"decoding":n.decoding=d;break;case"fetchpriority":n.fetchpriority=d;break;case"objectFit":n.objectFit=d;break;case"objectPosition":n.objectPosition=String(d);break}}if(!n.src||!n.alt)return null;return n}async function Ol(e,t){let r=/<Image\s+[^>]*?\/?>/g,n=[],o=[],s=e,i,a=[];while((i=r.exec(e))!==null)a.push({match:i[0],index:i.index});for(let c=a.length-1;c>=0;c--){let{match:l}=a[c],d=ns(l);if(d){let u=await t(d);if(s=s.replace(l,u.html),u.preloadLink)n.push(u.preloadLink);if(u.placeholderCss)o.push(u.placeholderCss)}}return{html:s,preloadLinks:n,styles:o}}function Pn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var mr=new Map;function is(){mr.clear()}async function Il(e,t){let r=`${e}:${JSON.stringify(t)}`;if(mr.has(r))return mr.get(r);try{let n=await Xe(e,t);return mr.set(r,n),n}catch{return null}}function as(){return ss({name:"image",hasEndTag:!1,description:"Render an optimized image with responsive variants",transform:async(e,t,r)=>{let{src:n,alt:o,options:s}=Ll(e,t,r);if(!n)return console.warn("@image directive: missing src argument"),"<!-- @image: missing src -->";let i={widths:s.widths||(s.width?[s.width]:Le),formats:s.formats||Fe,quality:s.quality||Ne,placeholder:(s.placeholder==="color"?"dominant-color":s.placeholder)||"none"};if(!await qe())return os(n,o||"",s);let a=await Il(n,i);if(!a)return os(n,o||"",s);return Nl(a,o||"",s)}})}function Ll(e,t,r){if(t.src)return{src:String(t.src),alt:String(t.alt||""),options:t.options||{}};let n=e.trim();if(n.startsWith("@image(")||n.startsWith("("))n=n.replace(/^@image\(/,"").replace(/^\(/,"").replace(/\)$/,"");let o=Fl(n),s=o[0]||"",i=o[1]||"",a={};if(s&&!s.startsWith("/")&&!s.startsWith(".")&&!s.startsWith("http")){let c=r[s];if(typeof c==="string")s=c}if(o[2])try{if(typeof o[2]==="string")a=JSON.parse(o[2]);else a=o[2]}catch{}return{src:s,alt:i,options:a}}function Fl(e){let t=[],r="",n=!1,o="",s=0,i=0;for(let a=0;a<e.length;a++){let c=e[a],l=a>0?e[a-1]:"";if((c==='"'||c==="'")&&l!=="\\"){if(!n)n=!0,o=c;else if(c===o)n=!1,o="";else r+=c;continue}if(!n){if(c==="{")s++;if(c==="}")s--;if(c==="[")i++;if(c==="]")i--;if(c===","&&s===0&&i===0){t.push(r.trim()),r="";continue}}r+=c}if(r.trim())t.push(r.trim());return t}function os(e,t,r){let n=[`src="${Be(e)}"`];if(t)n.push(`alt="${Be(t)}"`);if(r.width)n.push(`width="${r.width}"`);if(r.height)n.push(`height="${r.height}"`);if(r.class)n.push(`class="${Be(r.class)}"`);if(r.style)n.push(`style="${Be(r.style)}"`);if(r.lazy!==!1)n.push('loading="lazy"');return n.push('decoding="async"'),`<img ${n.join(" ")} />`}function Nl(e,t,r){let{variants:n,placeholder:o,width:s,height:i,aspectRatio:a}=e,c=new Map;for(let x of n){let y=c.get(x.format)||[];y.push(x),c.set(x.format,y)}let l=["avif","webp","jpeg","png"],d=[];for(let x of l){let y=c.get(x);if(y&&y.length>0){let b=zt(y),w=Ve(x),v=r.sizes||"100vw";d.push(` <source type="${w}" srcset="${Be(b)}" sizes="${Be(v)}" />`)}}let u=c.get("jpeg")||[],p=u.length>0?u[Math.floor(u.length/2)]:n[Math.floor(n.length/2)],h=[`src="${p?.url||e.src}"`,`alt="${Be(t)}"`];if(r.width||s)h.push(`width="${r.width||s}"`);if(r.height||i)h.push(`height="${r.height||i}"`);if(r.class)h.push(`class="${Be(r.class)}"`);let f=[];if(a)f.push(`aspect-ratio: ${a.toFixed(4)}`);if(r.style)f.push(r.style);if(f.length>0)h.push(`style="${f.join("; ")}"`);if(r.lazy!==!1&&!r.priority)h.push('loading="lazy"');if(h.push('decoding="async"'),r.priority)h.push('fetchpriority="high"');let g=`<picture>
61
61
  `;if(g+=d.join(`
62
62
  `)+`
63
63
  `,g+=` <img ${h.join(" ")} />
@@ -65,8 +65,8 @@ ${K.join(`
65
65
  ${g}
66
66
  </div>`}else if(r.placeholder==="color"){let y=o.replace(/[^a-zA-Z0-9#(),.\s%-]/g,"");g=`<div id="${x}" class="stx-image-placeholder" style="background-color: ${y};">
67
67
  ${g}
68
- </div>`}}if(r.priority&&p){let x=We(p.format);g=`<link rel="preload" as="image" href="${Ne(p.url)}" type="${x}" />
69
- `+g}return g}function Ne(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var Nl=is();import yt from"fs";import hr from"path";function Bl(e={}){let{inputDirs:t=["public","src/assets","assets"],outputDir:r="dist/images",baseUrl:n="/images",formats:o=Le,widths:s=Ie,quality:i=Fe,placeholder:a="none",concurrency:c=4,cache:l=!0,cacheDir:d=".stx/image-cache",referencedOnly:u=!1,verbose:p=!1}=e,h={imageReferences:new Set,processedImages:new Map,stats:{totalImages:0,optimizedImages:0,savedBytes:0,variants:0}};return{name:"stx-image-optimization",async setup(f){if(!await Ve()){console.warn("[stx-images] no image backend available, optimization disabled");return}if(l)await yt.promises.mkdir(d,{recursive:!0});if(p){let g=await Pn();console.log("[stx-images] Plugin initialized"),console.log(` Backend: ${g?"sharp (native fast path) + ts-images":"ts-images (pure TS)"}`),console.log(` Input dirs: ${t.join(", ")}`),console.log(` Output dir: ${r}`),console.log(` Formats: ${o.join(", ")}`),console.log(` Widths: ${s.join(", ")}`)}},async buildStart(){h.imageReferences.clear(),h.processedImages.clear(),h.stats={totalImages:0,optimizedImages:0,savedBytes:0,variants:0}},async transform(f,g){if(g.endsWith(".html")||g.endsWith(".stx")){let x=zl(f);for(let y of x)h.imageReferences.add(y)}if(f.includes("<Image")||f.includes("@image"))return await Hl(f,{formats:o,widths:s,quality:i,placeholder:a,outputDir:r,baseUrl:n,processedImages:h.processedImages});return f},async buildEnd(f){if(!await Ve())return;await yt.promises.mkdir(r,{recursive:!0});let g=[];for(let b of t){if(!yt.existsSync(b))continue;let w=await as(b);g.push(...w)}let x=u?g.filter((b)=>Ul(b,h.imageReferences)):g;if(h.stats.totalImages=x.length,p)console.log(`[stx-images] Processing ${x.length} images...`);let y=cs(x,c);for(let b of y)await Promise.all(b.map(async(w)=>{try{let v=await qe(w,{formats:o,widths:s,quality:i,placeholder:a,outputDir:r,baseUrl:n});h.processedImages.set(w,v),h.stats.optimizedImages++,h.stats.variants+=v.variants.length;let S=yt.statSync(w).size,T=On(v.variants);if(h.stats.savedBytes+=Math.max(0,S-T/v.variants.length),p)console.log(` \u2713 ${hr.basename(w)} \u2192 ${v.variants.length} variants`)}catch(v){console.error(`[stx-images] Error processing ${w}:`,v)}}));if(console.log("[stx-images] Optimization complete:"),console.log(` Images: ${h.stats.optimizedImages}/${h.stats.totalImages}`),console.log(` Variants: ${h.stats.variants}`),h.stats.savedBytes>0)console.log(` Saved: ~${In(h.stats.savedBytes)}`)}}}function zl(e){let t=[],r=/src=["']([^"']+\.(jpg|jpeg|png|webp|avif|gif))["']/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);let o=/<Image[^>]+src=["']([^"']+)["']/gi;while((n=o.exec(e))!==null)t.push(n[1]);let s=/@image\s*\(\s*['"]([^'"]+)['"]/gi;while((n=s.exec(e))!==null)t.push(n[1]);let i=/background(?:-image)?:\s*url\(["']?([^"')]+\.(jpg|jpeg|png|webp|avif|gif))["']?\)/gi;while((n=i.exec(e))!==null)t.push(n[1]);return t}function Ul(e,t){let r=hr.basename(e);for(let n of t)if(n.endsWith(r)||n.includes(r))return!0;return!1}async function Hl(e,t){return e}async function as(e){let t=[];async function r(n){let o=await yt.promises.readdir(n,{withFileTypes:!0});for(let s of o){let i=hr.join(n,s.name);if(s.isDirectory())await r(i);else if(s.isFile()&&mr(i))t.push(i)}}return await r(e),t}function cs(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}async function ls(e,t,r={}){if(!await Ve())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");return qe(e,{...r,outputDir:t})}async function Wl(e,t,r={}){let{formats:n=Le,widths:o=Ie,quality:s=Fe,placeholder:i="none",concurrency:a=4,verbose:c=!1}=r;if(!await Ve())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");await yt.promises.mkdir(t,{recursive:!0});let l=await as(e),d=[],u={totalImages:l.length,optimizedImages:0,savedBytes:0,variants:0},p=cs(l,a);for(let h of p){let f=await Promise.all(h.map(async(g)=>{try{let x=await qe(g,{formats:n,widths:o,quality:s,placeholder:i,outputDir:t,baseUrl:"/"});if(u.optimizedImages++,u.variants+=x.variants.length,c)console.log(` \u2713 ${hr.basename(g)}`);return x}catch(x){return console.error(`Error processing ${g}:`,x),null}}));d.push(...f.filter((g)=>g!==null))}return{processed:d,stats:u}}function ds(e){let t={};for(let r of e)t[r.src]={variants:r.variants,placeholder:r.placeholder};return t}async function Vl(e,t){let r=ds(e);await Bun.write(t,JSON.stringify(r,null,2))}var Sy={enabled:!0,widths:[320,640,768,1024,1280,1536,1920],formats:["webp","jpeg"],quality:80,devOptimize:!1,cacheDir:".stx/image-cache",placeholder:"none",inputDirs:["public","src/assets","assets"],outputDir:"dist/images",baseUrl:"/images"};var J=null;function gr(e,t,r=new WeakSet){if(Object.is(e,t))return!0;if(typeof e!=="object"||typeof t!=="object"||e===null||t===null)return!1;if(r.has(e))return!0;if(r.add(e),e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.source===t.source&&e.flags===t.flags;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!gr(e[s],t[s],r))return!1;return!0}if(Array.isArray(t))return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;for(let[s,i]of e)if(!t.has(s)||!gr(i,t.get(s),r))return!1;return!0}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}if(t instanceof Set)return!1;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!gr(e[s],t[s],r))return!1}return!0}function My(e){J=e}function Dy(){return J}function Py(){return{isMounted:!1,isUnmounted:!1,hooks:{beforeMount:[],mounted:[],beforeUpdate:[],updated:[],beforeUnmount:[],unmounted:[]},effects:[],scope:Gl()}}function Gl(){return{refs:new Map,effects:new Set,cleanups:[]}}function Oy(e){let t=new Set,r=new Set,n=e,o=Symbol("ref"),s={get value(){let i=yr();if(i)r.add(i);return n},set value(i){if(!Object.is(i,n)){let a=n;n=i;for(let c of t)c(i,a);for(let c of r)if(Ln())Fn(c);else c()}},subscribe(i){return t.add(i),()=>{t.delete(i)}}};if(J)J.scope.refs.set(o,s);return s}var us=new WeakMap;function Zl(e){let t=us.get(e);if(t)return t;let r=new Map,n=(i)=>{let a=r.get(i);if(!a)return;for(let c of[...a])if(Ln())Fn(c);else c()},o=(i,a)=>{if(!r.has(i))r.set(i,new Set);return r.get(i).add(a),()=>{r.get(i)?.delete(a)}},s=new Proxy(e,{get(i,a,c){let l=Reflect.get(i,a,c),d=yr();if(d)o(a,d);if(l!==null&&typeof l==="object"&&!Array.isArray(l)){let u=Object.getPrototypeOf(l);if(u===Object.prototype||u===null)return Zl(l)}return l},set(i,a,c,l){let d=Reflect.get(i,a,l),u=Reflect.set(i,a,c,l);if(!Object.is(c,d))n(a);return u},deleteProperty(i,a){let c=Reflect.deleteProperty(i,a);return n(a),c}});return us.set(e,s),s}function Iy(e){let t,r=!0,n=new Set,o=new Set,s=()=>{r=!0,i()},i=()=>{if(r){let c=t,l=zt(s);if(t=e(),Ut(l),r=!1,!Object.is(t,c)){for(let d of n)d(t,c);for(let d of o)d()}}},a=zt(s);return t=e(),r=!1,Ut(a),{get value(){let c=yr();if(c)o.add(c);return i(),t},set value(c){console.warn("[stx] Computed properties are readonly")},subscribe(c){return n.add(c),()=>{n.delete(c)}}}}function Ql(e){if(typeof requestAnimationFrame==="function"){requestAnimationFrame(()=>{requestAnimationFrame(e)});return}setTimeout(e,0)}function Ly(e,t,r={}){let{immediate:n=!1,deep:o=!1,flush:s="post"}=r,i,a,c=!1,l=()=>{if(c)return;let f=h();if((o?!gr(f,i):!Object.is(f,i))||n)if(t(f,i),o&&f!==null&&typeof f==="object")try{i=structuredClone(f)}catch{i=f}else i=f},d=(f)=>{if(s==="sync")f();else if(s==="pre")Promise.resolve().then(f);else Ql(f)},u=!1,p=()=>{if(c||u)return;u=!0,d(()=>{u=!1,l()})},h=()=>{if(typeof e==="function"){let f=zt(p);try{return e()}finally{Ut(f)}}return e.value};if(typeof e!=="function"){let f=e.subscribe(()=>{d(l)});a=()=>{c=!0,f()}}else a=()=>{c=!0};if(i=h(),n)d(l);if(J)J.scope.cleanups.push(()=>a?.());return()=>a?.()}function Fy(e,t,r={}){let n=[],o=e.map((s)=>s.value);for(let s of e){let i=s.subscribe(()=>{let a=e.map((c)=>c.value);t(a,o),o=[...a]});n.push(i)}if(r.immediate){let s=e.map((i)=>i.value);t(s,o)}return()=>{for(let s of n)s()}}function Ny(e){let t,r=!1,n=()=>{if(r)return;if(t)t();let o=zt(n);t=e(),Ut(o)};if(n(),J)J.scope.cleanups.push(()=>{if(r=!0,t)t()});return()=>{if(r=!0,t)t()}}function By(e){if(J)J.hooks.beforeMount.push(e);else console.warn("[stx] onBeforeMount called outside of component setup")}function zy(e){if(J)J.hooks.mounted.push(e);else console.warn("[stx] onMounted called outside of component setup")}function Uy(e){if(J)J.hooks.beforeUpdate.push(e);else console.warn("[stx] onBeforeUpdate called outside of component setup")}function Hy(e){if(J)J.hooks.updated.push(e);else console.warn("[stx] onUpdated called outside of component setup")}function Wy(e){if(J)J.hooks.beforeUnmount.push(e);else console.warn("[stx] onBeforeUnmount called outside of component setup")}function Vy(e){if(J)J.hooks.unmounted.push(e);else console.warn("[stx] onUnmounted called outside of component setup")}async function xt(e,t){let r=e.hooks[t];for(let n of r)await n()}async function qy(e){await xt(e,"beforeMount"),e.isMounted=!0,await xt(e,"mounted")}async function Xy(e){if(!e.isMounted||e.isUnmounted)return;await xt(e,"beforeUpdate"),await xt(e,"updated")}async function Jy(e){if(e.isUnmounted)return;await xt(e,"beforeUnmount");for(let t of e.scope.cleanups)t();e.isUnmounted=!0,await xt(e,"unmounted")}function Yy(){return`
68
+ </div>`}}if(r.priority&&p){let x=Ve(p.format);g=`<link rel="preload" as="image" href="${Be(p.url)}" type="${x}" />
69
+ `+g}return g}function Be(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var Bl=as();import xt from"fs";import gr from"path";function zl(e={}){let{inputDirs:t=["public","src/assets","assets"],outputDir:r="dist/images",baseUrl:n="/images",formats:o=Fe,widths:s=Le,quality:i=Ne,placeholder:a="none",concurrency:c=4,cache:l=!0,cacheDir:d=".stx/image-cache",referencedOnly:u=!1,verbose:p=!1}=e,h={imageReferences:new Set,processedImages:new Map,stats:{totalImages:0,optimizedImages:0,savedBytes:0,variants:0}};return{name:"stx-image-optimization",async setup(f){if(!await qe()){console.warn("[stx-images] no image backend available, optimization disabled");return}if(l)await xt.promises.mkdir(d,{recursive:!0});if(p){let g=await On();console.log("[stx-images] Plugin initialized"),console.log(` Backend: ${g?"sharp (native fast path) + ts-images":"ts-images (pure TS)"}`),console.log(` Input dirs: ${t.join(", ")}`),console.log(` Output dir: ${r}`),console.log(` Formats: ${o.join(", ")}`),console.log(` Widths: ${s.join(", ")}`)}},async buildStart(){h.imageReferences.clear(),h.processedImages.clear(),h.stats={totalImages:0,optimizedImages:0,savedBytes:0,variants:0}},async transform(f,g){if(g.endsWith(".html")||g.endsWith(".stx")){let x=Ul(f);for(let y of x)h.imageReferences.add(y)}if(f.includes("<Image")||f.includes("@image"))return await Wl(f,{formats:o,widths:s,quality:i,placeholder:a,outputDir:r,baseUrl:n,processedImages:h.processedImages});return f},async buildEnd(f){if(!await qe())return;await xt.promises.mkdir(r,{recursive:!0});let g=[];for(let b of t){if(!xt.existsSync(b))continue;let w=await cs(b);g.push(...w)}let x=u?g.filter((b)=>Hl(b,h.imageReferences)):g;if(h.stats.totalImages=x.length,p)console.log(`[stx-images] Processing ${x.length} images...`);let y=ls(x,c);for(let b of y)await Promise.all(b.map(async(w)=>{try{let v=await Xe(w,{formats:o,widths:s,quality:i,placeholder:a,outputDir:r,baseUrl:n});h.processedImages.set(w,v),h.stats.optimizedImages++,h.stats.variants+=v.variants.length;let k=xt.statSync(w).size,C=In(v.variants);if(h.stats.savedBytes+=Math.max(0,k-C/v.variants.length),p)console.log(` \u2713 ${gr.basename(w)} \u2192 ${v.variants.length} variants`)}catch(v){console.error(`[stx-images] Error processing ${w}:`,v)}}));if(console.log("[stx-images] Optimization complete:"),console.log(` Images: ${h.stats.optimizedImages}/${h.stats.totalImages}`),console.log(` Variants: ${h.stats.variants}`),h.stats.savedBytes>0)console.log(` Saved: ~${Ln(h.stats.savedBytes)}`)}}}function Ul(e){let t=[],r=/src=["']([^"']+\.(jpg|jpeg|png|webp|avif|gif))["']/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);let o=/<Image[^>]+src=["']([^"']+)["']/gi;while((n=o.exec(e))!==null)t.push(n[1]);let s=/@image\s*\(\s*['"]([^'"]+)['"]/gi;while((n=s.exec(e))!==null)t.push(n[1]);let i=/background(?:-image)?:\s*url\(["']?([^"')]+\.(jpg|jpeg|png|webp|avif|gif))["']?\)/gi;while((n=i.exec(e))!==null)t.push(n[1]);return t}function Hl(e,t){let r=gr.basename(e);for(let n of t)if(n.endsWith(r)||n.includes(r))return!0;return!1}async function Wl(e,t){return e}async function cs(e){let t=[];async function r(n){let o=await xt.promises.readdir(n,{withFileTypes:!0});for(let s of o){let i=gr.join(n,s.name);if(s.isDirectory())await r(i);else if(s.isFile()&&hr(i))t.push(i)}}return await r(e),t}function ls(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}async function ds(e,t,r={}){if(!await qe())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");return Xe(e,{...r,outputDir:t})}async function Vl(e,t,r={}){let{formats:n=Fe,widths:o=Le,quality:s=Ne,placeholder:i="none",concurrency:a=4,verbose:c=!1}=r;if(!await qe())throw Error("No image backend available \u2014 install sharp or ensure ts-images is bundled");await xt.promises.mkdir(t,{recursive:!0});let l=await cs(e),d=[],u={totalImages:l.length,optimizedImages:0,savedBytes:0,variants:0},p=ls(l,a);for(let h of p){let f=await Promise.all(h.map(async(g)=>{try{let x=await Xe(g,{formats:n,widths:o,quality:s,placeholder:i,outputDir:t,baseUrl:"/"});if(u.optimizedImages++,u.variants+=x.variants.length,c)console.log(` \u2713 ${gr.basename(g)}`);return x}catch(x){return console.error(`Error processing ${g}:`,x),null}}));d.push(...f.filter((g)=>g!==null))}return{processed:d,stats:u}}function us(e){let t={};for(let r of e)t[r.src]={variants:r.variants,placeholder:r.placeholder};return t}async function ql(e,t){let r=us(e);await Bun.write(t,JSON.stringify(r,null,2))}var ky={enabled:!0,widths:[320,640,768,1024,1280,1536,1920],formats:["webp","jpeg"],quality:80,devOptimize:!1,cacheDir:".stx/image-cache",placeholder:"none",inputDirs:["public","src/assets","assets"],outputDir:"dist/images",baseUrl:"/images"};var Y=null;function yr(e,t,r=new WeakSet){if(Object.is(e,t))return!0;if(typeof e!=="object"||typeof t!=="object"||e===null||t===null)return!1;if(r.has(e))return!0;if(r.add(e),e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.source===t.source&&e.flags===t.flags;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!yr(e[s],t[s],r))return!1;return!0}if(Array.isArray(t))return!1;if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;for(let[s,i]of e)if(!t.has(s)||!yr(i,t.get(s),r))return!1;return!0}if(t instanceof Map)return!1;if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}if(t instanceof Set)return!1;let n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!yr(e[s],t[s],r))return!1}return!0}function Dy(e){Y=e}function Py(){return Y}function Oy(){return{isMounted:!1,isUnmounted:!1,hooks:{beforeMount:[],mounted:[],beforeUpdate:[],updated:[],beforeUnmount:[],unmounted:[]},effects:[],scope:Zl()}}function Zl(){return{refs:new Map,effects:new Set,cleanups:[]}}function Iy(e){let t=new Set,r=new Set,n=e,o=Symbol("ref"),s={get value(){let i=xr();if(i)r.add(i);return n},set value(i){if(!Object.is(i,n)){let a=n;n=i;for(let c of t)c(i,a);for(let c of r)if(Fn())Nn(c);else c()}},subscribe(i){return t.add(i),()=>{t.delete(i)}}};if(Y)Y.scope.refs.set(o,s);return s}var ps=new WeakMap;function Ql(e){let t=ps.get(e);if(t)return t;let r=new Map,n=(i)=>{let a=r.get(i);if(!a)return;for(let c of[...a])if(Fn())Nn(c);else c()},o=(i,a)=>{if(!r.has(i))r.set(i,new Set);return r.get(i).add(a),()=>{r.get(i)?.delete(a)}},s=new Proxy(e,{get(i,a,c){let l=Reflect.get(i,a,c),d=xr();if(d)o(a,d);if(l!==null&&typeof l==="object"&&!Array.isArray(l)){let u=Object.getPrototypeOf(l);if(u===Object.prototype||u===null)return Ql(l)}return l},set(i,a,c,l){let d=Reflect.get(i,a,l),u=Reflect.set(i,a,c,l);if(!Object.is(c,d))n(a);return u},deleteProperty(i,a){let c=Reflect.deleteProperty(i,a);return n(a),c}});return ps.set(e,s),s}function Ly(e){let t,r=!0,n=new Set,o=new Set,s=()=>{r=!0,i()},i=()=>{if(r){let c=t,l=Ut(s);if(t=e(),Ht(l),r=!1,!Object.is(t,c)){for(let d of n)d(t,c);for(let d of o)d()}}},a=Ut(s);return t=e(),r=!1,Ht(a),{get value(){let c=xr();if(c)o.add(c);return i(),t},set value(c){console.warn("[stx] Computed properties are readonly")},subscribe(c){return n.add(c),()=>{n.delete(c)}}}}function ed(e){if(typeof requestAnimationFrame==="function"){requestAnimationFrame(()=>{requestAnimationFrame(e)});return}setTimeout(e,0)}function Fy(e,t,r={}){let{immediate:n=!1,deep:o=!1,flush:s="post"}=r,i,a,c=!1,l=()=>{if(c)return;let f=h();if((o?!yr(f,i):!Object.is(f,i))||n)if(t(f,i),o&&f!==null&&typeof f==="object")try{i=structuredClone(f)}catch{i=f}else i=f},d=(f)=>{if(s==="sync")f();else if(s==="pre")Promise.resolve().then(f);else ed(f)},u=!1,p=()=>{if(c||u)return;u=!0,d(()=>{u=!1,l()})},h=()=>{if(typeof e==="function"){let f=Ut(p);try{return e()}finally{Ht(f)}}return e.value};if(typeof e!=="function"){let f=e.subscribe(()=>{d(l)});a=()=>{c=!0,f()}}else a=()=>{c=!0};if(i=h(),n)d(l);if(Y)Y.scope.cleanups.push(()=>a?.());return()=>a?.()}function Ny(e,t,r={}){let n=[],o=e.map((s)=>s.value);for(let s of e){let i=s.subscribe(()=>{let a=e.map((c)=>c.value);t(a,o),o=[...a]});n.push(i)}if(r.immediate){let s=e.map((i)=>i.value);t(s,o)}return()=>{for(let s of n)s()}}function By(e){let t,r=!1,n=()=>{if(r)return;if(t)t();let o=Ut(n);t=e(),Ht(o)};if(n(),Y)Y.scope.cleanups.push(()=>{if(r=!0,t)t()});return()=>{if(r=!0,t)t()}}function zy(e){if(Y)Y.hooks.beforeMount.push(e);else console.warn("[stx] onBeforeMount called outside of component setup")}function Uy(e){if(Y)Y.hooks.mounted.push(e);else console.warn("[stx] onMounted called outside of component setup")}function Hy(e){if(Y)Y.hooks.beforeUpdate.push(e);else console.warn("[stx] onBeforeUpdate called outside of component setup")}function Wy(e){if(Y)Y.hooks.updated.push(e);else console.warn("[stx] onUpdated called outside of component setup")}function Vy(e){if(Y)Y.hooks.beforeUnmount.push(e);else console.warn("[stx] onBeforeUnmount called outside of component setup")}function qy(e){if(Y)Y.hooks.unmounted.push(e);else console.warn("[stx] onUnmounted called outside of component setup")}async function bt(e,t){let r=e.hooks[t];for(let n of r)await n()}async function Xy(e){await bt(e,"beforeMount"),e.isMounted=!0,await bt(e,"mounted")}async function Jy(e){if(!e.isMounted||e.isUnmounted)return;await bt(e,"beforeUpdate"),await bt(e,"updated")}async function Yy(e){if(e.isUnmounted)return;await bt(e,"beforeUnmount");for(let t of e.scope.cleanups)t();e.isUnmounted=!0,await bt(e,"unmounted")}function Ky(){return`
70
70
  <script data-stx-client-runtime>
71
71
  (function() {
72
72
  'use strict';
@@ -245,11 +245,11 @@ ${g}
245
245
  });
246
246
  window.provide = provide;
247
247
  })();
248
- </script>`}function Nn(e){for(let t of e.matchAll(/\bdefinePageMeta\s*\(\s*\{([\s\S]*?)\}\s*\)/g)){let r=t[1].match(/(?:^|,)\s*status\s*:\s*(\d{3})(?=\s*(?:,|$))/);if(!r)continue;let n=Number(r[1]);if(Number.isInteger(n)&&n>=100&&n<=599)return n}return}function bt(e,t){if(typeof window>"u")return t;return window[e]??t}function xr(e,t){if(typeof window>"u")return;window[e]=t}function ps(e){let t=bt("__STX_STORES__",{})[e];if(!t)throw Error(`Store "${e}" not found. Make sure it's defined with defineStore().`);return t}function ex(e){return ps(e)}function tx(e,t=5000){return new Promise((r,n)=>{let o=Date.now(),s=()=>{let i=ps(e);if(i)r(i);else if(Date.now()-o>t)n(Error(`Timeout waiting for store "${e}"`));else requestAnimationFrame(s)};s()})}function ld(){return bt("__STX_ROUTE_PARAMS__",{})}function dd(e){return ld()[e]}function rx(e){let t=dd(e);if(t===void 0)throw Error(`Route parameter "${e}" not found`);return t}function ud(){return bt("__STX_MIDDLEWARE_STATE__",{})}function nx(e){return ud()[e]}function ox(){if(typeof window>"u")return;if(!bt("__STX_STORES__",null))xr("__STX_STORES__",{})}function sx(e,t){let r=bt("__STX_STORES__",{});r[e]=t,xr("__STX_STORES__",r)}function ix(){return bt("__STX_STORE_STATE__",null)}function ax(e){xr("__STX_ROUTE_PARAMS__",e)}function cx(e){xr("__STX_MIDDLEWARE_STATE__",e)}function pd(){return typeof window>"u"}function fd(){return typeof window<"u"}function lx(e){if(fd())e()}function dx(e){if(pd())e()}async function md(e){try{let t=await Bun.file(e).text(),r=hd(t),n=gd(t,e),o=yd(t,r),s=xd(t,r);return{file:e,metrics:r,issues:n,suggestions:o,performance:s}}catch(t){throw Error(`Failed to analyze template ${e}: ${t instanceof Error?t.message:String(t)}`)}}function hd(e){let t=e.split(`
248
+ </script>`}function Bn(e){for(let t of e.matchAll(/\bdefinePageMeta\s*\(\s*\{([\s\S]*?)\}\s*\)/g)){let r=t[1].match(/(?:^|,)\s*status\s*:\s*(\d{3})(?=\s*(?:,|$))/);if(!r)continue;let n=Number(r[1]);if(Number.isInteger(n)&&n>=100&&n<=599)return n}return}function wt(e,t){if(typeof window>"u")return t;return window[e]??t}function br(e,t){if(typeof window>"u")return;window[e]=t}function fs(e){let t=wt("__STX_STORES__",{})[e];if(!t)throw Error(`Store "${e}" not found. Make sure it's defined with defineStore().`);return t}function tx(e){return fs(e)}function rx(e,t=5000){return new Promise((r,n)=>{let o=Date.now(),s=()=>{let i=fs(e);if(i)r(i);else if(Date.now()-o>t)n(Error(`Timeout waiting for store "${e}"`));else requestAnimationFrame(s)};s()})}function dd(){return wt("__STX_ROUTE_PARAMS__",{})}function ud(e){return dd()[e]}function nx(e){let t=ud(e);if(t===void 0)throw Error(`Route parameter "${e}" not found`);return t}function pd(){return wt("__STX_MIDDLEWARE_STATE__",{})}function ox(e){return pd()[e]}function sx(){if(typeof window>"u")return;if(!wt("__STX_STORES__",null))br("__STX_STORES__",{})}function ix(e,t){let r=wt("__STX_STORES__",{});r[e]=t,br("__STX_STORES__",r)}function ax(){return wt("__STX_STORE_STATE__",null)}function cx(e){br("__STX_ROUTE_PARAMS__",e)}function lx(e){br("__STX_MIDDLEWARE_STATE__",e)}function fd(){return typeof window>"u"}function md(){return typeof window<"u"}function dx(e){if(md())e()}function ux(e){if(fd())e()}async function hd(e){try{let t=await Bun.file(e).text(),r=gd(t),n=yd(t,e),o=xd(t,r),s=bd(t,r);return{file:e,metrics:r,issues:n,suggestions:o,performance:s}}catch(t){throw Error(`Failed to analyze template ${e}: ${t instanceof Error?t.message:String(t)}`)}}function gd(e){let t=e.split(`
249
249
  `),r=e.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),n=(r?r[1]:"").split(`
250
- `).length,o={conditionals:(e.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(e.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(e.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};o.total=o.conditionals+o.loops+o.includes+o.custom;let s=(e.match(/\{\{[\s\S]*?\}\}/g)||[]).length,i=(e.match(/\{!![\s\S]*?!!\}/g)||[]).length,a=(e.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,c=s+i+a,l=(e.match(/<[A-Z][^>]*>/g)||[]).length,d=(e.match(/@(?:layout|extends)\(/g)||[]).length,u=0,p=0;for(let g of t)if(/@(?:if|unless|foreach|for|while|section)\b/.test(g)&&!/@end/.test(g)&&!/@else/.test(g))p++,u=Math.max(u,p);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(g))p--;let h=u>=4?3:0,f=Math.min(10,Math.ceil(o.total*0.5+c*0.1+l*0.3+(n>10?n*0.05:0)+h));return{lines:t.length,characters:e.length,directives:o,expressions:c,components:l,layouts:d,scriptLines:n,complexity:f}}function gd(e,t){let r=[],n=fs(e,"if","endif");if(n>0)r.push({type:"error",category:"syntax",message:`Found ${n} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=fs(e,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let s=e.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(s&&s.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let i=(e.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(i>0)r.push({type:"warning",category:"security",message:`Found ${i} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let a=e.match(/<img[^>]*>/g);if(a){let d=a.filter((u)=>!u.includes("alt="));if(d.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${d.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let c=e.split(`
251
- `).filter((d)=>d.length>120);if(c.length>0)r.push({type:"info",category:"maintainability",message:`Found ${c.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let l=(e.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(l>3)r.push({type:"info",category:"maintainability",message:`Found ${l} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function yd(e,t){let r=[];if(t.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(t.complexity>5&&t.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(t.lines>100&&t.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(t.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let n=e.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(n&&n.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(t.directives.total===0&&t.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(t.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function xd(e,t){let r=1;if(r+=t.directives.conditionals*0.1,r+=t.directives.loops*0.5,r+=t.directives.includes*2,r+=t.expressions*0.05,r+=t.components*1,t.scriptLines>10)r+=t.scriptLines*0.1;let n;if(t.expressions===0&&t.directives.total===0)n="high";else if(t.expressions<5&&t.directives.total<3)n="medium";else n="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(n==="low"&&t.directives.total>5)o.push("Reduce dynamic content for better caching");if(t.components===0&&t.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:t.complexity,cacheability:n,recommendations:o}}function fs(e,t,r){let n=e.replace(/<!--[\s\S]*?-->/g,""),o=(n.match(new RegExp(`@${t}\\b`,"g"))||[]).length,s=(n.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-s)}async function px(e=["**/*.stx"],t){let r=[],n=[];for(let s of e){let i=await Array.fromAsync(new Bun.Glob(s).scan({cwd:t||process.cwd(),onlyFiles:!0,absolute:!0}));n.push(...i.filter((a)=>a.endsWith(".stx")))}for(let s of n)try{let i=await md(s);r.push(i)}catch(i){console.warn(`Failed to analyze ${s}:`,i)}let o=bd(r);return{results:r,summary:o}}function bd(e){let t=e.length,r=e.reduce((l,d)=>l+d.metrics.lines,0),n=t>0?e.reduce((l,d)=>l+d.metrics.complexity,0)/t:0,o=e.reduce((l,d)=>l+d.issues.length,0),s={};e.forEach((l)=>{l.issues.forEach((d)=>{s[d.category]=(s[d.category]||0)+1})});let i=t>0?e.reduce((l,d)=>l+d.performance.estimatedRenderTime,0)/t:0,a=Math.max(1,Math.min(10,Math.round(10-i/2-n/2))),c=[];if(n>6)c.push("Project has high average complexity. Consider refactoring complex templates.");if(o>t*2)c.push("High number of issues detected. Run detailed analysis on individual files.");if(s.security>0)c.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:t,totalLines:r,avgComplexity:Math.round(n*100)/100,totalIssues:o,issuesByCategory:s,performanceScore:a,recommendations:c}}import wd from"path";async function gx(e={}){let t=performance.now(),r=e.root||process.cwd(),n=await it(),o=n.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${o.toUpperCase()}${n.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let s,i;if(o==="ssg"){let{generateStaticSite:c}=await import("./chunk-73k79n7q.js");s=await c({pagesDir:wd.join(n.root||".",n.pagesDir||n.build?.pagesDir||"pages"),publicDir:n.publicDir||n.build?.publicDir||"public",outputDir:n.build?.outputDir||"dist",generate404:n.build?.generate404??!0,minify:n.build?.minify??!0,cleanOutput:n.build?.cleanOutput??!0,...e.ssg})}else{let{buildForProduction:c}=await import("./chunk-30rkn2ym.js");i=await c({outputDir:".output",debug:e.debug,...e.ssr})}let a=Math.round(performance.now()-t);return{mode:o,ssg:s,ssr:i,duration:a}}import br from"path";var ms=/<script\b[^>]*\bserver\b/i,vd=/<script\b[^>]*\bclient\b/i;async function wx(e){let t=performance.now(),r=await it(e),n=e||r.root||process.cwd(),o=[r.build?.pagesDir||r.pagesDir||"pages",r.componentsDir||"components",r.layoutsDir||"layouts",r.partialsDir||"partials"].map((a)=>br.resolve(n,a)),s=[],i=0;for(let a of o){let c=await hs(a);for(let l of c){i++;let d=await Bun.file(l).text();if(ms.test(d))s.push(br.relative(n,l))}}return{mode:s.length>0?"ssr":"ssg",serverScriptFiles:s,totalFilesScanned:i,scanDurationMs:Math.round(performance.now()-t)}}async function vx(e){let t=await it(e),r=e||t.root||process.cwd(),n=br.resolve(r,t.componentsDir||"components"),o=[],s=await hs(n);for(let i of s){let a=await Bun.file(i).text(),c=ms.test(a),l=vd.test(a)||/<script\b(?![^>]*\bserver\b)[^>]*>/i.test(a)&&!c;if(c&&l){let d=br.relative(r,i);o.push({file:d,message:`Component "${d}" has both <script server> and <script client>. `+"Components should be server OR client \u2014 compose them via props/slots."})}}return o}async function hs(e){let t=[];try{let r=new Bun.Glob("**/*.stx");for await(let n of r.scan({cwd:e,absolute:!0}))t.push(n)}catch{}return t}var gs={treeShake:!0,deadCodeElimination:!0,constantFolding:!0,stringPooling:!1,minifyHtml:!0,removeDevCode:!0,constants:{},preserveDirectives:[],target:"production"},ys=["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty","extends","section","endsection","yield","parent","include","includeIf","includeWhen","includeFirst","once","endonce","push","endpush","prepend","endprepend","stack","component","endcomponent","slot","endslot","props","auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole","csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file","translate","lang","choice","meta","title","seo","jsonld","canonical","robots","sitemap","ts","endts","js","endjs","css","endcss","markdown","endmarkdown","verbatim","endverbatim","env","production","debug","isset","endisset","empty","endempty"];function xs(e){let t=new Map,r=/@(\w+)/g,n,o=1,s=0;while((n=r.exec(e))!==null){let i=n[1],a=e.slice(s,n.index);o+=(a.match(/\n/g)||[]).length,s=n.index;let c=n.index-e.lastIndexOf(`
252
- `,n.index-1);if(ys.includes(i)){let l=t.get(i);if(l)l.count++,l.locations.push({line:o,column:c});else t.set(i,{name:i,count:1,locations:[{line:o,column:c}]})}}return Array.from(t.values())}function $d(e,t=[]){let r=xs(e),n=new Set(r.map((o)=>o.name));for(let o of t)n.add(o);for(let o of Array.from(n))if(!o.startsWith("end"))n.add(`end${o}`);return ys.filter((o)=>!n.has(o))}function Sd(e){let t=[],r={conditionals:["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","isset","endisset"],loops:["for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty"],includes:["include","includeIf","includeWhen","includeFirst","once","endonce","extends","section","endsection","yield","parent","push","endpush","prepend","endprepend","stack"],components:["component","endcomponent","slot","endslot","props"],auth:["auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole"],forms:["csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file"],i18n:["translate","lang","choice"],seo:["meta","title","seo","jsonld","canonical","robots","sitemap"]},n=new Set;for(let s of e)for(let[i,a]of Object.entries(r))if(a.includes(s)){n.add(i);break}for(let s of n)t.push(`import { process${jd(s)} } from './${s}'`);let o=e.filter((s)=>!s.startsWith("end")).map((s)=>` '${s}': true`).join(`,
250
+ `).length,o={conditionals:(e.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(e.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(e.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};o.total=o.conditionals+o.loops+o.includes+o.custom;let s=(e.match(/\{\{[\s\S]*?\}\}/g)||[]).length,i=(e.match(/\{!![\s\S]*?!!\}/g)||[]).length,a=(e.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,c=s+i+a,l=(e.match(/<[A-Z][^>]*>/g)||[]).length,d=(e.match(/@(?:layout|extends)\(/g)||[]).length,u=0,p=0;for(let g of t)if(/@(?:if|unless|foreach|for|while|section)\b/.test(g)&&!/@end/.test(g)&&!/@else/.test(g))p++,u=Math.max(u,p);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(g))p--;let h=u>=4?3:0,f=Math.min(10,Math.ceil(o.total*0.5+c*0.1+l*0.3+(n>10?n*0.05:0)+h));return{lines:t.length,characters:e.length,directives:o,expressions:c,components:l,layouts:d,scriptLines:n,complexity:f}}function yd(e,t){let r=[],n=ms(e,"if","endif");if(n>0)r.push({type:"error",category:"syntax",message:`Found ${n} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=ms(e,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let s=e.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(s&&s.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let i=(e.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(i>0)r.push({type:"warning",category:"security",message:`Found ${i} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let a=e.match(/<img[^>]*>/g);if(a){let d=a.filter((u)=>!u.includes("alt="));if(d.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${d.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let c=e.split(`
251
+ `).filter((d)=>d.length>120);if(c.length>0)r.push({type:"info",category:"maintainability",message:`Found ${c.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let l=(e.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(l>3)r.push({type:"info",category:"maintainability",message:`Found ${l} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function xd(e,t){let r=[];if(t.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(t.complexity>5&&t.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(t.lines>100&&t.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(t.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let n=e.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(n&&n.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(t.directives.total===0&&t.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(t.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function bd(e,t){let r=1;if(r+=t.directives.conditionals*0.1,r+=t.directives.loops*0.5,r+=t.directives.includes*2,r+=t.expressions*0.05,r+=t.components*1,t.scriptLines>10)r+=t.scriptLines*0.1;let n;if(t.expressions===0&&t.directives.total===0)n="high";else if(t.expressions<5&&t.directives.total<3)n="medium";else n="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(n==="low"&&t.directives.total>5)o.push("Reduce dynamic content for better caching");if(t.components===0&&t.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:t.complexity,cacheability:n,recommendations:o}}function ms(e,t,r){let n=e.replace(/<!--[\s\S]*?-->/g,""),o=(n.match(new RegExp(`@${t}\\b`,"g"))||[]).length,s=(n.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-s)}async function fx(e=["**/*.stx"],t){let r=[],n=[];for(let s of e){let i=await Array.fromAsync(new Bun.Glob(s).scan({cwd:t||process.cwd(),onlyFiles:!0,absolute:!0}));n.push(...i.filter((a)=>a.endsWith(".stx")))}for(let s of n)try{let i=await hd(s);r.push(i)}catch(i){console.warn(`Failed to analyze ${s}:`,i)}let o=wd(r);return{results:r,summary:o}}function wd(e){let t=e.length,r=e.reduce((l,d)=>l+d.metrics.lines,0),n=t>0?e.reduce((l,d)=>l+d.metrics.complexity,0)/t:0,o=e.reduce((l,d)=>l+d.issues.length,0),s={};e.forEach((l)=>{l.issues.forEach((d)=>{s[d.category]=(s[d.category]||0)+1})});let i=t>0?e.reduce((l,d)=>l+d.performance.estimatedRenderTime,0)/t:0,a=Math.max(1,Math.min(10,Math.round(10-i/2-n/2))),c=[];if(n>6)c.push("Project has high average complexity. Consider refactoring complex templates.");if(o>t*2)c.push("High number of issues detected. Run detailed analysis on individual files.");if(s.security>0)c.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:t,totalLines:r,avgComplexity:Math.round(n*100)/100,totalIssues:o,issuesByCategory:s,performanceScore:a,recommendations:c}}import vd from"path";async function yx(e={}){let t=performance.now(),r=e.root||process.cwd(),n=await at(),o=n.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${o.toUpperCase()}${n.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let s,i;if(o==="ssg"){let{generateStaticSite:c}=await import("./chunk-f72nnjy4.js");s=await c({pagesDir:vd.join(n.root||".",n.pagesDir||n.build?.pagesDir||"pages"),publicDir:n.publicDir||n.build?.publicDir||"public",outputDir:n.build?.outputDir||"dist",generate404:n.build?.generate404??!0,minify:n.build?.minify??!0,cleanOutput:n.build?.cleanOutput??!0,...e.ssg})}else{let{buildForProduction:c}=await import("./chunk-8wydx2we.js");i=await c({outputDir:".output",debug:e.debug,...e.ssr})}let a=Math.round(performance.now()-t);return{mode:o,ssg:s,ssr:i,duration:a}}import wr from"path";var hs=/<script\b[^>]*\bserver\b/i,$d=/<script\b[^>]*\bclient\b/i;async function vx(e){let t=performance.now(),r=await at(e),n=e||r.root||process.cwd(),o=[r.build?.pagesDir||r.pagesDir||"pages",r.componentsDir||"components",r.layoutsDir||"layouts",r.partialsDir||"partials"].map((a)=>wr.resolve(n,a)),s=[],i=0;for(let a of o){let c=await gs(a);for(let l of c){i++;let d=await Bun.file(l).text();if(hs.test(d))s.push(wr.relative(n,l))}}return{mode:s.length>0?"ssr":"ssg",serverScriptFiles:s,totalFilesScanned:i,scanDurationMs:Math.round(performance.now()-t)}}async function $x(e){let t=await at(e),r=e||t.root||process.cwd(),n=wr.resolve(r,t.componentsDir||"components"),o=[],s=await gs(n);for(let i of s){let a=await Bun.file(i).text(),c=hs.test(a),l=$d.test(a)||/<script\b(?![^>]*\bserver\b)[^>]*>/i.test(a)&&!c;if(c&&l){let d=wr.relative(r,i);o.push({file:d,message:`Component "${d}" has both <script server> and <script client>. `+"Components should be server OR client \u2014 compose them via props/slots."})}}return o}async function gs(e){let t=[];try{let r=new Bun.Glob("**/*.stx");for await(let n of r.scan({cwd:e,absolute:!0}))t.push(n)}catch{}return t}var ys={treeShake:!0,deadCodeElimination:!0,constantFolding:!0,stringPooling:!1,minifyHtml:!0,removeDevCode:!0,constants:{},preserveDirectives:[],target:"production"},xs=["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty","extends","section","endsection","yield","parent","include","includeIf","includeWhen","includeFirst","once","endonce","push","endpush","prepend","endprepend","stack","component","endcomponent","slot","endslot","props","auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole","csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file","translate","lang","choice","meta","title","seo","jsonld","canonical","robots","sitemap","ts","endts","js","endjs","css","endcss","markdown","endmarkdown","verbatim","endverbatim","env","production","debug","isset","endisset","empty","endempty"];function bs(e){let t=new Map,r=/@(\w+)/g,n,o=1,s=0;while((n=r.exec(e))!==null){let i=n[1],a=e.slice(s,n.index);o+=(a.match(/\n/g)||[]).length,s=n.index;let c=n.index-e.lastIndexOf(`
252
+ `,n.index-1);if(xs.includes(i)){let l=t.get(i);if(l)l.count++,l.locations.push({line:o,column:c});else t.set(i,{name:i,count:1,locations:[{line:o,column:c}]})}}return Array.from(t.values())}function Sd(e,t=[]){let r=bs(e),n=new Set(r.map((o)=>o.name));for(let o of t)n.add(o);for(let o of Array.from(n))if(!o.startsWith("end"))n.add(`end${o}`);return xs.filter((o)=>!n.has(o))}function kd(e){let t=[],r={conditionals:["if","else","elseif","endif","unless","endunless","switch","case","default","endswitch","isset","endisset"],loops:["for","endfor","foreach","endforeach","forelse","endforelse","while","endwhile","break","continue","empty"],includes:["include","includeIf","includeWhen","includeFirst","once","endonce","extends","section","endsection","yield","parent","push","endpush","prepend","endprepend","stack"],components:["component","endcomponent","slot","endslot","props"],auth:["auth","endauth","guest","endguest","can","endcan","cannot","endcannot","role","endrole","hasRole","endhasRole","hasAnyRole","endhasAnyRole"],forms:["csrf","method","error","enderror","old","input","textarea","select","checkbox","radio","file"],i18n:["translate","lang","choice"],seo:["meta","title","seo","jsonld","canonical","robots","sitemap"]},n=new Set;for(let s of e)for(let[i,a]of Object.entries(r))if(a.includes(s)){n.add(i);break}for(let s of n)t.push(`import { process${Rd(s)} } from './${s}'`);let o=e.filter((s)=>!s.startsWith("end")).map((s)=>` '${s}': true`).join(`,
253
253
  `);return`// Tree-shaken directive bundle
254
254
  // Only includes: ${e.join(", ")}
255
255
  ${t.join(`
@@ -262,9 +262,9 @@ ${o}
262
262
  export function isDirectiveActive(name: string): boolean {
263
263
  return name in activeDirectives
264
264
  }
265
- `}function kd(e,t={}){let r=[],n=/@if\(([^)]+)\)[\s\S]*?@endif/g,o=e.matchAll(n);for(let l of o){let d=l[1].trim();if(qn(d,t)===!1)r.push({start:l.index,end:l.index+l[0].length,reason:`@if condition always false: ${d}`})}let s=/@unless\(([^)]+)\)[\s\S]*?@endunless/g,i=e.matchAll(s);for(let l of i){let d=l[1].trim();if(qn(d,t)===!0)r.push({start:l.index,end:l.index+l[0].length,reason:`@unless condition always true: ${d}`})}let a=/@env\(['"]development['"]\)[\s\S]*?@endenv/g;if(t.__ENV__==="production"){let l=e.matchAll(a);for(let d of l)r.push({start:d.index,end:d.index+d[0].length,reason:"Development-only code in production build"})}let c=/@debug[\s\S]*?@enddebug/g;if(t.__ENV__==="production"){let l=e.matchAll(c);for(let d of l)r.push({start:d.index,end:d.index+d[0].length,reason:"Debug code in production build"})}return r}function Td(e,t={}){let r=kd(e,t),n=[];r.sort((s,i)=>i.start-s.start);let o=e;for(let s of r)o=o.slice(0,s.start)+o.slice(s.end),n.push(s.reason);return{content:o,removed:n}}function qn(e,t){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(/^\d+$/.test(e))return Number.parseInt(e,10);if(/^\d+\.\d+$/.test(e))return Number.parseFloat(e);if(/^['"].*['"]$/.test(e))return e.slice(1,-1);if(e in t)return t[e];let r=e.match(/^(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);if(r){let[,n,o,s]=r,i=n in t?t[n]:void 0,a=qn(s,t);if(i!==void 0&&a!==void 0)switch(o){case"==":case"===":return i===a;case"!=":case"!==":return i!==a;case">":return i>a;case"<":return i<a;case">=":return i>=a;case"<=":return i<=a}}return}function Cd(e,t){let r=[],n=e;return n=n.replace(/\{\{\s*(\w+)\s*\}\}/g,(o,s)=>{if(s in t)return r.push(`{{ ${s} }} -> ${t[s]}`),String(t[s]);return o}),n=n.replace(/\{\{\s*(\d+)\s*([+\-*])\s*(\d+)\s*\}\}/g,(o,s,i,a)=>{let c=Number.parseInt(s,10),l=Number.parseInt(a,10),d;switch(i){case"+":d=c+l;break;case"-":d=c-l;break;case"*":d=c*l;break;default:return o}return r.push(`{{ ${s} ${i} ${a} }} -> ${d}`),String(d)}),{content:n,folded:r}}function Ed(e){let t=e,r=[],n=0;t=t.replace(/<(pre|code|script|style)([^>]*)>([\s\S]*?)<\/\1>/gi,(o)=>{let s=`__PRESERVE_${n++}__`;return r.push({marker:s,content:o}),s}),t=t.replace(/\{\{([\s\S]*?)\}\}/g,(o)=>{let s=`__PRESERVE_${n++}__`;return r.push({marker:s,content:o}),s}),t=t.replace(/\{\{--([\s\S]*?)--\}\}/g,""),t=t.replace(/<!--[\s\S]*?-->/g,""),t=t.replace(/>\s+</g,"><"),t=t.replace(/^\s+/gm,""),t=t.replace(/\s+$/gm,""),t=t.replace(/\s{2,}/g," ");for(let{marker:o,content:s}of r){let i=t.indexOf(o);if(i!==-1)t=t.slice(0,i)+s+t.slice(i+o.length)}return t.trim()}function _d(e){let t=new Map,r=new Map,n=/(['"])([^'"]{10,})\1/g,o;while((o=n.exec(e))!==null){let a=o[2];r.set(a,(r.get(a)||0)+1)}let s=0,i=e;for(let[a,c]of r)if(c>1){let l=`__STR_${s++}__`;t.set(l,a);let d=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(['"])${d}\\1`,"g");i=i.replace(u,l)}return{content:i,pool:t,count:t.size}}function Ad(e,t={}){let r={...gs,...t},n=new Blob([e]).size,o=e,s=[],i=[],a=[],c=[],l=0;if(r.target==="production")r.constants={...r.constants,__ENV__:"production"};if(r.deadCodeElimination){let p=Td(o,r.constants);if(o=p.content,p.removed.length>0)s.push("Dead code elimination"),i.push(...p.removed.map((h)=>`Removed: ${h}`))}if(r.constantFolding&&Object.keys(r.constants).length>0){let p=Cd(o,r.constants);if(o=p.content,c=p.folded,c.length>0)s.push("Constant folding")}if(r.treeShake){if(a=$d(o,r.preserveDirectives),a.length>0)s.push("Tree shaking")}if(r.stringPooling){let p=_d(o);if(o=p.content,l=p.count,l>0)s.push("String pooling")}if(r.minifyHtml){let p=Ed(o);if(p.length<o.length)o=p,s.push("HTML minification")}let d=new Blob([o]).size,u=n>0?Math.round((1-d/n)*100):0;return{content:o,originalSize:n,optimizedSize:d,reduction:u,appliedOptimizations:s,removedDirectives:a,foldedConstants:c,pooledStrings:l,warnings:i}}async function Sx(e,t={}){let r={...gs,...t},n=new Map,o=[],s=0,i=0,a=new Set;for(let[u,p]of e){let h=Ad(p,r);n.set(u,h),s+=h.originalSize,i+=h.optimizedSize,o.push(...h.warnings.map((g)=>`${u}: ${g}`));let f=xs(p);for(let g of f)a.add(g.name)}let c;if(r.treeShake)c=Sd(Array.from(a));let l;if(r.stringPooling)l=new Map;let d=s>0?Math.round((1-i/s)*100):0;return{templates:n,directiveBundle:c,stringPool:l,totalOriginalSize:s,totalOptimizedSize:i,overallReduction:d,warnings:o}}function jd(e){return e.charAt(0).toUpperCase()+e.slice(1)}function vs(e,t){let r={},n=e.trim();if(n.startsWith("{"))n=n.slice(1);if(n.endsWith("}"))n=n.slice(0,-1);if(n=n.trim(),!n)return r;let o=0;while(o<n.length){while(o<n.length&&/\s/.test(n[o]))o++;if(o>=n.length)break;let s="";if(n[o]==='"'||n[o]==="'"){let c=n[o];o++;while(o<n.length&&n[o]!==c)if(n[o]==="\\"&&o+1<n.length)s+=n[o+1],o+=2;else s+=n[o],o++;o++}else while(o<n.length&&/[\w$]/.test(n[o]))s+=n[o],o++;while(o<n.length&&/\s/.test(n[o]))o++;if(n[o]===":")o++;while(o<n.length&&/\s/.test(n[o]))o++;let i,a=o;if(n[o]==='"'||n[o]==="'"){let c=n[o];o++;let l="";while(o<n.length&&n[o]!==c)if(n[o]==="\\"&&o+1<n.length)l+=n[o+1],o+=2;else l+=n[o],o++;o++,i=l}else if(n[o]==="{"){let c=1;o++;while(o<n.length&&c>0){if(n[o]==="{")c++;else if(n[o]==="}")c--;else if(n[o]==='"'||n[o]==="'"){let d=n[o];o++;while(o<n.length&&n[o]!==d){if(n[o]==="\\")o++;o++}}o++}let l=n.slice(a,o);i=vs(l,t)}else if(n[o]==="["){let c=1;o++;while(o<n.length&&c>0){if(n[o]==="[")c++;else if(n[o]==="]")c--;else if(n[o]==='"'||n[o]==="'"){let d=n[o];o++;while(o<n.length&&n[o]!==d){if(n[o]==="\\")o++;o++}}o++}let l=n.slice(a,o);try{i=JSON.parse(l.replace(/'/g,'"'))}catch{i=l}}else{let c="";while(o<n.length&&n[o]!==","&&!/\s/.test(n[o]))c+=n[o],o++;if(c=c.trim(),c==="true")i=!0;else if(c==="false")i=!1;else if(c==="null")i=null;else if(c==="undefined")i=void 0;else if(/^-?\d+(\.\d+)?$/.test(c))i=Number(c);else if(c in t)i=t[c];else i=c}if(s)r[s]=i;while(o<n.length&&/\s/.test(n[o]))o++;if(n[o]===",")o++}return r}function _x(e,t,r){let n=[];for(let[o,s]of Object.entries(t)){let i=e[o];if(s.required&&(i===void 0||i===null)){n.push(`Component "${r}": Missing required prop "${o}"`);continue}if(i===void 0||i===null)continue;let a=Array.isArray(s.type)?s.type:[s.type];if(!a.includes("any")){let c=Rd(i);if(!a.includes(c))n.push(`Component "${r}": Prop "${o}" expected ${a.join(" | ")}, got ${c}`)}if(s.validator&&!s.validator(i))n.push(`Component "${r}": Prop "${o}" failed custom validation`)}return n}function Ax(e,t){let r={...e};for(let[n,o]of Object.entries(t))if(r[n]===void 0&&o.default!==void 0)r[n]=typeof o.default==="function"?o.default():o.default;return r}function Rd(e){if(Array.isArray(e))return"array";if(e===null)return"null";return typeof e}var Md={name:"component",handler:async(e,t,r,n)=>{if(t.length<1)return vr("Component","component directive requires at least the component name",wr.INVALID_DIRECTIVE_SYNTAX);let o=t[0].replace(/['"]/g,""),s={};if(t.length>1)try{let d=t.slice(1).join(",").trim();if(d.startsWith("{")){if(s=bs(d,r),Object.keys(s).length===0)s=vs(d,r)}else{let u=d.trim(),p=r[u];if(p&&typeof p==="object"&&!Array.isArray(p))s=p}}catch(d){let u=d instanceof Error?d.message:String(d);return console.error("Component props parsing error:",u),vr("Component",`Error parsing component props: ${u}`,wr.EVALUATION_ERROR)}let i=r.__stx_options||{},a=i.componentsDir||"components",c=new Set;if(!r.__processedComponents)r.__processedComponents=new Set;let l=r.__processedComponents;try{return await ws(o,s,"",a,r,n,i,l,c)}catch(d){console.error("Component rendering error:",d);let u=d instanceof Error?d.message:String(d);return vr("Component",`Error rendering component: ${u}`,wr.COMPONENT_RENDER_ERROR)}},hasEndTag:!1};function jx(){return[Md]}import{mkdir as Dd,readFile as Pd,readdir as Od,stat as $s,writeFile as Id}from"fs/promises";import ve from"path";var Cs=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Ld(e){return e.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Xn(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Fd(e){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(e)&&!e.startsWith("xml")&&!/[A-Z]/.test(e)}function Nd(e){if(e===!0)return"open";if(e==="open"||e==="closed")return e;return!1}async function Bd(e){let t=[];async function r(n){let o=await Od(n,{withFileTypes:!0});o.sort((s,i)=>s.name.localeCompare(i.name));for(let s of o){let i=ve.join(n,s.name);if(s.isDirectory()){if(!s.name.startsWith(".")&&s.name!=="node_modules")await r(i)}else if(s.isFile()&&s.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(s.name))t.push(i)}}return await r(e),t}function zd(e,t){let r=e.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let n=r[1].trim();if(!n)return{};try{return JSON.parse(n)}catch(o){throw Error(`${t}: <script component> must contain JSON metadata (${o.message})`)}}function Ud(e,t){let r={},n=[...e.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of n){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let s;try{s=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(c){throw Error(`${t}: failed to transpile <script client> (${c.message})`)}let i=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,a;while(a=i.exec(s)){let c=a[1];if(Cs.has(c))throw Error(`${t}: client method "${c}" is reserved`);let l=i.lastIndex,d=1,u="",p=!1,h=l;for(;h<s.length&&d>0;h++){let g=s[h];if(p){p=!1;continue}if(u){if(g==="\\")p=!0;else if(g===u)u="";continue}if(g==='"'||g==="'"||g==="`")u=g;else if(g==="{")d++;else if(g==="}")d--}if(d!==0)throw Error(`${t}: unterminated client function "${c}"`);let f=a[0].includes("async")?"async ":"";r[c]=`${f}${c}(${a[2]}) {${s.slice(l,h-1)}}`,i.lastIndex=h}}return r}function Hd(e){let t=e.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(t?t[1]:e).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Ss(e){return[...e.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((t)=>t[1].trim()).filter(Boolean).join(`
265
+ `}function Td(e,t={}){let r=[],n=/@if\(([^)]+)\)[\s\S]*?@endif/g,o=e.matchAll(n);for(let l of o){let d=l[1].trim();if(Xn(d,t)===!1)r.push({start:l.index,end:l.index+l[0].length,reason:`@if condition always false: ${d}`})}let s=/@unless\(([^)]+)\)[\s\S]*?@endunless/g,i=e.matchAll(s);for(let l of i){let d=l[1].trim();if(Xn(d,t)===!0)r.push({start:l.index,end:l.index+l[0].length,reason:`@unless condition always true: ${d}`})}let a=/@env\(['"]development['"]\)[\s\S]*?@endenv/g;if(t.__ENV__==="production"){let l=e.matchAll(a);for(let d of l)r.push({start:d.index,end:d.index+d[0].length,reason:"Development-only code in production build"})}let c=/@debug[\s\S]*?@enddebug/g;if(t.__ENV__==="production"){let l=e.matchAll(c);for(let d of l)r.push({start:d.index,end:d.index+d[0].length,reason:"Debug code in production build"})}return r}function Cd(e,t={}){let r=Td(e,t),n=[];r.sort((s,i)=>i.start-s.start);let o=e;for(let s of r)o=o.slice(0,s.start)+o.slice(s.end),n.push(s.reason);return{content:o,removed:n}}function Xn(e,t){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(/^\d+$/.test(e))return Number.parseInt(e,10);if(/^\d+\.\d+$/.test(e))return Number.parseFloat(e);if(/^['"].*['"]$/.test(e))return e.slice(1,-1);if(e in t)return t[e];let r=e.match(/^(\w+)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/);if(r){let[,n,o,s]=r,i=n in t?t[n]:void 0,a=Xn(s,t);if(i!==void 0&&a!==void 0)switch(o){case"==":case"===":return i===a;case"!=":case"!==":return i!==a;case">":return i>a;case"<":return i<a;case">=":return i>=a;case"<=":return i<=a}}return}function Ed(e,t){let r=[],n=e;return n=n.replace(/\{\{\s*(\w+)\s*\}\}/g,(o,s)=>{if(s in t)return r.push(`{{ ${s} }} -> ${t[s]}`),String(t[s]);return o}),n=n.replace(/\{\{\s*(\d+)\s*([+\-*])\s*(\d+)\s*\}\}/g,(o,s,i,a)=>{let c=Number.parseInt(s,10),l=Number.parseInt(a,10),d;switch(i){case"+":d=c+l;break;case"-":d=c-l;break;case"*":d=c*l;break;default:return o}return r.push(`{{ ${s} ${i} ${a} }} -> ${d}`),String(d)}),{content:n,folded:r}}function _d(e){let t=e,r=[],n=0;t=t.replace(/<(pre|code|script|style)([^>]*)>([\s\S]*?)<\/\1>/gi,(o)=>{let s=`__PRESERVE_${n++}__`;return r.push({marker:s,content:o}),s}),t=t.replace(/\{\{([\s\S]*?)\}\}/g,(o)=>{let s=`__PRESERVE_${n++}__`;return r.push({marker:s,content:o}),s}),t=t.replace(/\{\{--([\s\S]*?)--\}\}/g,""),t=t.replace(/<!--[\s\S]*?-->/g,""),t=t.replace(/>\s+</g,"><"),t=t.replace(/^\s+/gm,""),t=t.replace(/\s+$/gm,""),t=t.replace(/\s{2,}/g," ");for(let{marker:o,content:s}of r){let i=t.indexOf(o);if(i!==-1)t=t.slice(0,i)+s+t.slice(i+o.length)}return t.trim()}function Ad(e){let t=new Map,r=new Map,n=/(['"])([^'"]{10,})\1/g,o;while((o=n.exec(e))!==null){let a=o[2];r.set(a,(r.get(a)||0)+1)}let s=0,i=e;for(let[a,c]of r)if(c>1){let l=`__STR_${s++}__`;t.set(l,a);let d=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(['"])${d}\\1`,"g");i=i.replace(u,l)}return{content:i,pool:t,count:t.size}}function jd(e,t={}){let r={...ys,...t},n=new Blob([e]).size,o=e,s=[],i=[],a=[],c=[],l=0;if(r.target==="production")r.constants={...r.constants,__ENV__:"production"};if(r.deadCodeElimination){let p=Cd(o,r.constants);if(o=p.content,p.removed.length>0)s.push("Dead code elimination"),i.push(...p.removed.map((h)=>`Removed: ${h}`))}if(r.constantFolding&&Object.keys(r.constants).length>0){let p=Ed(o,r.constants);if(o=p.content,c=p.folded,c.length>0)s.push("Constant folding")}if(r.treeShake){if(a=Sd(o,r.preserveDirectives),a.length>0)s.push("Tree shaking")}if(r.stringPooling){let p=Ad(o);if(o=p.content,l=p.count,l>0)s.push("String pooling")}if(r.minifyHtml){let p=_d(o);if(p.length<o.length)o=p,s.push("HTML minification")}let d=new Blob([o]).size,u=n>0?Math.round((1-d/n)*100):0;return{content:o,originalSize:n,optimizedSize:d,reduction:u,appliedOptimizations:s,removedDirectives:a,foldedConstants:c,pooledStrings:l,warnings:i}}async function kx(e,t={}){let r={...ys,...t},n=new Map,o=[],s=0,i=0,a=new Set;for(let[u,p]of e){let h=jd(p,r);n.set(u,h),s+=h.originalSize,i+=h.optimizedSize,o.push(...h.warnings.map((g)=>`${u}: ${g}`));let f=bs(p);for(let g of f)a.add(g.name)}let c;if(r.treeShake)c=kd(Array.from(a));let l;if(r.stringPooling)l=new Map;let d=s>0?Math.round((1-i/s)*100):0;return{templates:n,directiveBundle:c,stringPool:l,totalOriginalSize:s,totalOptimizedSize:i,overallReduction:d,warnings:o}}function Rd(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $s(e,t){let r={},n=e.trim();if(n.startsWith("{"))n=n.slice(1);if(n.endsWith("}"))n=n.slice(0,-1);if(n=n.trim(),!n)return r;let o=0;while(o<n.length){while(o<n.length&&/\s/.test(n[o]))o++;if(o>=n.length)break;let s="";if(n[o]==='"'||n[o]==="'"){let c=n[o];o++;while(o<n.length&&n[o]!==c)if(n[o]==="\\"&&o+1<n.length)s+=n[o+1],o+=2;else s+=n[o],o++;o++}else while(o<n.length&&/[\w$]/.test(n[o]))s+=n[o],o++;while(o<n.length&&/\s/.test(n[o]))o++;if(n[o]===":")o++;while(o<n.length&&/\s/.test(n[o]))o++;let i,a=o;if(n[o]==='"'||n[o]==="'"){let c=n[o];o++;let l="";while(o<n.length&&n[o]!==c)if(n[o]==="\\"&&o+1<n.length)l+=n[o+1],o+=2;else l+=n[o],o++;o++,i=l}else if(n[o]==="{"){let c=1;o++;while(o<n.length&&c>0){if(n[o]==="{")c++;else if(n[o]==="}")c--;else if(n[o]==='"'||n[o]==="'"){let d=n[o];o++;while(o<n.length&&n[o]!==d){if(n[o]==="\\")o++;o++}}o++}let l=n.slice(a,o);i=$s(l,t)}else if(n[o]==="["){let c=1;o++;while(o<n.length&&c>0){if(n[o]==="[")c++;else if(n[o]==="]")c--;else if(n[o]==='"'||n[o]==="'"){let d=n[o];o++;while(o<n.length&&n[o]!==d){if(n[o]==="\\")o++;o++}}o++}let l=n.slice(a,o);try{i=JSON.parse(l.replace(/'/g,'"'))}catch{i=l}}else{let c="";while(o<n.length&&n[o]!==","&&!/\s/.test(n[o]))c+=n[o],o++;if(c=c.trim(),c==="true")i=!0;else if(c==="false")i=!1;else if(c==="null")i=null;else if(c==="undefined")i=void 0;else if(/^-?\d+(\.\d+)?$/.test(c))i=Number(c);else if(c in t)i=t[c];else i=c}if(s)r[s]=i;while(o<n.length&&/\s/.test(n[o]))o++;if(n[o]===",")o++}return r}function Ax(e,t,r){let n=[];for(let[o,s]of Object.entries(t)){let i=e[o];if(s.required&&(i===void 0||i===null)){n.push(`Component "${r}": Missing required prop "${o}"`);continue}if(i===void 0||i===null)continue;let a=Array.isArray(s.type)?s.type:[s.type];if(!a.includes("any")){let c=Md(i);if(!a.includes(c))n.push(`Component "${r}": Prop "${o}" expected ${a.join(" | ")}, got ${c}`)}if(s.validator&&!s.validator(i))n.push(`Component "${r}": Prop "${o}" failed custom validation`)}return n}function jx(e,t){let r={...e};for(let[n,o]of Object.entries(t))if(r[n]===void 0&&o.default!==void 0)r[n]=typeof o.default==="function"?o.default():o.default;return r}function Md(e){if(Array.isArray(e))return"array";if(e===null)return"null";return typeof e}var Dd={name:"component",handler:async(e,t,r,n)=>{if(t.length<1)return $r("Component","component directive requires at least the component name",vr.INVALID_DIRECTIVE_SYNTAX);let o=t[0].replace(/['"]/g,""),s={};if(t.length>1)try{let d=t.slice(1).join(",").trim();if(d.startsWith("{")){if(s=ws(d,r),Object.keys(s).length===0)s=$s(d,r)}else{let u=d.trim(),p=r[u];if(p&&typeof p==="object"&&!Array.isArray(p))s=p}}catch(d){let u=d instanceof Error?d.message:String(d);return console.error("Component props parsing error:",u),$r("Component",`Error parsing component props: ${u}`,vr.EVALUATION_ERROR)}let i=r.__stx_options||{},a=i.componentsDir||"components",c=new Set;if(!r.__processedComponents)r.__processedComponents=new Set;let l=r.__processedComponents;try{return await vs(o,s,"",a,r,n,i,l,c)}catch(d){console.error("Component rendering error:",d);let u=d instanceof Error?d.message:String(d);return $r("Component",`Error rendering component: ${u}`,vr.COMPONENT_RENDER_ERROR)}},hasEndTag:!1};function Rx(){return[Dd]}import{mkdir as Pd,readFile as Od,readdir as Id,stat as Ss,writeFile as Ld}from"fs/promises";import $e from"path";var Es=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Fd(e){return e.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Jn(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Nd(e){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(e)&&!e.startsWith("xml")&&!/[A-Z]/.test(e)}function Bd(e){if(e===!0)return"open";if(e==="open"||e==="closed")return e;return!1}async function zd(e){let t=[];async function r(n){let o=await Id(n,{withFileTypes:!0});o.sort((s,i)=>s.name.localeCompare(i.name));for(let s of o){let i=$e.join(n,s.name);if(s.isDirectory()){if(!s.name.startsWith(".")&&s.name!=="node_modules")await r(i)}else if(s.isFile()&&s.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(s.name))t.push(i)}}return await r(e),t}function Ud(e,t){let r=e.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let n=r[1].trim();if(!n)return{};try{return JSON.parse(n)}catch(o){throw Error(`${t}: <script component> must contain JSON metadata (${o.message})`)}}function Hd(e,t){let r={},n=[...e.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of n){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let s;try{s=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(c){throw Error(`${t}: failed to transpile <script client> (${c.message})`)}let i=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,a;while(a=i.exec(s)){let c=a[1];if(Es.has(c))throw Error(`${t}: client method "${c}" is reserved`);let l=i.lastIndex,d=1,u="",p=!1,h=l;for(;h<s.length&&d>0;h++){let g=s[h];if(p){p=!1;continue}if(u){if(g==="\\")p=!0;else if(g===u)u="";continue}if(g==='"'||g==="'"||g==="`")u=g;else if(g==="{")d++;else if(g==="}")d--}if(d!==0)throw Error(`${t}: unterminated client function "${c}"`);let f=a[0].includes("async")?"async ":"";r[c]=`${f}${c}(${a[2]}) {${s.slice(l,h-1)}}`,i.lastIndex=h}}return r}function Wd(e){let t=e.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(t?t[1]:e).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function ks(e){return[...e.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((t)=>t[1].trim()).filter(Boolean).join(`
266
266
 
267
- `)}function Wd(e){let t=new Set;return{template:e.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(r,n,o,s,i)=>{let a=n.toLowerCase();t.add(a);let c=(o||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${a}="${i}"${c?` data-stx-mod-${a}="${c}"`:""}`}),eventTypes:[...t].sort()}}function Vd(e){let t=[];return{template:e.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(r,n,o,s)=>{let i=t.length;return t.push({id:i,name:n,expression:s}),` data-stx-bind-${i}=""`}),bindings:t}}function qd(e){let t=new Set;for(let r of e.matchAll(/<slot\b([^>]*)>/gi))t.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...t].map((r)=>({name:r}))}function Xd(e){return[...new Set([...e.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((t)=>t[1]))].sort().map((t)=>({name:t}))}function Jd(e,t){if(!t||!new Set(["string","number","boolean","object","array"]).has(t.type))throw Error(`Property "${e}" must declare one of: string, number, boolean, object, array`);return{...t,reflect:t.reflect??t.attribute!==!1}}async function Yd(e,t,r){let n=ve.isAbsolute(t.file)?t.file:ve.resolve(e,t.file),o=await Pd(n,"utf8"),s=zd(o,n),i=ve.basename(n,".stx"),a=t.name||s.name||Ld(i),c=`${Xn(r.prefix||"stx")}-${Xn(i)}`,l=t.tag||s.tag||c;if(!a||!/^[A-Za-z_$][\w$]*$/.test(a))throw Error(`${n}: invalid component class name "${a}"`);if(!Fd(l))throw Error(`${n}: invalid custom-element tag "${l}"; tags must be lowercase and contain a hyphen`);let d=t.properties||s.properties||s.props||{},u=Object.fromEntries(Object.entries(d).map(([y,b])=>[y,Jd(y,b)])),p=Wd(Hd(o)),h=Vd(p.template),f=s.methods||{},g=t.methods||{},x=Ud(o,n);return{file:ve.relative(e,n),sourcePath:n,name:a,tag:l,description:t.description||s.description||"",template:h.template,styles:Ss(o),shadowMode:Nd(t.shadowDOM??s.shadowDOM??r.shadowDOM),progressive:t.progressive??s.progressive??r.progressive??!0,properties:u,events:t.events||s.events||{},methods:{...f,...g,...x},eventTypes:p.eventTypes,bindings:h.bindings,slots:qd(h.template),cssProperties:Xd(Ss(o))}}function Kd(){let e=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),t=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
267
+ `)}function Vd(e){let t=new Set;return{template:e.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(r,n,o,s,i)=>{let a=n.toLowerCase();t.add(a);let c=(o||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${a}="${i}"${c?` data-stx-mod-${a}="${c}"`:""}`}),eventTypes:[...t].sort()}}function qd(e){let t=[];return{template:e.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(r,n,o,s)=>{let i=t.length;return t.push({id:i,name:n,expression:s}),` data-stx-bind-${i}=""`}),bindings:t}}function Xd(e){let t=new Set;for(let r of e.matchAll(/<slot\b([^>]*)>/gi))t.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...t].map((r)=>({name:r}))}function Jd(e){return[...new Set([...e.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((t)=>t[1]))].sort().map((t)=>({name:t}))}function Yd(e,t){if(!t||!new Set(["string","number","boolean","object","array"]).has(t.type))throw Error(`Property "${e}" must declare one of: string, number, boolean, object, array`);return{...t,reflect:t.reflect??t.attribute!==!1}}async function Kd(e,t,r){let n=$e.isAbsolute(t.file)?t.file:$e.resolve(e,t.file),o=await Od(n,"utf8"),s=Ud(o,n),i=$e.basename(n,".stx"),a=t.name||s.name||Fd(i),c=`${Jn(r.prefix||"stx")}-${Jn(i)}`,l=t.tag||s.tag||c;if(!a||!/^[A-Za-z_$][\w$]*$/.test(a))throw Error(`${n}: invalid component class name "${a}"`);if(!Nd(l))throw Error(`${n}: invalid custom-element tag "${l}"; tags must be lowercase and contain a hyphen`);let d=t.properties||s.properties||s.props||{},u=Object.fromEntries(Object.entries(d).map(([y,b])=>[y,Yd(y,b)])),p=Vd(Wd(o)),h=qd(p.template),f=s.methods||{},g=t.methods||{},x=Hd(o,n);return{file:$e.relative(e,n),sourcePath:n,name:a,tag:l,description:t.description||s.description||"",template:h.template,styles:ks(o),shadowMode:Bd(t.shadowDOM??s.shadowDOM??r.shadowDOM),progressive:t.progressive??s.progressive??r.progressive??!0,properties:u,events:t.events||s.events||{},methods:{...f,...g,...x},eventTypes:p.eventTypes,bindings:h.bindings,slots:Xd(h.template),cssProperties:Jd(ks(o))}}function Gd(){let e=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),t=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
268
268
 
269
269
  const escapeHTML = (value) => String(value ?? '')
270
270
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -514,7 +514,7 @@ export function defineComponent(Component, definition) {
514
514
  }
515
515
  return Component;
516
516
  }
517
- `}function Gd(e){let t=JSON.stringify({tag:e.tag,template:e.template,styles:e.styles,shadowMode:e.shadowMode,progressive:e.progressive,properties:e.properties,eventTypes:e.eventTypes,bindings:e.bindings},null,2),r=Object.entries(e.methods).map(([n,o])=>{if(Cs.has(n))throw Error(`${e.sourcePath}: method "${n}" is reserved`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(o.trim()))return` ${o.trim()}`;return` ${n}($event) {
517
+ `}function Zd(e){let t=JSON.stringify({tag:e.tag,template:e.template,styles:e.styles,shadowMode:e.shadowMode,progressive:e.progressive,properties:e.properties,eventTypes:e.eventTypes,bindings:e.bindings},null,2),r=Object.entries(e.methods).map(([n,o])=>{if(Es.has(n))throw Error(`${e.sourcePath}: method "${n}" is reserved`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(o.trim()))return` ${o.trim()}`;return` ${n}($event) {
518
518
  ${o}
519
519
  }`}).join(`
520
520
 
@@ -527,8 +527,8 @@ ${r}
527
527
 
528
528
  defineComponent(${e.name}, ${t});
529
529
  export default ${e.name};
530
- `}function $r(e){switch(e.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Zd(e){let t=Object.entries(e.properties).map(([s,i])=>` ${s}${i.required?"":"?"}: ${$r(i)}`).join(`
531
- `),r=Object.entries(e.properties).map(([s,i])=>` ${s}: ${$r(i)}`).join(`
530
+ `}function Sr(e){switch(e.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Qd(e){let t=Object.entries(e.properties).map(([s,i])=>` ${s}${i.required?"":"?"}: ${Sr(i)}`).join(`
531
+ `),r=Object.entries(e.properties).map(([s,i])=>` ${s}: ${Sr(i)}`).join(`
532
532
  `),n=Object.entries(e.events).map(([s,i])=>` ${JSON.stringify(s)}: CustomEvent<${i.detailType||"unknown"}>`).join(`
533
533
  `),o=Object.keys(e.methods).map((s)=>` ${s}($event?: Event): unknown`).join(`
534
534
  `);return`export interface ${e.name}Props {
@@ -554,11 +554,11 @@ declare global {
554
554
  }
555
555
 
556
556
  export default ${e.name}
557
- `}function Qd(e){return`declare global {
557
+ `}function eu(e){return`declare global {
558
558
  namespace JSX {
559
559
  interface IntrinsicElements {
560
- ${e.map((t)=>{let r=Object.entries(t.properties).map(([o,s])=>` ${JSON.stringify(o)}?: ${$r(s)}`).join(`
561
- `),n=Object.keys(t.events).map((o)=>{return` ${`on${o.split(/[-:]/).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}`}?: (event: CustomEvent<${t.events[o].detailType||"unknown"}>) => void`}).join(`
560
+ ${e.map((t)=>{let r=Object.entries(t.properties).map(([o,s])=>` ${JSON.stringify(o)}?: ${Sr(s)}`).join(`
561
+ `),n=Object.keys(t.events).map((o)=>` ${`on${o.split(/[-:]/).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}`}?: (event: CustomEvent<${t.events[o].detailType||"unknown"}>) => void`).join(`
562
562
  `);return` ${JSON.stringify(t.tag)}: {
563
563
  ${r}
564
564
  ${n}
@@ -573,9 +573,9 @@ ${n}
573
573
  }
574
574
 
575
575
  export {}
576
- `}function eu(e){return{schemaVersion:"1.0.0",modules:e.map((t)=>({kind:"javascript-module",path:`./${t.tag}.js`,declarations:[{kind:"class",name:t.name,description:t.description||void 0,customElement:!0,tagName:t.tag,members:Object.entries(t.properties).map(([r,n])=>({kind:"field",name:r,description:n.description,type:{text:$r(n)},default:n.default===void 0?void 0:JSON.stringify(n.default),attribute:n.attribute===!1?void 0:n.attribute||Xn(r),reflects:n.reflect})),events:Object.entries(t.events).map(([r,n])=>({name:r,description:n.description,type:{text:`CustomEvent<${n.detailType||"unknown"}>`}})),slots:t.slots,cssProperties:t.cssProperties}],exports:[{kind:"js",name:t.name,declaration:{name:t.name,module:`./${t.tag}.js`}}]}))}}function ks(e){if(!e.styles)return"";let t=e.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(t))return t;return`@scope (${e.tag}) {
576
+ `}function tu(e){return{schemaVersion:"1.0.0",modules:e.map((t)=>({kind:"javascript-module",path:`./${t.tag}.js`,declarations:[{kind:"class",name:t.name,description:t.description||void 0,customElement:!0,tagName:t.tag,members:Object.entries(t.properties).map(([r,n])=>({kind:"field",name:r,description:n.description,type:{text:Sr(n)},default:n.default===void 0?void 0:JSON.stringify(n.default),attribute:n.attribute===!1?void 0:n.attribute||Jn(r),reflects:n.reflect})),events:Object.entries(t.events).map(([r,n])=>({name:r,description:n.description,type:{text:`CustomEvent<${n.detailType||"unknown"}>`}})),slots:t.slots,cssProperties:t.cssProperties}],exports:[{kind:"js",name:t.name,declaration:{name:t.name,module:`./${t.tag}.js`}}]}))}}function Ts(e){if(!e.styles)return"";let t=e.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(t))return t;return`@scope (${e.tag}) {
577
577
  ${t}
578
- }`}function Ts(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function tu(e){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),n=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(e.map((i)=>[i.tag,{template:i.template,styles:i.styles,shadowMode:i.shadowMode,properties:i.properties}])),s=e.map((i)=>`export const render${i.name} = (props = {}, slots = {}) => renderComponent('${i.tag}', props, slots);`).join(`
578
+ }`}function Cs(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function ru(e){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),n=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(e.map((i)=>[i.tag,{template:i.template,styles:i.styles,shadowMode:i.shadowMode,properties:i.properties}])),s=e.map((i)=>`export const render${i.name} = (props = {}, slots = {}) => renderComponent('${i.tag}', props, slots);`).join(`
579
579
  `);return`const definitions = ${JSON.stringify(o,null,2)};
580
580
  const escapeHTML = (value) => String(value ?? '')
581
581
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -609,21 +609,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
609
609
  }
610
610
 
611
611
  ${s}
612
- `}async function Px(e){let t=ve.resolve(e.inputDir),r=ve.resolve(e.outputDir);if(!(await $s(t).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${t}`);let n=e.components?.length?e.components:(await Bd(t)).map((f)=>({file:f}));if(!n.length)throw Error(`No .stx components found in ${t}`);let o=await Promise.all(n.map((f)=>Yd(t,f,e)));o.sort((f,g)=>f.tag.localeCompare(g.tag));let s=o.filter((f,g)=>o.findIndex((x)=>x.tag===f.tag)!==g);if(s.length)throw Error(`Duplicate custom-element tag: ${s[0].tag}`);let i=o.filter((f,g)=>o.findIndex((x)=>x.name===f.name)!==g);if(i.length)throw Error(`Duplicate component class name: ${i[0].name}`);await Dd(r,{recursive:!0});let a=[],c=async(f,g)=>{let x=ve.join(r,f);return await Id(x,g.endsWith(`
612
+ `}async function Ox(e){let t=$e.resolve(e.inputDir),r=$e.resolve(e.outputDir);if(!(await Ss(t).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${t}`);let n=e.components?.length?e.components:(await zd(t)).map((f)=>({file:f}));if(!n.length)throw Error(`No .stx components found in ${t}`);let o=await Promise.all(n.map((f)=>Kd(t,f,e)));o.sort((f,g)=>f.tag.localeCompare(g.tag));let s=o.filter((f,g)=>o.findIndex((x)=>x.tag===f.tag)!==g);if(s.length)throw Error(`Duplicate custom-element tag: ${s[0].tag}`);let i=o.filter((f,g)=>o.findIndex((x)=>x.name===f.name)!==g);if(i.length)throw Error(`Duplicate component class name: ${i[0].name}`);await Pd(r,{recursive:!0});let a=[],c=async(f,g)=>{let x=$e.join(r,f);return await Ld(x,g.endsWith(`
613
613
  `)?g:`${g}
614
- `,"utf8"),a.push(x),x};await c("runtime.js",Kd());for(let f of o){if(await c(`${f.tag}.js`,Gd(f)),e.declarations!==!1)await c(`${f.tag}.d.ts`,Zd(f));if(e.css!==!1&&f.styles){let g=f.shadowMode?f.styles:ks(f);await c(`${f.tag}.css`,e.minify?Ts(g):g)}}let l=o.map((f)=>`export { ${f.name}, default as ${f.name}Element } from './${f.tag}.js';`).join(`
615
- `);if(await c("index.js",l),await c("ssr.js",tu(o)),e.declarations!==!1)await c("index.d.ts",o.map((f)=>`export * from './${f.tag}.js'`).join(`
616
- `)),await c("custom-elements.d.ts",Qd(o)),await c("ssr.d.ts",`${o.map((f)=>`export declare const render${f.name}: (props?: ${f.name}Props, slots?: Record<string, string>) => string`).join(`
614
+ `,"utf8"),a.push(x),x};await c("runtime.js",Gd());for(let f of o){if(await c(`${f.tag}.js`,Zd(f)),e.declarations!==!1)await c(`${f.tag}.d.ts`,Qd(f));if(e.css!==!1&&f.styles){let g=f.shadowMode?f.styles:Ts(f);await c(`${f.tag}.css`,e.minify?Cs(g):g)}}let l=o.map((f)=>`export { ${f.name}, default as ${f.name}Element } from './${f.tag}.js';`).join(`
615
+ `);if(await c("index.js",l),await c("ssr.js",ru(o)),e.declarations!==!1)await c("index.d.ts",o.map((f)=>`export * from './${f.tag}.js'`).join(`
616
+ `)),await c("custom-elements.d.ts",eu(o)),await c("ssr.d.ts",`${o.map((f)=>`export declare const render${f.name}: (props?: ${f.name}Props, slots?: Record<string, string>) => string`).join(`
617
617
  `)}
618
618
  export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
619
619
  ${o.map((f)=>`import type { ${f.name}Props } from './${f.tag}.js'`).join(`
620
- `)}`);let d;if(e.manifest!==!1)d=await c("custom-elements.json",JSON.stringify(eu(o),null,2));let u;if(e.css!==!1){let f=o.filter((g)=>!g.shadowMode&&g.styles).map(ks).join(`
620
+ `)}`);let d;if(e.manifest!==!1)d=await c("custom-elements.json",JSON.stringify(tu(o),null,2));let u;if(e.css!==!1){let f=o.filter((g)=>!g.shadowMode&&g.styles).map(Ts).join(`
621
621
 
622
- `);if(f)u=await c("bundle.css",e.minify?Ts(f):f)}let p;if(e.bundle!==!1){p=ve.join(r,"bundle.js");let f;try{f=await Bun.build({entrypoints:[ve.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:e.minify??!0,sourcemap:e.sourcemap||"none"})}catch(g){let x=g instanceof AggregateError?g.errors:[g],y=x.map((b)=>String(b).trim()).filter(Boolean).join(`
622
+ `);if(f)u=await c("bundle.css",e.minify?Cs(f):f)}let p;if(e.bundle!==!1){p=$e.join(r,"bundle.js");let f;try{f=await Bun.build({entrypoints:[$e.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:e.minify??!0,sourcemap:e.sourcemap||"none"})}catch(g){let x=g instanceof AggregateError?g.errors:[g],y=x.map((b)=>String(b).trim()).filter(Boolean).join(`
623
623
  `);throw AggregateError(x,`Failed to bundle component library${y?`
624
624
  ${y}`:""}`)}if(!f.success){let g=f.logs.map((x)=>String(x).trim()).filter(Boolean).join(`
625
625
  `);throw AggregateError(f.logs,`Failed to bundle component library${g?`
626
- ${g}`:""}`)}if(a.push(p),e.sourcemap==="external")a.push(`${p}.map`)}let h=await Promise.all(a.map(async(f)=>(await $s(f)).size));return{components:o.map((f)=>({name:f.name,tag:f.tag,source:f.sourcePath,module:ve.join(r,`${f.tag}.js`)})),files:a,manifest:d,bundle:p,cssBundle:u,totalBytes:h.reduce((f,g)=>f+g,0)}}import Sr from"zlib";import{promisify as _s}from"util";var ru=_s(Sr.brotliCompress),nu=_s(Sr.gzip),ou=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],su=["text/event-stream","multipart/x-mixed-replace"],iu=1024;function au(e){if(!e)return!1;let t=e.toLowerCase();if(su.some((r)=>t.startsWith(r)))return!1;return ou.some((r)=>t.startsWith(r))}function cu(e){let t=new Map;for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=n.trim().toLowerCase();if(!s)continue;let i=1;for(let a of o){let c=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(a);if(!c)continue;let l=Number.parseFloat(c[1]);if(Number.isFinite(l))i=l}t.set(s,i)}return t}function lu(e){if(!e)return null;let t=cu(e),r=t.get("*"),n=(o)=>t.get(o)??r??0;if(n("br")>0)return"br";if(n("gzip")>0)return"gzip";return null}async function wt(e,t,r={}){if(t.headers.get("content-encoding"))return t;if(t.status===204||t.status===304||!t.body)return t;if(!au(t.headers.get("content-type")))return t;let n=lu(e.headers.get("accept-encoding"));if(!n)return t;let o;try{o=new Uint8Array(await t.arrayBuffer())}catch{return t}let s=()=>new Response(o,{status:t.status,statusText:t.statusText,headers:Es(t.headers)});if(o.length<(r.threshold??iu))return s();try{let i=n==="br"?await ru(o,{params:{[Sr.constants.BROTLI_PARAM_QUALITY]:r.quality??5,[Sr.constants.BROTLI_PARAM_SIZE_HINT]:o.length}}):await nu(o);if(i.length>=o.length)return s();let a=Es(t.headers);return a.set("Content-Encoding",n),a.set("Content-Length",String(i.length)),new Response(i,{status:t.status,statusText:t.statusText,headers:a})}catch{return s()}}function Es(e){let t=new Headers(e),r=t.get("Vary");if(!r)return t.set("Vary","Accept-Encoding"),t;if(!r.split(",").some((n)=>n.trim().toLowerCase()==="accept-encoding"))t.set("Vary",`${r}, Accept-Encoding`);return t}var{serve:xu}=globalThis.Bun;import Yn from"fs";import $t from"path";function kr(){return`
626
+ ${g}`:""}`)}if(a.push(p),e.sourcemap==="external")a.push(`${p}.map`)}let h=await Promise.all(a.map(async(f)=>(await Ss(f)).size));return{components:o.map((f)=>({name:f.name,tag:f.tag,source:f.sourcePath,module:$e.join(r,`${f.tag}.js`)})),files:a,manifest:d,bundle:p,cssBundle:u,totalBytes:h.reduce((f,g)=>f+g,0)}}import kr from"zlib";import{promisify as As}from"util";var nu=As(kr.brotliCompress),ou=As(kr.gzip),su=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],iu=["text/event-stream","multipart/x-mixed-replace"],au=1024;function cu(e){if(!e)return!1;let t=e.toLowerCase();if(iu.some((r)=>t.startsWith(r)))return!1;return su.some((r)=>t.startsWith(r))}function lu(e){let t=new Map;for(let r of e.split(",")){let[n,...o]=r.trim().split(";"),s=n.trim().toLowerCase();if(!s)continue;let i=1;for(let a of o){let c=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(a);if(!c)continue;let l=Number.parseFloat(c[1]);if(Number.isFinite(l))i=l}t.set(s,i)}return t}function du(e){if(!e)return null;let t=lu(e),r=t.get("*"),n=(o)=>t.get(o)??r??0;if(n("br")>0)return"br";if(n("gzip")>0)return"gzip";return null}async function vt(e,t,r={}){if(t.headers.get("content-encoding"))return t;if(t.status===204||t.status===304||!t.body)return t;if(!cu(t.headers.get("content-type")))return t;let n=du(e.headers.get("accept-encoding"));if(!n)return t;let o;try{o=new Uint8Array(await t.arrayBuffer())}catch{return t}let s=()=>new Response(o,{status:t.status,statusText:t.statusText,headers:_s(t.headers)});if(o.length<(r.threshold??au))return s();try{let i=n==="br"?await nu(o,{params:{[kr.constants.BROTLI_PARAM_QUALITY]:r.quality??5,[kr.constants.BROTLI_PARAM_SIZE_HINT]:o.length}}):await ou(o);if(i.length>=o.length)return s();let a=_s(t.headers);return a.set("Content-Encoding",n),a.set("Content-Length",String(i.length)),new Response(i,{status:t.status,statusText:t.statusText,headers:a})}catch{return s()}}function _s(e){let t=new Headers(e),r=t.get("Vary");if(!r)return t.set("Vary","Accept-Encoding"),t;if(!r.split(",").some((n)=>n.trim().toLowerCase()==="accept-encoding"))t.set("Vary",`${r}, Accept-Encoding`);return t}var{serve:bu}=globalThis.Bun;import Kn from"fs";import St from"path";function Tr(){return`
627
627
  /* Theme selector for code blocks */
628
628
  .theme-selector {
629
629
  margin: 1rem 0;
@@ -673,13 +673,13 @@ ${g}`:""}`)}if(a.push(p),e.sourcemap==="external")a.push(`${p}.map`)}let h=await
673
673
 
674
674
  body.dark-mode a {
675
675
  color: #58a6ff;
676
- }`}function Tr(e){return`
676
+ }`}function Cr(e){return`
677
677
  <div class="theme-selector">
678
678
  Theme:
679
679
  <select id="themeSelector" onchange="changeTheme()">
680
680
  ${e}
681
681
  </select>
682
- </div>`}function Cr(){return`
682
+ </div>`}function Er(){return`
683
683
  function changeTheme() {
684
684
  const theme = document.getElementById('themeSelector').value;
685
685
 
@@ -695,7 +695,7 @@ else {
695
695
  }
696
696
 
697
697
  // Initialize theme on page load
698
- document.addEventListener('DOMContentLoaded', changeTheme);`}function Er(e){if(Object.keys(e).length===0)return"";return`
698
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function _r(e){if(Object.keys(e).length===0)return"";return`
699
699
  <div class="frontmatter">
700
700
  <h3>Frontmatter</h3>
701
701
  ${Object.entries(e).map(([t,r])=>`
@@ -703,19 +703,19 @@ else {
703
703
  <span class="frontmatter-label">${t}:</span>
704
704
  <span>${Array.isArray(r)?r.join(", "):String(r)}</span>
705
705
  </div>`).join("")}
706
- </div>`}import As from"net";async function du(e){return new Promise((t)=>{let r=As.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,"0.0.0.0")})}async function uu(e){return new Promise((t)=>{let r=As.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,"::")})}async function pu(e){if(!await du(e))return!1;return await uu(e)}async function Xe(e,t=20){e=Number(e);for(let r=0;r<t;r++){let n=e+r;if(await pu(n))return n}throw Error(`Could not find an available port between ${e} and ${e+t-1}`)}var fu={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function mu(){try{let e=await import("./chunk-7rsf8tes.js");if(typeof e.openDevWindow!=="function")return null;return e}catch{return null}}async function vt(e,t={}){let r={...fu,...t},n=await mu();if(!n)return console.log(`${m.yellow}\u26A0${m.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await n.openDevWindow(e,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${m.green}\u2713${m.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${m.red}\u2717${m.reset} Could not open native window:`,o),!1}}function _r(e){if(e.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let n=e.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(n){let o=n[1];try{let s=`
706
+ </div>`}import js from"net";async function uu(e){return new Promise((t)=>{let r=js.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,"0.0.0.0")})}async function pu(e){return new Promise((t)=>{let r=js.createServer();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen(e,"::")})}async function fu(e){if(!await uu(e))return!1;return await pu(e)}async function Je(e,t=20){e=Number(e);for(let r=0;r<t;r++){let n=e+r;if(await fu(n))return n}throw Error(`Could not find an available port between ${e} and ${e+t-1}`)}var mu={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function hu(){try{let e=await import("./chunk-qvwy1808.js");if(typeof e.openDevWindow!=="function")return null;return e}catch{return null}}async function $t(e,t={}){let r={...mu,...t},n=await hu();if(!n)return console.log(`${m.yellow}\u26A0${m.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await n.openDevWindow(e,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${m.green}\u2713${m.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${m.red}\u2717${m.reset} Could not open native window:`,o),!1}}function Ar(e){if(e.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let n=e.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(n){let o=n[1];try{let s=`
707
707
  ${o}
708
708
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
709
- `,i=Function(s)();if(i)return i}catch(s){console.warn("Invalid sidebarConfig:",s)}}return{sections:[]}}let t=e.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(t)try{return JSON.parse(t[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let r=e.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(r)try{let n=r[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(n)return Function(`return ${n[1]}`)()}catch(n){console.warn("Invalid native-sidebar script configuration:",n)}return}function Jn(){console.log(`
710
- Keyboard shortcuts:`),console.log(` ${m.cyan}o${m.reset} + Enter - Open in browser`),console.log(` ${m.cyan}c${m.reset} + Enter - Clear console`),console.log(` ${m.cyan}q${m.reset} + Enter (or ${m.cyan}Ctrl+C${m.reset}) - Quit server`),console.log(` ${m.cyan}h${m.reset} + Enter - Show this help`)}function hu(e){console.log(`${m.green}Server running at ${m.cyan}${e}${m.reset}`),console.log(`Press ${m.cyan}Ctrl+C${m.reset} to stop the server`),Jn()}function gu(e){console.log(`${m.dim}Opening ${m.cyan}${e}${m.dim} in your browser...${m.reset}`),Bun.spawn(["open",e],{stderr:"inherit"})}function Je(e,t,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Jn();let n="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();t(),process.exit(0)}if(n+=o,n.endsWith("\r")||n.endsWith(`
711
- `)){let s=n.trim().toLowerCase();n="",yu(s,e,t,r)}})}function yu(e,t,r,n){switch(e){case"o":if(n?.onOpen)n.onOpen();else gu(t);break;case"c":if(n?.onClear)n.onClear();else console.clear(),hu(t);break;case"q":if(n?.onQuit)n.onQuit();console.log(`${m.yellow}Stopping server...${m.reset}`),r(),process.exit(0);break;case"h":if(n?.onHelp)n.onHelp();else Jn();break;default:break}}async function Kn(e,t={}){let r=t.port||3000,n=t.watch!==!1,o=$t.resolve(e);if(!Yn.existsSync(o))return console.error(`${m.red}Error: File not found: ${m.bright}${o}${m.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${m.red}Error: File must have .md extension: ${m.bright}${o}${m.reset}`),!1;console.log(`${m.blue}Processing${m.reset} ${m.bright}${e}${m.reset}...`);let s=null,i=async()=>{try{let{content:d,data:u}=await $e(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:je.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),p=t.markdown?.syntaxHighlighting||je.markdown?.syntaxHighlighting,h=p?.defaultTheme||"github-dark",f=["github-dark"],g=p?.additionalThemes||[],x=[...new Set([...f,...g])].map((y)=>`<option value="${y}"${y===h?" selected":""}>${y}</option>`).join(`
709
+ `,i=Function(s)();if(i)return i}catch(s){console.warn("Invalid sidebarConfig:",s)}}return{sections:[]}}let t=e.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(t)try{return JSON.parse(t[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let r=e.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(r)try{let n=r[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(n)return Function(`return ${n[1]}`)()}catch(n){console.warn("Invalid native-sidebar script configuration:",n)}return}function Yn(){console.log(`
710
+ Keyboard shortcuts:`),console.log(` ${m.cyan}o${m.reset} + Enter - Open in browser`),console.log(` ${m.cyan}c${m.reset} + Enter - Clear console`),console.log(` ${m.cyan}q${m.reset} + Enter (or ${m.cyan}Ctrl+C${m.reset}) - Quit server`),console.log(` ${m.cyan}h${m.reset} + Enter - Show this help`)}function gu(e){console.log(`${m.green}Server running at ${m.cyan}${e}${m.reset}`),console.log(`Press ${m.cyan}Ctrl+C${m.reset} to stop the server`),Yn()}function yu(e){console.log(`${m.dim}Opening ${m.cyan}${e}${m.dim} in your browser...${m.reset}`),Bun.spawn(["open",e],{stderr:"inherit"})}function Ye(e,t,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Yn();let n="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();t(),process.exit(0)}if(n+=o,n.endsWith("\r")||n.endsWith(`
711
+ `)){let s=n.trim().toLowerCase();n="",xu(s,e,t,r)}})}function xu(e,t,r,n){switch(e){case"o":if(n?.onOpen)n.onOpen();else yu(t);break;case"c":if(n?.onClear)n.onClear();else console.clear(),gu(t);break;case"q":if(n?.onQuit)n.onQuit();console.log(`${m.yellow}Stopping server...${m.reset}`),r(),process.exit(0);break;case"h":if(n?.onHelp)n.onHelp();else Yn();break;default:break}}async function Gn(e,t={}){let r=t.port||3000,n=t.watch!==!1,o=St.resolve(e);if(!Kn.existsSync(o))return console.error(`${m.red}Error: File not found: ${m.bright}${o}${m.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${m.red}Error: File must have .md extension: ${m.bright}${o}${m.reset}`),!1;console.log(`${m.blue}Processing${m.reset} ${m.bright}${e}${m.reset}...`);let s=null,i=async()=>{try{let{content:d,data:u}=await Se(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:Re.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),p=t.markdown?.syntaxHighlighting||Re.markdown?.syntaxHighlighting,h=p?.defaultTheme||"github-dark",f=["github-dark"],g=p?.additionalThemes||[],x=[...new Set([...f,...g])].map((y)=>`<option value="${y}"${y===h?" selected":""}>${y}</option>`).join(`
712
712
  `);return s=`
713
713
  <!DOCTYPE html>
714
714
  <html lang="en">
715
715
  <head>
716
716
  <meta charset="UTF-8">
717
717
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
718
- <title>${bu(u.title||$t.basename(o))}</title>
718
+ <title>${wu(u.title||St.basename(o))}</title>
719
719
  <!-- Syntax highlighting styles -->
720
720
  <style id="syntax-theme">
721
721
  :root {
@@ -857,26 +857,26 @@ Keyboard shortcuts:`),console.log(` ${m.cyan}o${m.reset} + Enter - Open in brow
857
857
  min-width: 100px;
858
858
  color: #555;
859
859
  }
860
- ${kr()}
860
+ ${Tr()}
861
861
  </style>
862
862
  </head>
863
863
  <body>
864
- ${Er(u)}
865
- ${Tr(x)}
864
+ ${_r(u)}
865
+ ${Cr(x)}
866
866
 
867
867
  ${d}
868
868
 
869
869
  <script>
870
- ${Cr()}
870
+ ${Er()}
871
871
  </script>
872
872
  </body>
873
873
  </html>
874
- `,!0}catch(d){return console.error(`${m.red}Error processing Markdown file:${m.reset}`,d),!1}};if(!await i())return!1;let a=r;try{if(a=await Xe(r),a!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${a} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${a}/${m.reset}...`);let c=xu({port:a,fetch(d){if(new URL(d.url).pathname==="/")return new Response(s,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(d){return new Response(`<pre>${d}
874
+ `,!0}catch(d){return console.error(`${m.red}Error processing Markdown file:${m.reset}`,d),!1}};if(!await i())return!1;let a=r;try{if(a=await Je(r),a!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${a} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${a}/${m.reset}...`);let c=bu({port:a,fetch(d){if(new URL(d.url).pathname==="/")return new Response(s,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(d){return new Response(`<pre>${d}
875
875
  ${d.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
876
876
  ${m.blue}stx${m.reset} ${m.green}${process.env.stx_VERSION||"v0.0.10"}${m.reset} ${m.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${m.reset}`),console.log(`
877
877
  ${m.bright}\u2192 ${m.cyan}http://localhost:${a}/${m.reset}`),console.log(`
878
- ${m.yellow}Routes:${m.reset}`);let l=$t.relative(process.cwd(),o);if(console.log(` ${m.green}\u2514\u2500 /${m.reset} \u2192 ${m.bright}${l}${m.reset}`),console.log(`
879
- Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(c.url.toString(),()=>{if(n)Yn.watch($t.dirname(o),{recursive:!0}).close();c.stop()}),t.native)await vt(a,{title:$t.basename(o,".md")});if(n){let d=$t.dirname(o);console.log(`${m.blue}Watching ${m.bright}${d}${m.reset} for changes...`);let u=Yn.watch(d,{recursive:!0},async(p,h)=>{if(h&&h.endsWith(".md"))console.log(`${m.yellow}File ${m.bright}${h}${m.yellow} changed, reprocessing...${m.reset}`),await i()});process.on("SIGINT",()=>{u.close(),c.stop(),process.exit(0)})}return!0}function bu(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:vu}=globalThis.Bun;import Se from"fs";import de from"path";class js{clients=new Set;server=null;options;constructor(e={}){this.options={wsPort:e.wsPort??3001,showOverlay:e.showOverlay??!0,reconnectInterval:e.reconnectInterval??1000,maxReconnectAttempts:e.maxReconnectAttempts??10,verbose:e.verbose??!1}}start(e){let t=e??this.options.wsPort,r=20;for(let n=0;n<r;n++)try{if(this.server=Bun.serve({port:t,fetch(o,s){if(s.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,s)=>{let i=typeof s==="string"?s:s.toString();if(i==="ping")return;try{let a=JSON.parse(i);if(a.type==="console"&&Array.isArray(a.args)){let c=a.args.join(" "),l={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[a.level]??"\x1B[36m";console.log(`${l}[browser]${a.level!=="log"?` ${a.level}`:""}\x1B[0m ${c}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${t}`);return t}catch(o){if(o?.code==="EADDRINUSE"){t++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${e??this.options.wsPort}`)}stop(){for(let e of this.clients)try{e.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(e){let t=JSON.stringify(e),r=0;for(let n of this.clients)try{if(n.readyState===1)n.send(t),r++}catch{this.clients.delete(n)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${e.type} to ${r} client(s)`)}reload(e){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${e||"all"}`);this.broadcast({type:"reload",path:e,timestamp:Date.now()})}updateCss(e,t){this.broadcast({type:"css-update",path:e,content:t,timestamp:Date.now()})}error(e){this.broadcast({type:"error",content:e,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function wu(e,t={}){let{showOverlay:r=!0,reconnectInterval:n=1000,maxReconnectAttempts:o=10}=t;return`
878
+ ${m.yellow}Routes:${m.reset}`);let l=St.relative(process.cwd(),o);if(console.log(` ${m.green}\u2514\u2500 /${m.reset} \u2192 ${m.bright}${l}${m.reset}`),console.log(`
879
+ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Ye(c.url.toString(),()=>{if(n)Kn.watch(St.dirname(o),{recursive:!0}).close();c.stop()}),t.native)await $t(a,{title:St.basename(o,".md")});if(n){let d=St.dirname(o);console.log(`${m.blue}Watching ${m.bright}${d}${m.reset} for changes...`);let u=Kn.watch(d,{recursive:!0},async(p,h)=>{if(h&&h.endsWith(".md"))console.log(`${m.yellow}File ${m.bright}${h}${m.yellow} changed, reprocessing...${m.reset}`),await i()});process.on("SIGINT",()=>{u.close(),c.stop(),process.exit(0)})}return!0}function wu(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:$u}=globalThis.Bun;import ke from"fs";import ue from"path";class Rs{clients=new Set;server=null;options;constructor(e={}){this.options={wsPort:e.wsPort??3001,showOverlay:e.showOverlay??!0,reconnectInterval:e.reconnectInterval??1000,maxReconnectAttempts:e.maxReconnectAttempts??10,verbose:e.verbose??!1}}start(e){let t=e??this.options.wsPort,r=20;for(let n=0;n<r;n++)try{if(this.server=Bun.serve({port:t,fetch(o,s){if(s.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,s)=>{let i=typeof s==="string"?s:s.toString();if(i==="ping")return;try{let a=JSON.parse(i);if(a.type==="console"&&Array.isArray(a.args)){let c=a.args.join(" "),l={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[a.level]??"\x1B[36m";console.log(`${l}[browser]${a.level!=="log"?` ${a.level}`:""}\x1B[0m ${c}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${t}`);return t}catch(o){if(o?.code==="EADDRINUSE"){t++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${e??this.options.wsPort}`)}stop(){for(let e of this.clients)try{e.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(e){let t=JSON.stringify(e),r=0;for(let n of this.clients)try{if(n.readyState===1)n.send(t),r++}catch{this.clients.delete(n)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${e.type} to ${r} client(s)`)}reload(e){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${e||"all"}`);this.broadcast({type:"reload",path:e,timestamp:Date.now()})}updateCss(e,t){this.broadcast({type:"css-update",path:e,content:t,timestamp:Date.now()})}error(e){this.broadcast({type:"error",content:e,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function vu(e,t={}){let{showOverlay:r=!0,reconnectInterval:n=1000,maxReconnectAttempts:o=10}=t;return`
880
880
  <script>
881
881
  (function() {
882
882
  // stx Hot Reload Client
@@ -1075,10 +1075,10 @@ else {
1075
1075
  };
1076
1076
  })();
1077
1077
  </script>
1078
- `}function Be(e,t,r={}){let n=wu(t,r),o=e.lastIndexOf("</body>");if(o!==-1)return e.slice(0,o)+n+e.slice(o);if(e.includes("</html>"))return e.replace("</html>",`${n}</html>`);return e+n}function Ar(e){let t=e.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function jr(e){let t=e.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((r)=>t.endsWith(r))}function Rr(e){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((t)=>t.test(e))}var St=null;function Mr(e){if(!St)St=new js(e);return St}function Ht(){if(St)St.stop(),St=null}import Dr from"path";var Tt={name:"bun-plugin-stx",async setup(e){let t={...await it(),...e.config?.stx},r=new Set,n=t.webComponents?.enabled?`./${Dr.relative(Dr.dirname(e.config?.outdir||"dist"),t.webComponents.outputDir||"dist/web-components")}`:"/web-components",o=[];if(t.webComponents?.enabled)try{let s=await Or(t,r);if(o.push(...s),t.debug&&s.length>0)console.log(`Successfully built ${s.length} web components`)}catch(s){console.error("Failed to build web components:",s)}e.onLoad({filter:/\.stx$/},async({path:s})=>{try{let i=new Set;if(t.cache&&t.cachePath){let h=await Ir(s,t);if(h){if(t.debug)console.log(`Using cached version of ${s}`);return{contents:h,loader:"html"}}}let a=await Qn(()=>Bun.file(s).text(),"",(h)=>{throw new Zn(`Failed to read stx file: ${s}`,s,void 0,void 0,`File read error: ${h.message}`)});if(!a)throw new Zn(`stx file is empty: ${s}`,s);let{scriptContent:c,templateContent:l,allScripts:d}=eo.time("script-extraction",()=>{let h=a,f=kt(a);if(f)h=f.content.trim();let g=a.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],x="",y=[];for(let w of g){let v=w.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",S=w.match(/<script\b([^>]*)>/i),T=S?S[1]:"";if(/\bserver\b/i.test(T))x=v;else y.push(w)}let b=h.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:x,templateContent:b,allScripts:y}}),u={__filename:s,__dirname:Dr.dirname(s),__stx:{webComponentsPath:n,builtComponents:o}};await Qn(()=>te(c,u,s),void 0,(h)=>{let f=new Gn(`Script execution failed in ${s}: ${h.message}`,s,void 0,void 0,c.substring(0,100));if(Pr.log(f,{filePath:s,scriptContent:c}),t.debug)throw f});let p=await eo.timeAsync("directive-processing",async()=>{return await se(l,u,s,t,i)});if(d.length>0){let{interpolateScriptsInTemplate:h}=await import("./chunk-fjzye4qj.js"),f=h(d.join(`
1078
+ `}function ze(e,t,r={}){let n=vu(t,r),o=e.lastIndexOf("</body>");if(o!==-1)return e.slice(0,o)+n+e.slice(o);if(e.includes("</html>"))return e.replace("</html>",`${n}</html>`);return e+n}function jr(e){let t=e.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function Rr(e){let t=e.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((r)=>t.endsWith(r))}function Mr(e){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((t)=>t.test(e))}var kt=null;function Dr(e){if(!kt)kt=new Rs(e);return kt}function Wt(){if(kt)kt.stop(),kt=null}import Pr from"path";var Ct={name:"bun-plugin-stx",async setup(e){let t={...await at(),...e.config?.stx},r=new Set,n=t.webComponents?.enabled?`./${Pr.relative(Pr.dirname(e.config?.outdir||"dist"),t.webComponents.outputDir||"dist/web-components")}`:"/web-components",o=[];if(t.webComponents?.enabled)try{let s=await Ir(t,r);if(o.push(...s),t.debug&&s.length>0)console.log(`Successfully built ${s.length} web components`)}catch(s){console.error("Failed to build web components:",s)}e.onLoad({filter:/\.stx$/},async({path:s})=>{try{let i=new Set;if(t.cache&&t.cachePath){let h=await Lr(s,t);if(h){if(t.debug)console.log(`Using cached version of ${s}`);return{contents:h,loader:"html"}}}let a=await eo(()=>Bun.file(s).text(),"",(h)=>{throw new Qn(`Failed to read stx file: ${s}`,s,void 0,void 0,`File read error: ${h.message}`)});if(!a)throw new Qn(`stx file is empty: ${s}`,s);let{scriptContent:c,templateContent:l,allScripts:d}=to.time("script-extraction",()=>{let h=a,f=Tt(a);if(f)h=f.content.trim();let g=a.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],x="",y=[];for(let w of g){let v=w.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",k=w.match(/<script\b([^>]*)>/i),C=k?k[1]:"";if(/\bserver\b/i.test(C))x=v;else y.push(w)}let b=h.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:x,templateContent:b,allScripts:y}}),u={__filename:s,__dirname:Pr.dirname(s),__stx:{webComponentsPath:n,builtComponents:o}};await eo(()=>re(c,u,s),void 0,(h)=>{let f=new Zn(`Script execution failed in ${s}: ${h.message}`,s,void 0,void 0,c.substring(0,100));if(Or.log(f,{filePath:s,scriptContent:c}),t.debug)throw f});let p=await to.timeAsync("directive-processing",async()=>await ie(l,u,s,t,i));if(d.length>0){let{interpolateScriptsInTemplate:h}=await import("./chunk-2152npfd.js"),f=h(d.join(`
1079
1079
  `),u),g=p.search(/<\/body>/i);if(g!==-1)p=p.slice(0,g)+f+`
1080
1080
  `+p.slice(g);else p+=`
1081
- ${f}`}if(p=await Fr(p),i.forEach((h)=>r.add(h)),t.cache&&t.cachePath){if(await Lr(s,p,i,t),t.debug)console.log(`Cached template ${s} with ${i.size} dependencies`)}return{contents:p,loader:"html"}}catch(i){let a=i instanceof Error?i:new Gn(`Plugin processing failed: ${String(i)}`,s);if(Pr.log(a,{filePath:s,buildConfig:e.config}),Ms.logDetailedError(a,{filePath:s,plugin:"bun-plugin-stx"}),t.debug)console.error("stx Plugin Error:",a);let c=a,l=c.line||null,d=c.context||null;return{contents:t.debug||Rs()?`<!DOCTYPE html>
1081
+ ${f}`}if(p=await Nr(p),i.forEach((h)=>r.add(h)),t.cache&&t.cachePath){if(await Fr(s,p,i,t),t.debug)console.log(`Cached template ${s} with ${i.size} dependencies`)}return{contents:p,loader:"html"}}catch(i){let a=i instanceof Error?i:new Zn(`Plugin processing failed: ${String(i)}`,s);if(Or.log(a,{filePath:s,buildConfig:e.config}),Ds.logDetailedError(a,{filePath:s,plugin:"bun-plugin-stx"}),t.debug)console.error("stx Plugin Error:",a);let c=a,l=c.line||null,d=c.context||null;return{contents:t.debug||Ms()?`<!DOCTYPE html>
1082
1082
  <html lang="en">
1083
1083
  <head>
1084
1084
  <meta charset="UTF-8">
@@ -1101,16 +1101,16 @@ ${f}`}if(p=await Fr(p),i.forEach((h)=>r.add(h)),t.cache&&t.cachePath){if(await L
1101
1101
 
1102
1102
  <div class="error-details">
1103
1103
  <h3>Error Details</h3>
1104
- <p><strong>File:</strong> <span class="file-path">${Re(s)}</span></p>
1105
- <p><strong>Error:</strong> ${Re(a.message)}</p>
1106
- ${l?`<p><strong>Line:</strong> ${Re(String(l))}</p>`:""}
1107
- ${d?`<p><strong>Context:</strong> ${Re(String(d))}</p>`:""}
1104
+ <p><strong>File:</strong> <span class="file-path">${Me(s)}</span></p>
1105
+ <p><strong>Error:</strong> ${Me(a.message)}</p>
1106
+ ${l?`<p><strong>Line:</strong> ${Me(String(l))}</p>`:""}
1107
+ ${d?`<p><strong>Context:</strong> ${Me(String(d))}</p>`:""}
1108
1108
  </div>
1109
1109
 
1110
1110
  ${a.stack?`
1111
1111
  <div class="error-details">
1112
1112
  <h3>Stack Trace</h3>
1113
- <pre class="error-code">${Re(a.stack)}</pre>
1113
+ <pre class="error-code">${Me(a.stack)}</pre>
1114
1114
  </div>`:""}
1115
1115
 
1116
1116
  <div class="help-section">
@@ -1119,7 +1119,7 @@ ${f}`}if(p=await Fr(p),i.forEach((h)=>r.add(h)),t.cache&&t.cachePath){if(await L
1119
1119
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
1120
1120
  <li>Verify that all variables used in the template are properly defined</li>
1121
1121
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
1122
- <li>Run <code>stx debug ${Re(Dr.basename(s))}</code> for detailed analysis</li>
1122
+ <li>Run <code>stx debug ${Me(Pr.basename(s))}</code> for detailed analysis</li>
1123
1123
  <li>Enable debug mode in your stx config for more detailed error messages</li>
1124
1124
  </ul>
1125
1125
  </div>
@@ -1138,12 +1138,12 @@ ${f}`}if(p=await Fr(p),i.forEach((h)=>r.add(h)),t.cache&&t.cachePath){if(await L
1138
1138
  <h1>Something went wrong</h1>
1139
1139
  <p>An internal error occurred. Please try again later.</p>
1140
1140
  </body>
1141
- </html>`,loader:"html"}}})}};async function $u(e,t={}){let r=t.port||3000,n=t.watch!==!1,o=t.hotReload!==!1&&n,s=null,i=t.hmrPort||r+1,a=de.resolve(e);if(!Se.existsSync(a))return console.error(`${m.red}Error: File not found: ${m.bright}${a}${m.reset}`),!1;if(a.endsWith(".md"))return Kn(a,t);else if(!a.endsWith(".stx"))return console.error(`${m.red}Error: Unsupported file type: ${m.bright}${a}${m.reset}. Only .stx and .md files are supported.`),!1;let c=ke(process.cwd(),"output");Se.mkdirSync(c,{recursive:!0}),console.log(`${m.blue}Building ${m.bright}${e}${m.reset}...`);let l=null,d=async()=>{try{let y={name:"public-assets",setup(v){v.onResolve({filter:/^\/(images|fonts|assets|public)\//},(S)=>{return{path:S.path,external:!0}})}},b=await Bun.build({entrypoints:[a],outdir:c,plugins:[y,Tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!b.success)return console.error(`${m.red}Build failed:${m.reset}`,b.logs),!1;let w=b.outputs.find((v)=>v.path.endsWith(".html"));if(!w)return console.error(`${m.red}No HTML output found${m.reset}`),!1;return l=await Bun.file(w.path).text(),!0}catch(y){return console.error(`${m.red}Error building stx file:${m.reset}`,y),!1}};if(!await d())return!1;let u=de.dirname(a);await Nr(u);let p=r;try{if(p=await Xe(r),p!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${p} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}if(o){let y=t.hmrPort||p+1;s=Mr({wsPort:y,verbose:!1}),i=s.start(y)}let h={},f=null;try{let{loadStxConfig:y}=await import("./chunk-kxp888dn.js"),b=await y();if(b?.apiRouter)f=b?.apiRouter,console.log(`${m.blue}Using custom router for API handling${m.reset}`);if(b?.apiRoutes){h=b.apiRoutes;let w=Object.keys(h).length;if(w>0)console.log(`${m.blue}Loaded ${m.bright}${w} API route${w>1?"s":""}${m.reset}`)}if(b?.broadcasting?.enabled)try{let{startBroadcasting:w,loadChannels:v}=await import("./chunk-zfbh14qe.js"),S=b.broadcasting;await w(S);let T=S.port??6001;console.log(`${m.magenta}Broadcasting on ${m.cyan}ws://localhost:${T}/ws${m.reset}`);let C=de.join(process.cwd(),"channels.ts");if(Se.existsSync(C))try{let j=await v(C);console.log(`${m.blue}Loaded ${m.bright}${j} broadcast channel${j!==1?"s":""}${m.blue} from channels.ts${m.reset}`)}catch(j){console.warn(`${m.yellow}Failed to load channels.ts: ${j.message}${m.reset}`)}}catch(w){console.warn(`${m.yellow}Broadcasting failed to start: ${w.message}${m.reset}`)}}catch{}if(console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${p}/${m.reset}...`),o)console.log(`${m.magenta}Hot reload enabled on ws://localhost:${i}${m.reset}`);let g=vu({port:p,async fetch(y){return wt(y,await(async()=>{let b=new URL(y.url);if(f)try{let C=await f.handleRequest(y);if(C.status!==404)return C}catch{}if(h[b.pathname])try{return await h[b.pathname](y)}catch(C){return new Response(JSON.stringify({error:C.message}),{status:500,headers:{"Content-Type":"application/json"}})}if(b.pathname==="/")return(async()=>{let C=await re(l||"");if(o)C=Be(C,i);if(t.native)if(C.includes("<head>"))C=C.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(C.includes("<html"))C=C.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else C="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+C;if(t.titlebarHidden)if(C.includes("<head>"))C=C.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(C.includes("<html"))C=C.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else C=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${C}`;return C})().then((C)=>new Response(C,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let w=de.join(c,b.pathname);if(Se.existsSync(w)&&Se.statSync(w).isFile()){let C=Bun.file(w),j=de.extname(w).toLowerCase(),k="text/plain";if(j===".ts"||j===".tsx"){let L=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),X=await C.text(),K=L.transformSync(X);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(C,{headers:{"Content-Type":k}})}let v=de.dirname(a),S=de.join(v,b.pathname);if(Se.existsSync(S)&&Se.statSync(S).isFile()){let C=Bun.file(S),j=de.extname(S).toLowerCase(),k="text/plain";if(j===".ts"||j===".tsx"){let L=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),X=await C.text(),K=L.transformSync(X);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".svg":k="image/svg+xml";break;case".ico":k="image/x-icon";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(C,{headers:{"Content-Type":k}})}let T=de.join(process.cwd(),"public",b.pathname);if(Se.existsSync(T)&&Se.statSync(T).isFile()){let C=Bun.file(T),j=de.extname(T).toLowerCase(),k="application/octet-stream";if(j===".ts"||j===".tsx"){let L=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),X=await C.text(),K=L.transformSync(X);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":k="text/html";break;case".css":k="text/css";break;case".js":k="text/javascript";break;case".json":k="application/json";break;case".png":k="image/png";break;case".jpg":case".jpeg":k="image/jpeg";break;case".gif":k="image/gif";break;case".svg":k="image/svg+xml";break;case".ico":k="image/x-icon";break;case".woff":k="font/woff";break;case".woff2":k="font/woff2";break;case".ttf":k="font/ttf";break;case".otf":k="font/otf";break;case".eot":k="application/vnd.ms-fontobject";break}return new Response(C,{headers:{"Content-Type":k}})}return new Response("Not Found",{status:404})})())},error(y){return new Response(`<pre>${y}
1141
+ </html>`,loader:"html"}}})}};async function Su(e,t={}){let r=t.port||3000,n=t.watch!==!1,o=t.hotReload!==!1&&n,s=null,i=t.hmrPort||r+1,a=ue.resolve(e);if(!ke.existsSync(a))return console.error(`${m.red}Error: File not found: ${m.bright}${a}${m.reset}`),!1;if(a.endsWith(".md"))return Gn(a,t);else if(!a.endsWith(".stx"))return console.error(`${m.red}Error: Unsupported file type: ${m.bright}${a}${m.reset}. Only .stx and .md files are supported.`),!1;let c=Te(process.cwd(),"output");ke.mkdirSync(c,{recursive:!0}),console.log(`${m.blue}Building ${m.bright}${e}${m.reset}...`);let l=null,d=async()=>{try{let y={name:"public-assets",setup(v){v.onResolve({filter:/^\/(images|fonts|assets|public)\//},(k)=>({path:k.path,external:!0}))}},b=await Bun.build({entrypoints:[a],outdir:c,plugins:[y,Ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!b.success)return console.error(`${m.red}Build failed:${m.reset}`,b.logs),!1;let w=b.outputs.find((v)=>v.path.endsWith(".html"));if(!w)return console.error(`${m.red}No HTML output found${m.reset}`),!1;return l=await Bun.file(w.path).text(),!0}catch(y){return console.error(`${m.red}Error building stx file:${m.reset}`,y),!1}};if(!await d())return!1;let u=ue.dirname(a);await Br(u);let p=r;try{if(p=await Je(r),p!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${p} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}if(o){let y=t.hmrPort||p+1;s=Dr({wsPort:y,verbose:!1}),i=s.start(y)}let h={},f=null;try{let{loadStxConfig:y}=await import("./chunk-n2j24b0h.js"),b=await y();if(b?.apiRouter)f=b?.apiRouter,console.log(`${m.blue}Using custom router for API handling${m.reset}`);if(b?.apiRoutes){h=b.apiRoutes;let w=Object.keys(h).length;if(w>0)console.log(`${m.blue}Loaded ${m.bright}${w} API route${w>1?"s":""}${m.reset}`)}if(b?.broadcasting?.enabled)try{let{startBroadcasting:w,loadChannels:v}=await import("./chunk-r63za1mr.js"),k=b.broadcasting;await w(k);let C=k.port??6001;console.log(`${m.magenta}Broadcasting on ${m.cyan}ws://localhost:${C}/ws${m.reset}`);let E=ue.join(process.cwd(),"channels.ts");if(ke.existsSync(E))try{let R=await v(E);console.log(`${m.blue}Loaded ${m.bright}${R} broadcast channel${R!==1?"s":""}${m.blue} from channels.ts${m.reset}`)}catch(R){console.warn(`${m.yellow}Failed to load channels.ts: ${R.message}${m.reset}`)}}catch(w){console.warn(`${m.yellow}Broadcasting failed to start: ${w.message}${m.reset}`)}}catch{}if(console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${p}/${m.reset}...`),o)console.log(`${m.magenta}Hot reload enabled on ws://localhost:${i}${m.reset}`);let g=$u({port:p,async fetch(y){return vt(y,await(async()=>{let b=new URL(y.url);if(f)try{let E=await f.handleRequest(y);if(E.status!==404)return E}catch{}if(h[b.pathname])try{return await h[b.pathname](y)}catch(E){return new Response(JSON.stringify({error:E.message}),{status:500,headers:{"Content-Type":"application/json"}})}if(b.pathname==="/")return(async()=>{let E=await ne(l||"");if(o)E=ze(E,i);if(t.native)if(E.includes("<head>"))E=E.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(E.includes("<html"))E=E.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else E="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+E;if(t.titlebarHidden)if(E.includes("<head>"))E=E.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(E.includes("<html"))E=E.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else E=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${E}`;return E})().then((E)=>new Response(E,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let w=ue.join(c,b.pathname);if(ke.existsSync(w)&&ke.statSync(w).isFile()){let E=Bun.file(w),R=ue.extname(w).toLowerCase(),T="text/plain";if(R===".ts"||R===".tsx"){let F=new Bun.Transpiler({loader:R===".tsx"?"tsx":"ts"}),J=await E.text(),G=F.transformSync(J);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(R){case".html":T="text/html";break;case".css":T="text/css";break;case".js":T="text/javascript";break;case".json":T="application/json";break;case".png":T="image/png";break;case".jpg":case".jpeg":T="image/jpeg";break;case".gif":T="image/gif";break;case".woff":T="font/woff";break;case".woff2":T="font/woff2";break;case".ttf":T="font/ttf";break;case".otf":T="font/otf";break;case".eot":T="application/vnd.ms-fontobject";break}return new Response(E,{headers:{"Content-Type":T}})}let v=ue.dirname(a),k=ue.join(v,b.pathname);if(ke.existsSync(k)&&ke.statSync(k).isFile()){let E=Bun.file(k),R=ue.extname(k).toLowerCase(),T="text/plain";if(R===".ts"||R===".tsx"){let F=new Bun.Transpiler({loader:R===".tsx"?"tsx":"ts"}),J=await E.text(),G=F.transformSync(J);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(R){case".html":T="text/html";break;case".css":T="text/css";break;case".js":T="text/javascript";break;case".json":T="application/json";break;case".png":T="image/png";break;case".jpg":case".jpeg":T="image/jpeg";break;case".gif":T="image/gif";break;case".svg":T="image/svg+xml";break;case".ico":T="image/x-icon";break;case".woff":T="font/woff";break;case".woff2":T="font/woff2";break;case".ttf":T="font/ttf";break;case".otf":T="font/otf";break;case".eot":T="application/vnd.ms-fontobject";break}return new Response(E,{headers:{"Content-Type":T}})}let C=ue.join(process.cwd(),"public",b.pathname);if(ke.existsSync(C)&&ke.statSync(C).isFile()){let E=Bun.file(C),R=ue.extname(C).toLowerCase(),T="application/octet-stream";if(R===".ts"||R===".tsx"){let F=new Bun.Transpiler({loader:R===".tsx"?"tsx":"ts"}),J=await E.text(),G=F.transformSync(J);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(R){case".html":T="text/html";break;case".css":T="text/css";break;case".js":T="text/javascript";break;case".json":T="application/json";break;case".png":T="image/png";break;case".jpg":case".jpeg":T="image/jpeg";break;case".gif":T="image/gif";break;case".svg":T="image/svg+xml";break;case".ico":T="image/x-icon";break;case".woff":T="font/woff";break;case".woff2":T="font/woff2";break;case".ttf":T="font/ttf";break;case".otf":T="font/otf";break;case".eot":T="application/vnd.ms-fontobject";break}return new Response(E,{headers:{"Content-Type":T}})}return new Response("Not Found",{status:404})})())},error(y){return new Response(`<pre>${y}
1142
1142
  ${y.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1143
1143
  ${m.blue}stx${m.reset} ${m.green}${process.env.stx_VERSION||"v0.0.10"}${m.reset} ${m.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${m.reset}`),console.log(`
1144
1144
  ${m.bright}\u2192 ${m.cyan}http://localhost:${p}/${m.reset}`),console.log(`
1145
- ${m.yellow}Routes:${m.reset}`);let x=de.relative(process.cwd(),a);if(console.log(` ${m.green}\u2514\u2500 /${m.reset} \u2192 ${m.bright}${x}${m.reset}`),console.log(`
1146
- Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(g.url.toString(),()=>{if(n)Se.watch(de.dirname(a),{recursive:!0}).close();g.stop()}),t.native){let y=await Bun.file(a).text(),b=_r(y);await vt(p,{title:de.basename(a,".stx"),titlebarHidden:t.titlebarHidden===!0,nativeSidebar:!!b,sidebarConfig:b})}if(n){let y=de.dirname(a);console.log(`${m.blue}Watching ${m.bright}${y}${m.reset} for changes...`);let b=Se.watch(y,{recursive:!0},async(w,v)=>{if(!v||Rr(v))return;if(jr(v)){console.log(`${m.yellow}File ${m.bright}${v}${m.yellow} changed, rebuilding...${m.reset}`),at.clear(),ct();let S=await d();if(await Br(u),o&&s)if(S)s.reload(v);else s.error("Build failed - check console for details")}else if(Ar(v)){if(console.log(`${m.cyan}CSS ${m.bright}${v}${m.cyan} changed${m.reset}`),o&&s)s.updateCss(v)}});process.on("SIGINT",()=>{if(b.close(),s)Ht();g.stop(),process.exit(0)})}return!0}var{serve:Su}=globalThis.Bun;import Ye from"fs";import ie from"path";var Ds=`
1145
+ ${m.yellow}Routes:${m.reset}`);let x=ue.relative(process.cwd(),a);if(console.log(` ${m.green}\u2514\u2500 /${m.reset} \u2192 ${m.bright}${x}${m.reset}`),console.log(`
1146
+ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Ye(g.url.toString(),()=>{if(n)ke.watch(ue.dirname(a),{recursive:!0}).close();g.stop()}),t.native){let y=await Bun.file(a).text(),b=Ar(y);await $t(p,{title:ue.basename(a,".stx"),titlebarHidden:t.titlebarHidden===!0,nativeSidebar:!!b,sidebarConfig:b})}if(n){let y=ue.dirname(a);console.log(`${m.blue}Watching ${m.bright}${y}${m.reset} for changes...`);let b=ke.watch(y,{recursive:!0},async(w,v)=>{if(!v||Mr(v))return;if(Rr(v)){console.log(`${m.yellow}File ${m.bright}${v}${m.yellow} changed, rebuilding...${m.reset}`),ct.clear(),lt();let k=await d();if(await zr(u),o&&s)if(k)s.reload(v);else s.error("Build failed - check console for details")}else if(jr(v)){if(console.log(`${m.cyan}CSS ${m.bright}${v}${m.cyan} changed${m.reset}`),o&&s)s.updateCss(v)}});process.on("SIGINT",()=>{if(b.close(),s)Wt();g.stop(),process.exit(0)})}return!0}var{serve:ku}=globalThis.Bun;import Ke from"fs";import ae from"path";var Ps=`
1147
1147
  <script data-stx-helpers>
1148
1148
  (function() {
1149
1149
  'use strict'
@@ -1454,14 +1454,14 @@ else {
1454
1454
 
1455
1455
  })()
1456
1456
  </script>
1457
- `;function Is(e){if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map((n)=>n.split(ie.sep)),r=[];for(let n=0;n<t[0].length;n++){let o=t[0][n];if(t.every((s)=>s[n]===o))r.push(o);else break}return r.join(ie.sep)}async function ku(e,t={}){let r=t.port||3000,n=t.watch!==!1;for(let h of e){let f=ie.resolve(h);if(!Ye.existsSync(f))return console.error(`${m.red}Error: File not found: ${m.bright}${f}${m.reset}`),!1;if(!f.endsWith(".stx")&&!f.endsWith(".md"))return console.error(`${m.red}Error: Unsupported file type: ${m.bright}${f}${m.reset}. Only .stx and .md files are supported.`),!1}let o=ke(process.cwd(),"output");Ye.mkdirSync(o,{recursive:!0});let s=Is(e.map((h)=>ie.dirname(ie.resolve(h))));console.log(`${m.blue}Processing ${m.bright}${e.length}${m.reset} files...`);let i={},a=[],c=async()=>{try{for(let h of e){let f=ie.resolve(h);if(f.endsWith(".md"))try{let{content:g,data:x}=await $e(f,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:je.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),y=t.markdown?.syntaxHighlighting||je.markdown?.syntaxHighlighting,b=y?.defaultTheme||"github-dark",w=["github-dark"],v=y?.additionalThemes||[],S=[...new Set([...w,...v])].map((j)=>`<option value="${j}"${j===b?" selected":""}>${j}</option>`).join(`
1458
- `),T=`
1457
+ `;function Ls(e){if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map((n)=>n.split(ae.sep)),r=[];for(let n=0;n<t[0].length;n++){let o=t[0][n];if(t.every((s)=>s[n]===o))r.push(o);else break}return r.join(ae.sep)}async function Tu(e,t={}){let r=t.port||3000,n=t.watch!==!1;for(let h of e){let f=ae.resolve(h);if(!Ke.existsSync(f))return console.error(`${m.red}Error: File not found: ${m.bright}${f}${m.reset}`),!1;if(!f.endsWith(".stx")&&!f.endsWith(".md"))return console.error(`${m.red}Error: Unsupported file type: ${m.bright}${f}${m.reset}. Only .stx and .md files are supported.`),!1}let o=Te(process.cwd(),"output");Ke.mkdirSync(o,{recursive:!0});let s=Ls(e.map((h)=>ae.dirname(ae.resolve(h))));console.log(`${m.blue}Processing ${m.bright}${e.length}${m.reset} files...`);let i={},a=[],c=async()=>{try{for(let h of e){let f=ae.resolve(h);if(f.endsWith(".md"))try{let{content:g,data:x}=await Se(f,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:Re.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),y=t.markdown?.syntaxHighlighting||Re.markdown?.syntaxHighlighting,b=y?.defaultTheme||"github-dark",w=["github-dark"],v=y?.additionalThemes||[],k=[...new Set([...w,...v])].map((R)=>`<option value="${R}"${R===b?" selected":""}>${R}</option>`).join(`
1458
+ `),C=`
1459
1459
  <!DOCTYPE html>
1460
1460
  <html lang="en">
1461
1461
  <head>
1462
1462
  <meta charset="UTF-8">
1463
1463
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1464
- <title>${Ps(x.title||ie.basename(f))}</title>
1464
+ <title>${Os(x.title||ae.basename(f))}</title>
1465
1465
  <!-- Syntax highlighting styles -->
1466
1466
  <style id="syntax-theme">
1467
1467
  :root {
@@ -1603,34 +1603,34 @@ else {
1603
1603
  min-width: 100px;
1604
1604
  color: #555;
1605
1605
  }
1606
- ${kr()}
1606
+ ${Tr()}
1607
1607
  </style>
1608
1608
  </head>
1609
1609
  <body>
1610
- ${Er(x)}
1611
- ${Tr(S)}
1610
+ ${_r(x)}
1611
+ ${Cr(k)}
1612
1612
 
1613
1613
  ${g}
1614
1614
 
1615
1615
  <script>
1616
- ${Cr()}
1616
+ ${Er()}
1617
1617
  </script>
1618
1618
  </body>
1619
1619
  </html>
1620
- `,C=`/${ie.relative(s,f).replace(/\.md$/,"")}`;if(C.endsWith("/index"))C=C.slice(0,-6)||"/";i[C||"/"]={filePath:f,content:T,fileType:"md"}}catch(g){console.error(`${m.red}Error processing Markdown file ${m.bright}${h}${m.reset}:`,g);continue}else{let g={name:"public-assets",setup(b){b.onResolve({filter:/^\/(images|fonts|assets|public)\//},(w)=>{return{path:w.path,external:!0}})}},x;try{let b=await Bun.build({entrypoints:[f],outdir:o,plugins:[g,Tt],define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!b.success){console.error(`${m.red}Build failed for ${m.bright}${h}${m.reset}:`,Ct(b.logs,f));continue}let w=b.outputs.find((v)=>v.path.endsWith(".html"));if(!w){console.error(`${m.red}No HTML output found for ${m.bright}${h}${m.reset}`);continue}x=await Bun.file(w.path).text()}catch(b){console.error(`${m.red}Build failed for ${m.bright}${h}${m.reset}:
1621
- ${Ct(b,f)}`);continue}let y=`/${ie.relative(s,f).replace(/\.stx$/,"")}`;if(y.endsWith("/index"))y=y.slice(0,-6)||"/";if(y.includes("[")){let{regex:b,params:w}=Os(y);a.push({pattern:b,paramNames:w,filePath:f,routeTemplate:y,fileType:"stx"}),i[y]={filePath:f,content:x,fileType:"stx"}}else i[y||"/"]={filePath:f,content:x,fileType:"stx"}}}if(Object.keys(i).length===0)return console.error(`${m.red}No files were successfully processed${m.reset}`),!1;return!0}catch(h){return console.error(`${m.red}Error processing files:${m.reset}`,Ct(h)),!1}};if(!await c())return!1;let l=r;try{if(l=await Xe(r),l!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${l} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${l}/${m.reset}...`);let d=Su({port:l,async fetch(h){let f=new URL(h.url),g=ie.join(process.cwd(),"public",f.pathname);if(Ye.existsSync(g)&&Ye.statSync(g).isFile()){let b=Bun.file(g),w=ie.extname(g).toLowerCase(),v="application/octet-stream";if(w===".ts"||w===".tsx"){let S=new Bun.Transpiler({loader:w===".tsx"?"tsx":"ts"}),T=await b.text(),C=S.transformSync(T);return new Response(C,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(w){case".html":v="text/html";break;case".css":v="text/css";break;case".js":v="text/javascript";break;case".json":v="application/json";break;case".png":v="image/png";break;case".jpg":case".jpeg":v="image/jpeg";break;case".gif":v="image/gif";break;case".svg":v="image/svg+xml";break;case".ico":v="image/x-icon";break;case".woff":v="font/woff";break;case".woff2":v="font/woff2";break;case".ttf":v="font/ttf";break;case".otf":v="font/otf";break;case".eot":v="application/vnd.ms-fontobject";break}return new Response(b,{headers:{"Content-Type":v}})}let x=i[f.pathname];if(!x&&!f.pathname.endsWith("/"))x=i[`${f.pathname}/`];if(!x)for(let b of a){let w=f.pathname.match(b.pattern);if(w){let v=i[b.routeTemplate];if(v){let S={};for(let j=0;j<b.paramNames.length;j++)S[b.paramNames[j]]=decodeURIComponent(w[j+1]);let T=v.content,C=`<script>window.__routeParams = ${JSON.stringify(S)};</script>`;if(T.includes("</head>"))T=T.replace("</head>",`${C}
1622
- </head>`);else T=C+T;x={...v,content:T}}break}}if(x)return re(x.content).then((b)=>{if(b.includes("</head>"))b=b.replace("</head>",`${Ds}
1623
- </head>`);return new Response(b,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let y=ie.join(o,f.pathname);if(Ye.existsSync(y)&&Ye.statSync(y).isFile()){let b=Bun.file(y),w=ie.extname(y).toLowerCase(),v="text/plain";if(w===".ts"||w===".tsx"){let S=new Bun.Transpiler({loader:w===".tsx"?"tsx":"ts"}),T=await b.text(),C=S.transformSync(T);return new Response(C,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(w){case".html":v="text/html";break;case".css":v="text/css";break;case".js":v="text/javascript";break;case".json":v="application/json";break;case".png":v="image/png";break;case".jpg":case".jpeg":v="image/jpeg";break;case".gif":v="image/gif";break;case".svg":v="image/svg+xml";break;case".ico":v="image/x-icon";break;case".woff":v="font/woff";break;case".woff2":v="font/woff2";break;case".ttf":v="font/ttf";break;case".otf":v="font/otf";break;case".eot":v="application/vnd.ms-fontobject";break}return new Response(b,{headers:{"Content-Type":v}})}if(f.pathname!=="/"&&i["/"]){let b=h.headers.get("X-STX-Router")==="true";return re(i["/"].content).then((w)=>{if(b){let v=w.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(v){let S=w.match(/<title[^>]*>([\s\S]*?)<\/title>/i),T=S?S[1]:"",C=`<!DOCTYPE html><html><head><title>${Ps(T)}</title></head><body><main>${v[1]}</main></body></html>`;return new Response(C,{headers:{"Content-Type":"text/html","X-STX-Partial":"true","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}return new Response(w,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(h){return new Response(`<pre>${h}
1620
+ `,E=`/${ae.relative(s,f).replace(/\.md$/,"")}`;if(E.endsWith("/index"))E=E.slice(0,-6)||"/";i[E||"/"]={filePath:f,content:C,fileType:"md"}}catch(g){console.error(`${m.red}Error processing Markdown file ${m.bright}${h}${m.reset}:`,g);continue}else{let g={name:"public-assets",setup(b){b.onResolve({filter:/^\/(images|fonts|assets|public)\//},(w)=>({path:w.path,external:!0}))}},x;try{let b=await Bun.build({entrypoints:[f],outdir:o,plugins:[g,Ct],define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!b.success){console.error(`${m.red}Build failed for ${m.bright}${h}${m.reset}:`,Et(b.logs,f));continue}let w=b.outputs.find((v)=>v.path.endsWith(".html"));if(!w){console.error(`${m.red}No HTML output found for ${m.bright}${h}${m.reset}`);continue}x=await Bun.file(w.path).text()}catch(b){console.error(`${m.red}Build failed for ${m.bright}${h}${m.reset}:
1621
+ ${Et(b,f)}`);continue}let y=`/${ae.relative(s,f).replace(/\.stx$/,"")}`;if(y.endsWith("/index"))y=y.slice(0,-6)||"/";if(y.includes("[")){let{regex:b,params:w}=Is(y);a.push({pattern:b,paramNames:w,filePath:f,routeTemplate:y,fileType:"stx"}),i[y]={filePath:f,content:x,fileType:"stx"}}else i[y||"/"]={filePath:f,content:x,fileType:"stx"}}}if(Object.keys(i).length===0)return console.error(`${m.red}No files were successfully processed${m.reset}`),!1;return!0}catch(h){return console.error(`${m.red}Error processing files:${m.reset}`,Et(h)),!1}};if(!await c())return!1;let l=r;try{if(l=await Je(r),l!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${l} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}console.log(`${m.blue}Starting server on ${m.cyan}http://localhost:${l}/${m.reset}...`);let d=ku({port:l,async fetch(h){let f=new URL(h.url),g=ae.join(process.cwd(),"public",f.pathname);if(Ke.existsSync(g)&&Ke.statSync(g).isFile()){let b=Bun.file(g),w=ae.extname(g).toLowerCase(),v="application/octet-stream";if(w===".ts"||w===".tsx"){let k=new Bun.Transpiler({loader:w===".tsx"?"tsx":"ts"}),C=await b.text(),E=k.transformSync(C);return new Response(E,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(w){case".html":v="text/html";break;case".css":v="text/css";break;case".js":v="text/javascript";break;case".json":v="application/json";break;case".png":v="image/png";break;case".jpg":case".jpeg":v="image/jpeg";break;case".gif":v="image/gif";break;case".svg":v="image/svg+xml";break;case".ico":v="image/x-icon";break;case".woff":v="font/woff";break;case".woff2":v="font/woff2";break;case".ttf":v="font/ttf";break;case".otf":v="font/otf";break;case".eot":v="application/vnd.ms-fontobject";break}return new Response(b,{headers:{"Content-Type":v}})}let x=i[f.pathname];if(!x&&!f.pathname.endsWith("/"))x=i[`${f.pathname}/`];if(!x)for(let b of a){let w=f.pathname.match(b.pattern);if(w){let v=i[b.routeTemplate];if(v){let k={};for(let R=0;R<b.paramNames.length;R++)k[b.paramNames[R]]=decodeURIComponent(w[R+1]);let C=v.content,E=`<script>window.__routeParams = ${JSON.stringify(k)};</script>`;if(C.includes("</head>"))C=C.replace("</head>",`${E}
1622
+ </head>`);else C=E+C;x={...v,content:C}}break}}if(x)return ne(x.content).then((b)=>{if(b.includes("</head>"))b=b.replace("</head>",`${Ps}
1623
+ </head>`);return new Response(b,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let y=ae.join(o,f.pathname);if(Ke.existsSync(y)&&Ke.statSync(y).isFile()){let b=Bun.file(y),w=ae.extname(y).toLowerCase(),v="text/plain";if(w===".ts"||w===".tsx"){let k=new Bun.Transpiler({loader:w===".tsx"?"tsx":"ts"}),C=await b.text(),E=k.transformSync(C);return new Response(E,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(w){case".html":v="text/html";break;case".css":v="text/css";break;case".js":v="text/javascript";break;case".json":v="application/json";break;case".png":v="image/png";break;case".jpg":case".jpeg":v="image/jpeg";break;case".gif":v="image/gif";break;case".svg":v="image/svg+xml";break;case".ico":v="image/x-icon";break;case".woff":v="font/woff";break;case".woff2":v="font/woff2";break;case".ttf":v="font/ttf";break;case".otf":v="font/otf";break;case".eot":v="application/vnd.ms-fontobject";break}return new Response(b,{headers:{"Content-Type":v}})}if(f.pathname!=="/"&&i["/"]){let b=h.headers.get("X-STX-Router")==="true";return ne(i["/"].content).then((w)=>{if(b){let v=w.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(v){let k=w.match(/<title[^>]*>([\s\S]*?)<\/title>/i),C=k?k[1]:"",E=`<!DOCTYPE html><html><head><title>${Os(C)}</title></head><body><main>${v[1]}</main></body></html>`;return new Response(E,{headers:{"Content-Type":"text/html","X-STX-Partial":"true","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}return new Response(w,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(h){return new Response(`<pre>${h}
1624
1624
  ${h.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1625
1625
  ${m.blue}stx${m.reset} ${m.green}${process.env.stx_VERSION||"v0.0.10"}${m.reset} ${m.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${m.reset}`),console.log(`
1626
1626
  ${m.bright}\u2192 ${m.cyan}http://localhost:${l}/${m.reset}`),console.log(`
1627
- ${m.yellow}Routes:${m.reset}`);let u=new Set(a.map((h)=>h.routeTemplate)),p=Object.entries(i).filter(([h])=>!u.has(h)).sort(([h],[f])=>h.localeCompare(f)).map(([h,f])=>({route:h==="/"?"/":h,filePath:ie.relative(process.cwd(),f.filePath),fileType:f.fileType}));for(let h of a){let f=h.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");p.push({route:f,filePath:ie.relative(process.cwd(),h.filePath),fileType:"stx"})}if(p.sort((h,f)=>h.route.localeCompare(f.route)),p.forEach((h,f)=>{let g=f===p.length-1?"\u2514\u2500 ":"\u251C\u2500 ",x=h.fileType==="md"?`${m.magenta}(markdown)${m.reset}`:"";console.log(` ${m.green}${g}${h.route}${m.reset} \u2192 ${m.bright}${h.filePath}${m.reset} ${x}`)}),console.log(`
1628
- Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(d.url.toString(),()=>{if(n)Ye.watch(s,{recursive:!0}).close();d.stop()}),n){console.log(`${m.blue}Watching for changes...${m.reset}`);let h=Ye.watch(s,{recursive:!0},async(f,g)=>{if(!g)return;if(g.endsWith(".stx")||g.endsWith(".js")||g.endsWith(".ts")||g.endsWith(".md"))console.log(`${m.yellow}File ${m.bright}${g}${m.yellow} changed, rebuilding...${m.reset}`),at.clear(),ct(),await c()});process.on("SIGINT",()=>{h.close(),d.stop(),process.exit(0)})}return!0}function Ps(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Cu}=globalThis.Bun;import ge from"fs";import H from"path";async function Ls(e){try{return Nn(await Bun.file(e).text())}catch{return}}function to(e){let t=Bun.file(e),r=H.extname(e).toLowerCase(),n={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},o=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":n[r]||"application/octet-stream",...o}})}async function Eu(e=".",t={}){let r=t.port||3000,n=t.watch!==!1,o=t.hotReload!==!1&&n,s=null,i=t.hmrPort||r+1,a=H.resolve(e),{loadStxConfig:c}=await import("./chunk-kxp888dn.js"),l=await c(a),d=l.root&&l.root!=="."?H.join(a,l.root):a,u=t.pagesDir||l.pagesDir||"pages",p=H.join(d,u);if(!ge.existsSync(p))return console.error(`${m.red}Error: No '${u}' directory found${m.reset}`),console.log(`${m.dim}Looked in: ${m.bright}${p}${m.reset}`),console.log(`${m.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${m.reset}`),console.log(`${m.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${m.reset}`),console.log(`${m.dim}Starting fresh? Create ${u}/index.stx for the homepage.${m.reset}`),!1;let h=no(d,{pagesDir:u});if(h.length===0)return console.error(`${m.red}Error: No page files found in ${m.bright}${p}${m.reset}`),!1;console.log(`${m.blue}Found ${m.bright}${h.length}${m.blue} routes${m.reset}`);let f=l?._pluginPageDirs||[],g=[];for(let{dir:_,prefix:E}of f)if(ge.existsSync(_)){let A=no(H.dirname(_),{pagesDir:H.basename(_)});for(let R of A){let M=E==="/"?R.pattern:`${E}${R.pattern==="/"?"":R.pattern}`;g.push({route:{...R,pattern:M},prefix:E})}if(A.length>0)console.log(`${m.blue}Plugin pages: ${m.bright}${A.length}${m.blue} routes at ${m.cyan}${E}${m.reset}`)}let x=new Map,y=null,b=null;if(t.stxOptions?.shell!==!1){if(b=await Hs(a,t.stxOptions?.shell),b){if(y=await oo(b,t.stxOptions||{}),y)console.log(`${m.blue}Using app shell: ${m.bright}${H.relative(a,b)}${m.reset} ${m.dim}(deprecated: use layouts/default.stx instead)${m.reset}`)}}Bn(),await Un(a);let w=zn();if(w.length>0)console.log(`${m.blue}Loaded ${m.bright}${w.length}${m.blue} middleware: ${m.dim}${w.join(", ")}${m.reset}`);let v={},S=null;try{let{loadStxConfig:_}=await import("./chunk-kxp888dn.js"),E=await _(a);if(E?.apiRouter)S=E?.apiRouter,console.log(`${m.blue}Using custom router for API handling${m.reset}`);if(E?.apiRoutes){v=E.apiRoutes;let A=Object.keys(v).length;if(A>0)console.log(`${m.blue}Loaded ${m.bright}${A} API route${A>1?"s":""}${m.reset}`)}if(E?.broadcasting?.enabled)try{let{startBroadcasting:A,loadChannels:R}=await import("./chunk-zfbh14qe.js"),M=E.broadcasting;await A(M);let N=M.port??6001;console.log(`${m.magenta}Broadcasting on ${m.cyan}ws://localhost:${N}/ws${m.reset}`);let Z=H.join(process.cwd(),"channels.ts");if(ge.existsSync(Z))try{let z=await R(Z);console.log(`${m.blue}Loaded ${m.bright}${z} broadcast channel${z!==1?"s":""}${m.blue} from channels.ts${m.reset}`)}catch(z){console.warn(`${m.yellow}Failed to load channels.ts: ${z.message}${m.reset}`)}}catch(A){console.warn(`${m.yellow}Broadcasting failed to start: ${A.message}${m.reset}`)}}catch{}let T=ke(a,"output");ge.mkdirSync(T,{recursive:!0});let C=new Map,j=new Set,k=async(_)=>{let E=Fs(p,_);if(!E)return null;try{let A=await Bun.build({entrypoints:[E],outdir:T,plugins:[Tt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!A.success)return null;let R=A.outputs.find((M)=>M.path.endsWith(".html"));if(!R)return null;return await Bun.file(R.path).text()}catch{return null}},L=async(_,E)=>{try{let{processDirectives:A,extractVariables:R,defaultConfig:M,loadStxConfig:N,injectRouterScript:Z}=await import("./chunk-kxp888dn.js"),{checkCache:z,cacheTemplate:me,readFileCached:q,templateCache:nt}=await import("./chunk-wcrqs5z9.js"),Ce=await N(a),D=(V)=>{if(!V)return V;if(H.isAbsolute(V))return V;return H.resolve(a,V)},I={...M,...Ce,...t.stxOptions,autoShell:!0};if(t.debugDirectives)I.debug=!0;I.partialsDir=D(I.partialsDir),I.componentsDir=D(I.componentsDir),I.layoutsDir=D(I.layoutsDir),I.storesDir=D(I.storesDir||"stores"),I.cachePath=D(I.cachePath)??ke(a,"cache");let U=!E&&!t.profile,F=I.cache!==!1;if(F&&U){let V=nt.get(_.filePath);if(V)try{if((await ge.promises.stat(_.filePath)).mtime.getTime()<=V.mtime){let le=!0;for(let we of V.dependencies){if(!ge.existsSync(we)){le=!1;break}if((await ge.promises.stat(we)).mtime.getTime()>V.mtime){le=!1;break}}if(le){let we=V.output;if(y)we=Ur(we,{preserveHead:!0});return{route:_,content:we,status:await Ls(_.filePath)}}}}catch{}let be=await z(_.filePath,I);if(be){let le=be;if(y)le=Ur(le,{preserveHead:!0});return{route:_,content:le,status:await Ls(_.filePath)}}}let P=F?await q(_.filePath):await Bun.file(_.filePath).text(),pe=Nn(P),{classifyAllScripts:fe}=await import("./chunk-kxp888dn.js"),ce=fe(P),he=ce.server.map((V)=>V.content),Ee=P;for(let V of ce.server)Ee=Ee.replace(V.fullTag,"");let xe={__filename:_.filePath,__dirname:H.dirname(_.filePath),params:E??{},__stx_runtime_head:{}};for(let V of he)try{await R(V,xe,_.filePath)}catch(be){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",_.filePath,be?.message||be)}let $n=new Set,_e;if(t.profile){let V=performance.now();_e=await A(Ee,xe,_.filePath,I,$n);let be=performance.now()-V,le=H.relative(a,_.filePath)||_.filePath;console.log(`[stx:profile] ${le} \u2192 ${be.toFixed(2)}ms`)}else _e=await A(Ee,xe,_.filePath,I,$n);if(!y)_e=await Z(_e,{router:I.router});{let{interpolateScriptExpressions:V}=await import("./chunk-fjzye4qj.js");_e=_e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(be,le,we)=>{if(!/function\s+__stx_setup_/.test(we))return be;return`<script${le}>${V(we,xe)}</script>`})}if(y)_e=Ur(_e,{preserveHead:!0});if(F&&U)await me(_.filePath,_e,$n,I);let{extractStreamBoundaries:xl}=await import("./chunk-edrtesh7.js"),mt=xl(xe),Nt=xe.__streamTemplates;if(Nt&&typeof Nt==="object"&&Object.keys(Nt).length>0){let V=xe.streamBoundaries||{},be={...I,autoShell:!1},le=Object.keys(Nt).map((He)=>({id:He,render:async()=>{let bl=typeof V[He]==="function"?await V[He]():void 0;return A(Nt[He],{...xe,$boundary:bl},_.filePath,be,new Set)}})),we=new Set(le.map((He)=>He.id));mt=[...(mt||[]).filter((He)=>!we.has(He.id)),...le]}if(mt&&mt.length>0)j.add(_.pattern);else mt=void 0;return{route:_,content:_e,status:pe,boundaries:mt}}catch(A){return console.error(`${m.red}Error building ${m.bright}${_.pattern}${m.reset}:`,A),null}},X=8,K=async()=>{C.clear(),x.clear();for(let _=0;_<h.length;_+=X){let E=h.slice(_,_+X),A=await Promise.all(E.map((R)=>L(R)));for(let R of A)if(R)C.set(R.route.pattern,R)}for(let _=0;_<g.length;_+=X){let E=g.slice(_,_+X),A=await Promise.all(E.map(({route:R})=>L(R)));for(let R of A)if(R)x.set(R.route.pattern,R)}return C.size>0};if(console.log(`${m.blue}Building pages...${m.reset}`),!await K())return console.error(`${m.red}No pages were successfully built${m.reset}`),!1;await Nr(a);let ne=r;try{if(ne=await Xe(r),ne!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${ne} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}if(o){let _=t.hmrPort||ne+1;s=Mr({wsPort:_,verbose:!1}),i=s.start(_)}let ye=(_,E)=>{let A=`<script data-stx-route-params>(function(){var p=${JSON.stringify(E).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(_.includes("</head>"))return _.replace("</head>",`${A}</head>`);if(_.includes("<body"))return _.replace(/<body([^>]*)>/,`<body$1>${A}`);return A+_};console.log(`${m.blue}Starting server...${m.reset}`);let oe=Cu({port:ne,async fetch(_){let E=new URL(_.url),A=l?.publicDir||"public",R=H.join(a,A,E.pathname),M=H.join(a,E.pathname),N=H.join(T,E.pathname),[Z,z,me]=await Promise.all([ge.promises.stat(R).catch(()=>null),ge.promises.stat(M).catch(()=>null),ge.promises.stat(N).catch(()=>null)]);if(Z?.isFile())return to(R);if(z?.isFile())return to(M);if(me?.isFile())return to(N);if(E.pathname.startsWith("/_stx/component/")){let D=decodeURIComponent(E.pathname.slice(16));if(D)try{let I=`<${D} />`,U={...buildConfig,autoShell:!1},F=await processDirectives(I,{},H.join(a,"components",`${D}.stx`),U,new Set);return new Response(F,{headers:{"Content-Type":"text/html"}})}catch(I){return new Response(`<div class="stx-async-error">${I.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(E.pathname==="/_stx/img"){let{handleImageRequest:D}=await import("./chunk-xhepdj1f.js"),I=await D(_,{publicDir:H.join(a,A),cacheDir:ke(a,"cache","img")});if(I)return I}if(S)try{let D=await S.handleRequest(_);if(D.status!==404)return D}catch{}if(v[E.pathname])try{return await v[E.pathname](_)}catch(D){return new Response(JSON.stringify({error:D.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=ro(E.pathname,h);if(q){let D=C.get(q.route.pattern),I=j.has(q.route.pattern);if(q.route.isDynamic&&Object.keys(q.params).length>0||I){let U=await L(q.route,q.params);if(U)D=U}if(D){let U=D.status??200,F=(q.route.filePath?Bs(await Bun.file(q.route.filePath).text().catch(()=>"")):null)??{};if(F.validate){if(!await F.validate({params:q.params})){let pe=await k(404);if(pe){let fe=pe;if(fe=await re(fe,a),o)fe=Be(fe,i);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(F.middleware){let pe=Hn(E.pathname,q.params,F,E.search),fe=Wn(pe,null,_,{isServer:!0}),ce=await Vn(F.middleware,fe);if(ce.redirect){let he=ce.redirect.path,Ee=ce.redirect.options.redirectCode||302,xe=new Headers(ce.responseHeaders);return xe.set("Location",he),new Response(null,{status:Ee,headers:xe})}if(ce.abort){let{statusCode:he,message:Ee}=ce.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${he}</title></head><body><h1>Error ${he}</h1><p>${Ee}</p></body></html>`,{status:he,headers:{"Content-Type":"text/html"}})}if(Object.keys(ce.state).length>0){let he=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ce.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;D.content=D.content.replace("</head>",`${he}</head>`)}}let P=D.content;if(y&&Ws(_)){let pe=Hr(P),fe=Wr(P),ce=P.match(/<title[^>]*>([\s\S]*?)<\/title>/i),he=ce?ce[1].trim():"";if(Object.keys(q.params).length>0)P=ye(P,q.params);P=await re(P,a);let Ee=l?.router?.container||"main";return P=Vs(P,Ee),new Response(P,{status:U,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":pe.layout,"X-STX-Layout-Group":pe.group,"X-STX-Runtime":fe?"true":"false",...he&&{"X-STX-Title":encodeURIComponent(he)},[zs]:Us(),"Cache-Control":"no-store, no-cache, must-revalidate"}})}if(y)P=zr(y,P);if(Object.keys(q.params).length>0)P=ye(P,q.params);if(P=await re(P,a),o)P=Be(P,i);if(t.native)if(P.includes("<head>"))P=P.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else P="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+P;if(t.titlebarHidden)if(P.includes("<head>"))P=P.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else P=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${P}`;if(D.boundaries&&D.boundaries.length>0){let{renderStreamingPage:pe,streamToResponse:fe}=await import("./chunk-edrtesh7.js");return fe(pe(P,D.boundaries,{timeoutMs:30000}),{status:U,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(P,{status:U,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}if(g.length>0){let D=g.map((U)=>U.route),I=ro(E.pathname,D);if(I){let U=x.get(I.route.pattern);if(U){let F=U.content;if(y)F=zr(y,F);if(Object.keys(I.params).length>0)F=ye(F,I.params);if(F=await re(F,a),o)F=Be(F,i);return new Response(F,{status:U.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:U}of f)if(U!=="/"&&E.pathname.startsWith(U)){let F=x.get(U)||x.get(U+"/");if(F){let P=F.content;if(y)P=zr(y,P);if(P=await re(P,a),o)P=Be(P,i);return new Response(P,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let nt=C.get("/");if(nt){let D=nt.content;if(D=await re(D,a),o)D=Be(D,i);if(t.native)if(D.includes("<head>"))D=D.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else D="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+D;return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ce=await k(404);if(Ce){let D=Ce;if(D=await re(D,a),o)D=Be(D,i);return new Response(D,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(_){let E=await k(500);if(E)return new Response(E,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${_}
1629
- ${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1627
+ ${m.yellow}Routes:${m.reset}`);let u=new Set(a.map((h)=>h.routeTemplate)),p=Object.entries(i).filter(([h])=>!u.has(h)).sort(([h],[f])=>h.localeCompare(f)).map(([h,f])=>({route:h==="/"?"/":h,filePath:ae.relative(process.cwd(),f.filePath),fileType:f.fileType}));for(let h of a){let f=h.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");p.push({route:f,filePath:ae.relative(process.cwd(),h.filePath),fileType:"stx"})}if(p.sort((h,f)=>h.route.localeCompare(f.route)),p.forEach((h,f)=>{let g=f===p.length-1?"\u2514\u2500 ":"\u251C\u2500 ",x=h.fileType==="md"?`${m.magenta}(markdown)${m.reset}`:"";console.log(` ${m.green}${g}${h.route}${m.reset} \u2192 ${m.bright}${h.filePath}${m.reset} ${x}`)}),console.log(`
1628
+ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Ye(d.url.toString(),()=>{if(n)Ke.watch(s,{recursive:!0}).close();d.stop()}),n){console.log(`${m.blue}Watching for changes...${m.reset}`);let h=Ke.watch(s,{recursive:!0},async(f,g)=>{if(!g)return;if(g.endsWith(".stx")||g.endsWith(".js")||g.endsWith(".ts")||g.endsWith(".md"))console.log(`${m.yellow}File ${m.bright}${g}${m.yellow} changed, rebuilding...${m.reset}`),ct.clear(),lt(),await c()});process.on("SIGINT",()=>{h.close(),d.stop(),process.exit(0)})}return!0}function Os(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Eu}=globalThis.Bun;import ye from"fs";import W from"path";async function Fs(e){try{return Bn(await Bun.file(e).text())}catch{return}}function ro(e){let t=Bun.file(e),r=W.extname(e).toLowerCase(),n={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},o=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":n[r]||"application/octet-stream",...o}})}async function _u(e=".",t={}){let r=t.port||3000,n=t.watch!==!1,o=t.hotReload!==!1&&n,s=null,i=t.hmrPort||r+1,a=W.resolve(e),{loadStxConfig:c}=await import("./chunk-n2j24b0h.js"),l=await c(a),d=l.root&&l.root!=="."?W.join(a,l.root):a,u=t.pagesDir||l.pagesDir||"pages",p=W.join(d,u);if(!ye.existsSync(p))return console.error(`${m.red}Error: No '${u}' directory found${m.reset}`),console.log(`${m.dim}Looked in: ${m.bright}${p}${m.reset}`),console.log(`${m.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${m.reset}`),console.log(`${m.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${m.reset}`),console.log(`${m.dim}Starting fresh? Create ${u}/index.stx for the homepage.${m.reset}`),!1;let h=oo(d,{pagesDir:u});if(h.length===0)return console.error(`${m.red}Error: No page files found in ${m.bright}${p}${m.reset}`),!1;console.log(`${m.blue}Found ${m.bright}${h.length}${m.blue} routes${m.reset}`);let f=l?._pluginPageDirs||[],g=[];for(let{dir:A,prefix:_}of f)if(ye.existsSync(A)){let j=oo(W.dirname(A),{pagesDir:W.basename(A)});for(let M of j){let D=_==="/"?M.pattern:`${_}${M.pattern==="/"?"":M.pattern}`;g.push({route:{...M,pattern:D},prefix:_})}if(j.length>0)console.log(`${m.blue}Plugin pages: ${m.bright}${j.length}${m.blue} routes at ${m.cyan}${_}${m.reset}`)}let x=new Map,y=null,b=null;if(t.stxOptions?.shell!==!1){if(b=await Ws(a,t.stxOptions?.shell),b){if(y=await so(b,t.stxOptions||{}),y)console.log(`${m.blue}Using app shell: ${m.bright}${W.relative(a,b)}${m.reset} ${m.dim}(deprecated: use layouts/default.stx instead)${m.reset}`)}}zn(),await Hn(a);let w=Un();if(w.length>0)console.log(`${m.blue}Loaded ${m.bright}${w.length}${m.blue} middleware: ${m.dim}${w.join(", ")}${m.reset}`);let v={},k=null;try{let{loadStxConfig:A}=await import("./chunk-n2j24b0h.js"),_=await A(a);if(_?.apiRouter)k=_?.apiRouter,console.log(`${m.blue}Using custom router for API handling${m.reset}`);if(_?.apiRoutes){v=_.apiRoutes;let j=Object.keys(v).length;if(j>0)console.log(`${m.blue}Loaded ${m.bright}${j} API route${j>1?"s":""}${m.reset}`)}if(_?.broadcasting?.enabled)try{let{startBroadcasting:j,loadChannels:M}=await import("./chunk-r63za1mr.js"),D=_.broadcasting;await j(D);let B=D.port??6001;console.log(`${m.magenta}Broadcasting on ${m.cyan}ws://localhost:${B}/ws${m.reset}`);let Q=W.join(process.cwd(),"channels.ts");if(ye.existsSync(Q))try{let U=await M(Q);console.log(`${m.blue}Loaded ${m.bright}${U} broadcast channel${U!==1?"s":""}${m.blue} from channels.ts${m.reset}`)}catch(U){console.warn(`${m.yellow}Failed to load channels.ts: ${U.message}${m.reset}`)}}catch(j){console.warn(`${m.yellow}Broadcasting failed to start: ${j.message}${m.reset}`)}}catch{}let C=Te(a,"output");ye.mkdirSync(C,{recursive:!0});let E=new Map,R=new Set,T=async(A)=>{let _=Ns(p,A);if(!_)return null;try{let j=await Bun.build({entrypoints:[_],outdir:C,plugins:[Ct],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!j.success)return null;let M=j.outputs.find((D)=>D.path.endsWith(".html"));if(!M)return null;return await Bun.file(M.path).text()}catch{return null}},F=async(A,_)=>{try{let{processDirectives:j,extractVariables:M,defaultConfig:D,loadStxConfig:B,injectRouterScript:Q}=await import("./chunk-n2j24b0h.js"),{checkCache:U,cacheTemplate:he,readFileCached:X,templateCache:ot}=await import("./chunk-vg1erq1q.js"),Ee=await B(a),P=(q)=>{if(!q)return q;if(W.isAbsolute(q))return q;return W.resolve(a,q)},L={...D,...Ee,...t.stxOptions,autoShell:!0};if(t.debugDirectives)L.debug=!0;L.partialsDir=P(L.partialsDir),L.componentsDir=P(L.componentsDir),L.layoutsDir=P(L.layoutsDir),L.storesDir=P(L.storesDir||"stores"),L.cachePath=P(L.cachePath)??Te(a,"cache");let H=!_&&!t.profile,N=L.cache!==!1;if(N&&H){let q=ot.get(A.filePath);if(q)try{if((await ye.promises.stat(A.filePath)).mtime.getTime()<=q.mtime){let de=!0;for(let ve of q.dependencies){if(!ye.existsSync(ve)){de=!1;break}if((await ye.promises.stat(ve)).mtime.getTime()>q.mtime){de=!1;break}}if(de){let ve=q.output;if(y)ve=Hr(ve,{preserveHead:!0});return{route:A,content:ve,status:await Fs(A.filePath)}}}}catch{}let we=await U(A.filePath,L);if(we){let de=we;if(y)de=Hr(de,{preserveHead:!0});return{route:A,content:de,status:await Fs(A.filePath)}}}let O=N?await X(A.filePath):await Bun.file(A.filePath).text(),fe=Bn(O),{classifyAllScripts:me}=await import("./chunk-n2j24b0h.js"),le=me(O),ge=le.server.map((q)=>q.content),_e=O;for(let q of le.server)_e=_e.replace(q.fullTag,"");let be={__filename:A.filePath,__dirname:W.dirname(A.filePath),params:_??{},__stx_runtime_head:{}};for(let q of ge)try{await M(q,be,A.filePath)}catch(we){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,we?.message||we)}let Sn=new Set,Ae;if(t.profile){let q=performance.now();Ae=await j(_e,be,A.filePath,L,Sn);let we=performance.now()-q,de=W.relative(a,A.filePath)||A.filePath;console.log(`[stx:profile] ${de} \u2192 ${we.toFixed(2)}ms`)}else Ae=await j(_e,be,A.filePath,L,Sn);if(!y)Ae=await Q(Ae,{router:L.router});{let{interpolateScriptExpressions:q}=await import("./chunk-2152npfd.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(we,de,ve)=>{if(!/function\s+__stx_setup_/.test(ve))return we;return`<script${de}>${q(ve,be)}</script>`})}if(y)Ae=Hr(Ae,{preserveHead:!0});if(N&&H)await he(A.filePath,Ae,Sn,L);let{extractStreamBoundaries:bl}=await import("./chunk-5f0d9j9a.js"),ht=bl(be),Bt=be.__streamTemplates;if(Bt&&typeof Bt==="object"&&Object.keys(Bt).length>0){let q=be.streamBoundaries||{},we={...L,autoShell:!1},de=Object.keys(Bt).map((We)=>({id:We,render:async()=>{let wl=typeof q[We]==="function"?await q[We]():void 0;return j(Bt[We],{...be,$boundary:wl},A.filePath,we,new Set)}})),ve=new Set(de.map((We)=>We.id));ht=[...(ht||[]).filter((We)=>!ve.has(We.id)),...de]}if(ht&&ht.length>0)R.add(A.pattern);else ht=void 0;return{route:A,content:Ae,status:fe,boundaries:ht}}catch(j){return console.error(`${m.red}Error building ${m.bright}${A.pattern}${m.reset}:`,j),null}},J=8,G=async()=>{E.clear(),x.clear();for(let A=0;A<h.length;A+=J){let _=h.slice(A,A+J),j=await Promise.all(_.map((M)=>F(M)));for(let M of j)if(M)E.set(M.route.pattern,M)}for(let A=0;A<g.length;A+=J){let _=g.slice(A,A+J),j=await Promise.all(_.map(({route:M})=>F(M)));for(let M of j)if(M)x.set(M.route.pattern,M)}return E.size>0};if(console.log(`${m.blue}Building pages...${m.reset}`),!await G())return console.error(`${m.red}No pages were successfully built${m.reset}`),!1;await Br(a);let oe=r;try{if(oe=await Je(r),oe!==r)console.log(`${m.yellow}Port ${r} is busy, using port ${oe} instead${m.reset}`)}catch{return console.error(`${m.red}Could not find an available port${m.reset}`),!1}if(o){let A=t.hmrPort||oe+1;s=Dr({wsPort:A,verbose:!1}),i=s.start(A)}let xe=(A,_)=>{let j=`<script data-stx-route-params>(function(){var p=${JSON.stringify(_).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${j}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${j}`);return j+A};console.log(`${m.blue}Starting server...${m.reset}`);let se=Eu({port:oe,async fetch(A){let _=new URL(A.url),j=l?.publicDir||"public",M=W.join(a,j,_.pathname),D=W.join(a,_.pathname),B=W.join(C,_.pathname),[Q,U,he]=await Promise.all([ye.promises.stat(M).catch(()=>null),ye.promises.stat(D).catch(()=>null),ye.promises.stat(B).catch(()=>null)]);if(Q?.isFile())return ro(M);if(U?.isFile())return ro(D);if(he?.isFile())return ro(B);if(_.pathname.startsWith("/_stx/component/")){let P=decodeURIComponent(_.pathname.slice(16));if(P)try{let L=`<${P} />`,H={...buildConfig,autoShell:!1},N=await processDirectives(L,{},W.join(a,"components",`${P}.stx`),H,new Set);return new Response(N,{headers:{"Content-Type":"text/html"}})}catch(L){return new Response(`<div class="stx-async-error">${L.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(_.pathname==="/_stx/img"){let{handleImageRequest:P}=await import("./chunk-1wenkmk0.js"),L=await P(A,{publicDir:W.join(a,j),cacheDir:Te(a,"cache","img")});if(L)return L}if(k)try{let P=await k.handleRequest(A);if(P.status!==404)return P}catch{}if(v[_.pathname])try{return await v[_.pathname](A)}catch(P){return new Response(JSON.stringify({error:P.message}),{status:500,headers:{"Content-Type":"application/json"}})}let X=no(_.pathname,h);if(X){let P=E.get(X.route.pattern),L=R.has(X.route.pattern);if(X.route.isDynamic&&Object.keys(X.params).length>0||L){let H=await F(X.route,X.params);if(H)P=H}if(P){let H=P.status??200,N=(X.route.filePath?zs(await Bun.file(X.route.filePath).text().catch(()=>"")):null)??{};if(N.validate){if(!await N.validate({params:X.params})){let fe=await T(404);if(fe){let me=fe;if(me=await ne(me,a),o)me=ze(me,i);return new Response(me,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(N.middleware){let fe=Wn(_.pathname,X.params,N,_.search),me=Vn(fe,null,A,{isServer:!0}),le=await qn(N.middleware,me);if(le.redirect){let ge=le.redirect.path,_e=le.redirect.options.redirectCode||302,be=new Headers(le.responseHeaders);return be.set("Location",ge),new Response(null,{status:_e,headers:be})}if(le.abort){let{statusCode:ge,message:_e}=le.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ge}</title></head><body><h1>Error ${ge}</h1><p>${_e}</p></body></html>`,{status:ge,headers:{"Content-Type":"text/html"}})}if(Object.keys(le.state).length>0){let ge=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(le.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;P.content=P.content.replace("</head>",`${ge}</head>`)}}let O=P.content;if(y&&Vs(A)){let fe=Wr(O),me=Vr(O),le=O.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ge=le?le[1].trim():"";if(Object.keys(X.params).length>0)O=xe(O,X.params);O=await ne(O,a);let _e=l?.router?.container||"main";return O=qs(O,_e),new Response(O,{status:H,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":fe.layout,"X-STX-Layout-Group":fe.group,"X-STX-Runtime":me?"true":"false",...ge&&{"X-STX-Title":encodeURIComponent(ge)},[Us]:Hs(),"Cache-Control":"no-store, no-cache, must-revalidate"}})}if(y)O=Ur(y,O);if(Object.keys(X.params).length>0)O=xe(O,X.params);if(O=await ne(O,a),o)O=ze(O,i);if(t.native)if(O.includes("<head>"))O=O.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;if(t.titlebarHidden)if(O.includes("<head>"))O=O.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else O=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${O}`;if(P.boundaries&&P.boundaries.length>0){let{renderStreamingPage:fe,streamToResponse:me}=await import("./chunk-5f0d9j9a.js");return me(fe(O,P.boundaries,{timeoutMs:30000}),{status:H,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(O,{status:H,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}if(g.length>0){let P=g.map((H)=>H.route),L=no(_.pathname,P);if(L){let H=x.get(L.route.pattern);if(H){let N=H.content;if(y)N=Ur(y,N);if(Object.keys(L.params).length>0)N=xe(N,L.params);if(N=await ne(N,a),o)N=ze(N,i);return new Response(N,{status:H.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:H}of f)if(H!=="/"&&_.pathname.startsWith(H)){let N=x.get(H)||x.get(H+"/");if(N){let O=N.content;if(y)O=Ur(y,O);if(O=await ne(O,a),o)O=ze(O,i);return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let ot=E.get("/");if(ot){let P=ot.content;if(P=await ne(P,a),o)P=ze(P,i);if(t.native)if(P.includes("<head>"))P=P.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else P="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+P;return new Response(P,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ee=await T(404);if(Ee){let P=Ee;if(P=await ne(P,a),o)P=ze(P,i);return new Response(P,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let _=await T(500);if(_)return new Response(_,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
1629
+ ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1630
1630
  ${m.blue}stx${m.reset} ${m.green}${process.env.stx_VERSION||"v0.0.10"}${m.reset} ${m.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${m.reset}`),console.log(`
1631
- ${m.bright}\u2192 ${m.cyan}http://localhost:${ne}/${m.reset}`),o)console.log(`${m.dim} HMR: ws://localhost:${i}${m.reset}`);console.log(`
1632
- ${m.yellow}Routes:${m.reset}`);let G=[...Ns(h,a)];for(let{route:_}of g)G.push(`${_.pattern}`);if(G.forEach((_,E)=>{let A=E===G.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${m.green}${A}${m.reset}${_}`)}),console.log(`
1633
- Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.url.toString(),()=>{if(s)Ht();oe.stop()}),t.native){let _,E=H.join(p,"index.stx");if(ge.existsSync(E)){let R=await Bun.file(E).text();_=_r(R)}let A=l?.app?.window??{};await vt(ne,{title:l?.app?.head?.title||H.basename(a)||"stx App",width:A.width,height:A.height,darkMode:A.darkMode,hotReload:A.hotReload,titlebarHidden:A.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!_,sidebarConfig:_})}if(n){console.log(`${m.blue}Watching for changes...${m.reset}`);let _=(R)=>{return R.startsWith("public/")||R.startsWith("public\\")},E=(R)=>{let M=R.toLowerCase();return M.endsWith(".stx")||M.endsWith(".html")||M.endsWith(".md")},A=ge.watch(a,{recursive:!0},async(R,M)=>{if(!M||Rr(M))return;if(jr(M))if(_(M)){if(console.log(`${m.cyan}${M} changed${m.reset}`),o&&s)s.reload(M)}else if(E(M)){console.log(`${m.yellow}${M} changed, rebuilding...${m.reset}`),at.clear(),ct();try{let{invalidateFileCache:N,templateCache:Z}=await import("./chunk-wcrqs5z9.js");N(H.resolve(a,M)),Z.delete(H.resolve(a,M))}catch{}if(b&&M){if(H.resolve(a,M)===b||H.basename(b)===M){let N=await oo(b,t.stxOptions||{});if(N)y=N}}if(await K(),await Br(a),o&&s)s.reload(M)}else{console.log(`${m.yellow}${M} changed, rebuilding...${m.reset}`),at.clear(),ct();try{let{invalidateFileCache:N,templateCache:Z}=await import("./chunk-wcrqs5z9.js");N(H.resolve(a,M)),Z.delete(H.resolve(a,M))}catch{}if(await K(),o&&s)s.reload(M)}else if(Ar(M)){if(console.log(`${m.cyan}CSS ${M} changed${m.reset}`),o&&s)s.updateCss(M)}});process.on("SIGINT",()=>{if(A.close(),s)Ht();oe.stop(),process.exit(0)})}return!0}var _u=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Au(e){let t=(e||"").trim();if(!t)return null;if(/[\s>+~,:]/.test(t))return null;let r={},n=t,o=n.match(/^[a-z][\w-]*/i);if(o)r.tag=o[0].toLowerCase(),n=n.slice(o[0].length);while(n.length>0){let s=n.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(s){if(r.attr=s[1],s[3]!==void 0&&s[3]!=="")r.attrValue=s[3];n=n.slice(s[0].length);continue}let i=n.match(/^#([\w-]+)/);if(i){r.id=i[1],n=n.slice(i[0].length);continue}let a=n.match(/^\.([\w-]+)/);if(a){r.className=a[1],n=n.slice(a[0].length);continue}return null}if(!r.tag&&!r.attr&&!r.id&&!r.className)return null;return r}function ju(e,t){if(t.attr){if(!(t.attrValue===void 0?new RegExp(`\\b${t.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${t.attr}\\s*=\\s*(["'])\\s*${t.attrValue}\\s*\\1`,"i")).test(e))return!1}if(t.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${t.id}\\s*\\1`,"i").test(e))return!1}if(t.className){let r=e.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!r)return!1;if(!r[2].split(/\s+/).includes(t.className))return!1}return!0}function mw(e,t="main"){let r=Au(t);if(!r)return null;let n=/<([a-z][\w-]*)\b([^>]*)>/gi,o;while((o=n.exec(e))!==null){let s=o[1].toLowerCase(),i=o[2]||"";if(i.trimEnd().endsWith("/")||_u.has(s))continue;if(r.tag&&r.tag!==s)continue;if(!ju(i,r))continue;let a=o[0],c=o.index+a.length,l=new RegExp(`<(/?)${s}\\b([^>]*)>`,"gi");l.lastIndex=c;let d=1,u;while((u=l.exec(e))!==null){let p=u[1]==="/";if(!p&&(u[2]||"").trimEnd().endsWith("/"))continue;if(d+=p?-1:1,d===0)return{openTag:a,openIndex:o.index,start:c,end:u.index,tagName:s}}return null}return null}var O={enabled:!1,components:new Map,stores:new Map,events:[],performance:[],selectedComponent:null,selectedStore:null,maxEvents:1000,maxPerformance:500};function Ru(e={}){if(typeof window>"u")return;O.enabled=!0,O.maxEvents=e.maxEvents||1000,O.maxPerformance=e.maxPerformance||500,window.__STX_DEVTOOLS__={getState:()=>O,getComponents:()=>Array.from(O.components.values()),getComponent:(t)=>O.components.get(t),getStores:()=>Array.from(O.stores.values()),getStore:(t)=>O.stores.get(t),getEvents:()=>O.events,getPerformance:()=>O.performance,selectComponent:(t)=>io(t),selectStore:(t)=>Du(t),inspectElement:(t)=>Pu(t),highlightComponent:(t)=>Ks(t),clearHighlight:()=>Gs(),logComponentTree:()=>Ou(),logStoreState:(t)=>Iu(t),timeTravel:(t,r)=>Lu(t,r)},Nu(),Fu(),console.log("%c[STX DevTools] Enabled","color: #10b981; font-weight: bold;")}function Mu(){O.enabled=!1,delete window.__STX_DEVTOOLS__;let e=document.getElementById("stx-devtools-panel");if(e)e.remove();console.log("%c[STX DevTools] Disabled","color: #ef4444;")}function qs(e){if(!O.enabled)return;let t=O.components.get(e);if(t){if(t.parentId){let r=O.components.get(t.parentId);if(r)r.children=r.children.filter((n)=>n!==e)}O.components.delete(e),so({timestamp:Date.now(),type:"component:unmounted",componentId:e,payload:{name:t.name}})}}function Js(e,t,r={},n=[]){if(!O.enabled)return;let o={id:e,state:t,getters:r,actions:n,history:[{timestamp:Date.now(),type:"state",name:"__init__",newValue:t}]};O.stores.set(e,o),so({timestamp:Date.now(),type:"store:registered",payload:{id:e,state:t}})}function Ys(e,t,r,n,o="state"){if(!O.enabled)return;let s=O.stores.get(e);if(s){let i={timestamp:Date.now(),type:o,name:t,oldValue:r,newValue:n,stack:Error().stack};if(s.history.push(i),s.history.length>100)s.history=s.history.slice(-100);if(o==="state")s.state={...s.state,[t]:n};so({timestamp:Date.now(),type:`store:${o}`,payload:{storeId:e,name:t,oldValue:r,newValue:n}})}}function so(e){if(!O.enabled)return;if(O.events.push(e),O.events.length>O.maxEvents)O.events=O.events.slice(-O.maxEvents);if(typeof window<"u")window.dispatchEvent(new CustomEvent("stx:devtools:event",{detail:e}))}function io(e){O.selectedComponent=e;let t=O.components.get(e);if(t)Ks(e),console.log("%c[STX DevTools] Selected component:","color: #3b82f6;",t);return t}function Du(e){O.selectedStore=e;let t=O.stores.get(e);if(t)console.log("%c[STX DevTools] Selected store:","color: #8b5cf6;",t);return t}function Pu(e){let t=e;while(t){let r=t.getAttribute("data-stx-component-id");if(r)return io(r);t=t.parentElement}console.log("%c[STX DevTools] No component found for element","color: #f59e0b;");return}function Ks(e){Gs();let t=O.components.get(e);if(t?.element){let r=document.createElement("div");r.id="stx-devtools-highlight",r.style.cssText=`
1631
+ ${m.bright}\u2192 ${m.cyan}http://localhost:${oe}/${m.reset}`),o)console.log(`${m.dim} HMR: ws://localhost:${i}${m.reset}`);console.log(`
1632
+ ${m.yellow}Routes:${m.reset}`);let Z=[...Bs(h,a)];for(let{route:A}of g)Z.push(`${A.pattern}`);if(Z.forEach((A,_)=>{let j=_===Z.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${m.green}${j}${m.reset}${A}`)}),console.log(`
1633
+ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Ye(se.url.toString(),()=>{if(s)Wt();se.stop()}),t.native){let A,_=W.join(p,"index.stx");if(ye.existsSync(_)){let M=await Bun.file(_).text();A=Ar(M)}let j=l?.app?.window??{};await $t(oe,{title:l?.app?.head?.title||W.basename(a)||"stx App",width:j.width,height:j.height,darkMode:j.darkMode,hotReload:j.hotReload,titlebarHidden:j.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(n){console.log(`${m.blue}Watching for changes...${m.reset}`);let A=(M)=>M.startsWith("public/")||M.startsWith("public\\"),_=(M)=>{let D=M.toLowerCase();return D.endsWith(".stx")||D.endsWith(".html")||D.endsWith(".md")},j=ye.watch(a,{recursive:!0},async(M,D)=>{if(!D||Mr(D))return;if(Rr(D))if(A(D)){if(console.log(`${m.cyan}${D} changed${m.reset}`),o&&s)s.reload(D)}else if(_(D)){console.log(`${m.yellow}${D} changed, rebuilding...${m.reset}`),ct.clear(),lt();try{let{invalidateFileCache:B,templateCache:Q}=await import("./chunk-vg1erq1q.js");B(W.resolve(a,D)),Q.delete(W.resolve(a,D))}catch{}if(b&&D){if(W.resolve(a,D)===b||W.basename(b)===D){let B=await so(b,t.stxOptions||{});if(B)y=B}}if(await G(),await zr(a),o&&s)s.reload(D)}else{console.log(`${m.yellow}${D} changed, rebuilding...${m.reset}`),ct.clear(),lt();try{let{invalidateFileCache:B,templateCache:Q}=await import("./chunk-vg1erq1q.js");B(W.resolve(a,D)),Q.delete(W.resolve(a,D))}catch{}if(await G(),o&&s)s.reload(D)}else if(jr(D)){if(console.log(`${m.cyan}CSS ${D} changed${m.reset}`),o&&s)s.updateCss(D)}});process.on("SIGINT",()=>{if(j.close(),s)Wt();se.stop(),process.exit(0)})}return!0}var Au=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function ju(e){let t=(e||"").trim();if(!t)return null;if(/[\s>+~,:]/.test(t))return null;let r={},n=t,o=n.match(/^[a-z][\w-]*/i);if(o)r.tag=o[0].toLowerCase(),n=n.slice(o[0].length);while(n.length>0){let s=n.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(s){if(r.attr=s[1],s[3]!==void 0&&s[3]!=="")r.attrValue=s[3];n=n.slice(s[0].length);continue}let i=n.match(/^#([\w-]+)/);if(i){r.id=i[1],n=n.slice(i[0].length);continue}let a=n.match(/^\.([\w-]+)/);if(a){r.className=a[1],n=n.slice(a[0].length);continue}return null}if(!r.tag&&!r.attr&&!r.id&&!r.className)return null;return r}function Ru(e,t){if(t.attr){if(!(t.attrValue===void 0?new RegExp(`\\b${t.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${t.attr}\\s*=\\s*(["'])\\s*${t.attrValue}\\s*\\1`,"i")).test(e))return!1}if(t.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${t.id}\\s*\\1`,"i").test(e))return!1}if(t.className){let r=e.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!r)return!1;if(!r[2].split(/\s+/).includes(t.className))return!1}return!0}function hw(e,t="main"){let r=ju(t);if(!r)return null;let n=/<([a-z][\w-]*)\b([^>]*)>/gi,o;while((o=n.exec(e))!==null){let s=o[1].toLowerCase(),i=o[2]||"";if(i.trimEnd().endsWith("/")||Au.has(s))continue;if(r.tag&&r.tag!==s)continue;if(!Ru(i,r))continue;let a=o[0],c=o.index+a.length,l=new RegExp(`<(/?)${s}\\b([^>]*)>`,"gi");l.lastIndex=c;let d=1,u;while((u=l.exec(e))!==null){let p=u[1]==="/";if(!p&&(u[2]||"").trimEnd().endsWith("/"))continue;if(d+=p?-1:1,d===0)return{openTag:a,openIndex:o.index,start:c,end:u.index,tagName:s}}return null}return null}var I={enabled:!1,components:new Map,stores:new Map,events:[],performance:[],selectedComponent:null,selectedStore:null,maxEvents:1000,maxPerformance:500};function Mu(e={}){if(typeof window>"u")return;I.enabled=!0,I.maxEvents=e.maxEvents||1000,I.maxPerformance=e.maxPerformance||500,window.__STX_DEVTOOLS__={getState:()=>I,getComponents:()=>Array.from(I.components.values()),getComponent:(t)=>I.components.get(t),getStores:()=>Array.from(I.stores.values()),getStore:(t)=>I.stores.get(t),getEvents:()=>I.events,getPerformance:()=>I.performance,selectComponent:(t)=>ao(t),selectStore:(t)=>Pu(t),inspectElement:(t)=>Ou(t),highlightComponent:(t)=>Gs(t),clearHighlight:()=>Zs(),logComponentTree:()=>Iu(),logStoreState:(t)=>Lu(t),timeTravel:(t,r)=>Fu(t,r)},Bu(),Nu(),console.log("%c[STX DevTools] Enabled","color: #10b981; font-weight: bold;")}function Du(){I.enabled=!1,delete window.__STX_DEVTOOLS__;let e=document.getElementById("stx-devtools-panel");if(e)e.remove();console.log("%c[STX DevTools] Disabled","color: #ef4444;")}function Xs(e){if(!I.enabled)return;let t=I.components.get(e);if(t){if(t.parentId){let r=I.components.get(t.parentId);if(r)r.children=r.children.filter((n)=>n!==e)}I.components.delete(e),io({timestamp:Date.now(),type:"component:unmounted",componentId:e,payload:{name:t.name}})}}function Ys(e,t,r={},n=[]){if(!I.enabled)return;let o={id:e,state:t,getters:r,actions:n,history:[{timestamp:Date.now(),type:"state",name:"__init__",newValue:t}]};I.stores.set(e,o),io({timestamp:Date.now(),type:"store:registered",payload:{id:e,state:t}})}function Ks(e,t,r,n,o="state"){if(!I.enabled)return;let s=I.stores.get(e);if(s){let i={timestamp:Date.now(),type:o,name:t,oldValue:r,newValue:n,stack:Error().stack};if(s.history.push(i),s.history.length>100)s.history=s.history.slice(-100);if(o==="state")s.state={...s.state,[t]:n};io({timestamp:Date.now(),type:`store:${o}`,payload:{storeId:e,name:t,oldValue:r,newValue:n}})}}function io(e){if(!I.enabled)return;if(I.events.push(e),I.events.length>I.maxEvents)I.events=I.events.slice(-I.maxEvents);if(typeof window<"u")window.dispatchEvent(new CustomEvent("stx:devtools:event",{detail:e}))}function ao(e){I.selectedComponent=e;let t=I.components.get(e);if(t)Gs(e),console.log("%c[STX DevTools] Selected component:","color: #3b82f6;",t);return t}function Pu(e){I.selectedStore=e;let t=I.stores.get(e);if(t)console.log("%c[STX DevTools] Selected store:","color: #8b5cf6;",t);return t}function Ou(e){let t=e;while(t){let r=t.getAttribute("data-stx-component-id");if(r)return ao(r);t=t.parentElement}console.log("%c[STX DevTools] No component found for element","color: #f59e0b;");return}function Gs(e){Zs();let t=I.components.get(e);if(t?.element){let r=document.createElement("div");r.id="stx-devtools-highlight",r.style.cssText=`
1634
1634
  position: absolute;
1635
1635
  background: rgba(59, 130, 246, 0.2);
1636
1636
  border: 2px solid #3b82f6;
@@ -1648,7 +1648,7 @@ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.
1648
1648
  font-family: monospace;
1649
1649
  border-radius: 4px;
1650
1650
  white-space: nowrap;
1651
- `,o.textContent=`<${t.name}>`,r.appendChild(o),document.body.appendChild(r)}}function Gs(){let e=document.getElementById("stx-devtools-highlight");if(e)e.remove()}function Ou(){console.group("%c[STX DevTools] Component Tree","color: #10b981; font-weight: bold;");let e=Array.from(O.components.values()).filter((r)=>!r.parentId);function t(r,n){let o=" ".repeat(n);if(console.log(`${o}%c<${r.name}>%c id=${r.id} renders=${r.renderCount}`,"color: #3b82f6;","color: #6b7280;"),Object.keys(r.props).length>0)console.log(`${o} props:`,r.props);if(Object.keys(r.state).length>0)console.log(`${o} state:`,r.state);for(let s of r.children){let i=O.components.get(s);if(i)t(i,n+1)}}for(let r of e)t(r,0);console.groupEnd()}function Iu(e){console.group("%c[STX DevTools] Store State","color: #8b5cf6; font-weight: bold;");let t=e?[O.stores.get(e)].filter(Boolean):Array.from(O.stores.values());for(let r of t)if(r)console.group(`Store: ${r.id}`),console.log("State:",r.state),console.log("Getters:",r.getters),console.log("Actions:",r.actions),console.log("History:",r.history),console.groupEnd();console.groupEnd()}function Lu(e,t){let r=O.stores.get(t);if(!r)return;if(e<0||e>=r.history.length){console.warn("[STX DevTools] Invalid history index");return}let n={};for(let o=0;o<=e;o++){let s=r.history[o];if(s.type==="state"&&s.name!=="__init__")n[s.name]=s.newValue;else if(s.name==="__init__")Object.assign(n,s.newValue)}if(console.log(`%c[STX DevTools] Time traveled to index ${e}`,"color: #f59e0b;",n),typeof window<"u"&&window.__STX_STORES__){let o=window.__STX_STORES__[t];if(o&&typeof o.$patch==="function")o.$patch(n)}}function Fu(){if(typeof MutationObserver>"u")return;new MutationObserver((e)=>{for(let t of e)t.removedNodes.forEach((r)=>{if(r instanceof HTMLElement){let n=r.getAttribute("data-stx-component-id");if(n)qs(n);r.querySelectorAll("[data-stx-component-id]").forEach((o)=>{let s=o.getAttribute("data-stx-component-id");if(s)qs(s)})}})}).observe(document.body,{childList:!0,subtree:!0})}function Nu(){if(typeof document>"u")return;if(document.getElementById("stx-devtools-panel"))return;let e=document.createElement("div");e.id="stx-devtools-panel",e.innerHTML=`
1651
+ `,o.textContent=`<${t.name}>`,r.appendChild(o),document.body.appendChild(r)}}function Zs(){let e=document.getElementById("stx-devtools-highlight");if(e)e.remove()}function Iu(){console.group("%c[STX DevTools] Component Tree","color: #10b981; font-weight: bold;");let e=Array.from(I.components.values()).filter((r)=>!r.parentId);function t(r,n){let o=" ".repeat(n);if(console.log(`${o}%c<${r.name}>%c id=${r.id} renders=${r.renderCount}`,"color: #3b82f6;","color: #6b7280;"),Object.keys(r.props).length>0)console.log(`${o} props:`,r.props);if(Object.keys(r.state).length>0)console.log(`${o} state:`,r.state);for(let s of r.children){let i=I.components.get(s);if(i)t(i,n+1)}}for(let r of e)t(r,0);console.groupEnd()}function Lu(e){console.group("%c[STX DevTools] Store State","color: #8b5cf6; font-weight: bold;");let t=e?[I.stores.get(e)].filter(Boolean):Array.from(I.stores.values());for(let r of t)if(r)console.group(`Store: ${r.id}`),console.log("State:",r.state),console.log("Getters:",r.getters),console.log("Actions:",r.actions),console.log("History:",r.history),console.groupEnd();console.groupEnd()}function Fu(e,t){let r=I.stores.get(t);if(!r)return;if(e<0||e>=r.history.length){console.warn("[STX DevTools] Invalid history index");return}let n={};for(let o=0;o<=e;o++){let s=r.history[o];if(s.type==="state"&&s.name!=="__init__")n[s.name]=s.newValue;else if(s.name==="__init__")Object.assign(n,s.newValue)}if(console.log(`%c[STX DevTools] Time traveled to index ${e}`,"color: #f59e0b;",n),typeof window<"u"&&window.__STX_STORES__){let o=window.__STX_STORES__[t];if(o&&typeof o.$patch==="function")o.$patch(n)}}function Nu(){if(typeof MutationObserver>"u")return;new MutationObserver((e)=>{for(let t of e)t.removedNodes.forEach((r)=>{if(r instanceof HTMLElement){let n=r.getAttribute("data-stx-component-id");if(n)Xs(n);r.querySelectorAll("[data-stx-component-id]").forEach((o)=>{let s=o.getAttribute("data-stx-component-id");if(s)Xs(s)})}})}).observe(document.body,{childList:!0,subtree:!0})}function Bu(){if(typeof document>"u")return;if(document.getElementById("stx-devtools-panel"))return;let e=document.createElement("div");e.id="stx-devtools-panel",e.innerHTML=`
1652
1652
  <style>
1653
1653
  #stx-devtools-panel {
1654
1654
  position: fixed;
@@ -1757,33 +1757,33 @@ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.
1757
1757
  <div id="stx-devtools-content">
1758
1758
  <div id="stx-devtools-components-tab"></div>
1759
1759
  </div>
1760
- `,document.body.appendChild(e);let t=e.querySelector("#stx-devtools-header"),r=e.querySelector("#stx-devtools-toggle");t?.addEventListener("click",()=>{if(e.classList.toggle("open"),r)r.textContent=e.classList.contains("open")?"\u25BC":"\u25B2"});let n=e.querySelectorAll(".stx-devtools-tab");n.forEach((o)=>{o.addEventListener("click",()=>{n.forEach((s)=>s.classList.remove("active")),o.classList.add("active"),Xs(o.getAttribute("data-tab")||"components")})}),setInterval(()=>{let o=e.querySelector(".stx-devtools-tab.active");if(o&&e.classList.contains("open"))Xs(o.getAttribute("data-tab")||"components")},1000)}function Xs(e){let t=document.getElementById("stx-devtools-content");if(!t)return;switch(e){case"components":t.innerHTML=Bu();break;case"stores":t.innerHTML=zu();break;case"events":t.innerHTML=Uu();break}t.querySelectorAll(".stx-devtools-component").forEach((r)=>{r.addEventListener("click",()=>{let n=r.getAttribute("data-id");if(n)io(n)})})}function Bu(){let e=Array.from(O.components.values()).filter((r)=>!r.parentId);function t(r,n){let o=r.children.map((s)=>O.components.get(s)).filter(Boolean).map((s)=>t(s,n+1)).join("");return`
1761
- <div class="stx-devtools-component ${O.selectedComponent===r.id?"selected":""}"
1760
+ `,document.body.appendChild(e);let t=e.querySelector("#stx-devtools-header"),r=e.querySelector("#stx-devtools-toggle");t?.addEventListener("click",()=>{if(e.classList.toggle("open"),r)r.textContent=e.classList.contains("open")?"\u25BC":"\u25B2"});let n=e.querySelectorAll(".stx-devtools-tab");n.forEach((o)=>{o.addEventListener("click",()=>{n.forEach((s)=>s.classList.remove("active")),o.classList.add("active"),Js(o.getAttribute("data-tab")||"components")})}),setInterval(()=>{let o=e.querySelector(".stx-devtools-tab.active");if(o&&e.classList.contains("open"))Js(o.getAttribute("data-tab")||"components")},1000)}function Js(e){let t=document.getElementById("stx-devtools-content");if(!t)return;switch(e){case"components":t.innerHTML=zu();break;case"stores":t.innerHTML=Uu();break;case"events":t.innerHTML=Hu();break}t.querySelectorAll(".stx-devtools-component").forEach((r)=>{r.addEventListener("click",()=>{let n=r.getAttribute("data-id");if(n)ao(n)})})}function zu(){let e=Array.from(I.components.values()).filter((r)=>!r.parentId);function t(r,n){let o=r.children.map((s)=>I.components.get(s)).filter(Boolean).map((s)=>t(s,n+1)).join("");return`
1761
+ <div class="stx-devtools-component ${I.selectedComponent===r.id?"selected":""}"
1762
1762
  data-id="${r.id}"
1763
1763
  style="padding-left: ${n*16+8}px">
1764
1764
  <span class="stx-devtools-component-name">&lt;${r.name}&gt;</span>
1765
1765
  <span class="stx-devtools-component-id">${r.id}</span>
1766
1766
  </div>
1767
1767
  ${o}
1768
- `}if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No components registered</div>';return e.map((r)=>t(r,0)).join("")}function zu(){let e=Array.from(O.stores.values());if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No stores registered</div>';return e.map((t)=>`
1768
+ `}if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No components registered</div>';return e.map((r)=>t(r,0)).join("")}function Uu(){let e=Array.from(I.stores.values());if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No stores registered</div>';return e.map((t)=>`
1769
1769
  <div class="stx-devtools-section">
1770
1770
  <div class="stx-devtools-section-title">${t.id}</div>
1771
1771
  <div class="stx-devtools-json">${JSON.stringify(t.state,null,2)}</div>
1772
1772
  </div>
1773
- `).join("")}function Uu(){let e=O.events.slice(-20).reverse();if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No events recorded</div>';return e.map((t)=>`
1773
+ `).join("")}function Hu(){let e=I.events.slice(-20).reverse();if(e.length===0)return'<div style="color: #6b7280; padding: 8px;">No events recorded</div>';return e.map((t)=>`
1774
1774
  <div style="padding: 4px 0; border-bottom: 1px solid #374151;">
1775
1775
  <span style="color: #60a5fa;">${t.type}</span>
1776
1776
  <span style="color: #6b7280; font-size: 10px; margin-left: 8px;">
1777
1777
  ${new Date(t.timestamp).toLocaleTimeString()}
1778
1778
  </span>
1779
1779
  </div>
1780
- `).join("")}import ao from"fs";import Wt from"path";async function Hu(e){try{let t=(await Bun.file(e).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!t)return[];let r=t[1],n=[],o=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,s;while((s=o.exec(r))!==null){let i=s[1],a=s[2]||s[3]||s[4];if(!a)continue;let c={name:a},l=i.match(/@type\s+\{([^}]+)\}/i);if(l)c.type=l[1].trim();if(i.match(/@required/i))c.required=!0;let d=i.match(/@default\s+(.+?)(?:\s+|$)/i);if(d)c.default=d[1].trim();let u=i.split(`
1781
- `).map((p)=>p.trim().replace(/^\*\s*/,"")).filter((p)=>!p.startsWith("@")&&p.length>0);c.description=u.join(" ").trim(),n.push(c)}if(n.length===0){let i=r.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(i){let a=i[1].split(",").map((c)=>c.trim()).filter(Boolean);for(let c of a){let[l]=c.split(":").map((d)=>d.trim());if(l)n.push({name:l})}}}return n}catch(t){return console.error(`Error extracting props from ${e}:`,t),[]}}async function Wu(e){try{let t=await Bun.file(e).text(),r=t.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||t.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1782
- `).map((n)=>n.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Vu(e,t=!1,r){let n=Wt.basename(e,".stx"),o=await Hu(e),s=await Wu(e),i="";if(t&&r)i=`<${r}></${r}>`;else{let a=o.map((c)=>{if(c.type==="boolean")return`:${c.name}="true"`;return`${c.name}="value"`}).join(`
1780
+ `).join("")}import co from"fs";import Vt from"path";async function Wu(e){try{let t=(await Bun.file(e).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!t)return[];let r=t[1],n=[],o=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,s;while((s=o.exec(r))!==null){let i=s[1],a=s[2]||s[3]||s[4];if(!a)continue;let c={name:a},l=i.match(/@type\s+\{([^}]+)\}/i);if(l)c.type=l[1].trim();if(i.match(/@required/i))c.required=!0;let d=i.match(/@default\s+(.+?)(?:\s+|$)/i);if(d)c.default=d[1].trim();let u=i.split(`
1781
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).filter((p)=>!p.startsWith("@")&&p.length>0);c.description=u.join(" ").trim(),n.push(c)}if(n.length===0){let i=r.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(i){let a=i[1].split(",").map((c)=>c.trim()).filter(Boolean);for(let c of a){let[l]=c.split(":").map((d)=>d.trim());if(l)n.push({name:l})}}}return n}catch(t){return console.error(`Error extracting props from ${e}:`,t),[]}}async function Vu(e){try{let t=await Bun.file(e).text(),r=t.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||t.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1782
+ `).map((n)=>n.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qu(e,t=!1,r){let n=Vt.basename(e,".stx"),o=await Wu(e),s=await Vu(e),i="";if(t&&r)i=`<${r}></${r}>`;else{let a=o.map((c)=>{if(c.type==="boolean")return`:${c.name}="true"`;return`${c.name}="value"`}).join(`
1783
1783
  `);i=`<${n}
1784
1784
  ${a}
1785
- />`}return{name:n,path:e,description:s,props:o,example:i,isWebComponent:t,tag:r}}async function Zs(e){try{if(!await Vt(e))return console.warn(`Components directory does not exist: ${e}`),[];let t=await ao.promises.readdir(e,{withFileTypes:!0}),r=[];for(let n of t){let o=Wt.join(e,n.name);if(n.isDirectory()){let s=await Zs(o);r.push(...s)}else if(n.isFile()&&n.name.endsWith(".stx"))r.push(o)}return r}catch(t){return console.error(`Error finding component files in ${e}:`,t),[]}}async function qu(e,t){try{if(!await Vt(e))return[];let r=await Zs(e),n=[],o=new Map;if(t?.components?.length)for(let s of t.components)o.set(s.file,s);for(let s of r){let i=o.get(s),a=!!i,c=i?.tag,l=await Vu(s,a,c);n.push(l)}return n}catch(r){return console.error("Error generating component docs:",r),[]}}async function Xu(e){try{if(!await Vt(e))return[];let t=await ao.promises.readdir(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.endsWith(".stx"))continue;let o=Wt.join(e,n.name),s=await Bun.file(o).text(),i=Wt.basename(o,".stx"),a=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),c=a?a[1].split(`
1786
- `).map((g)=>g.trim().replace(/^\*\s*/,"")).join(" ").trim():"",l=/@component\(\s*['"]([^'"]+)['"]/g,d=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,u=new Set,p;while((p=l.exec(s))!==null)u.add(p[1]);while((p=d.exec(s))!==null)if(p[1]&&p[1]!=="slot")u.add(p[1]);let h=/@([a-z]+)(?:\s*\(|\s+|$)/g,f=new Set;while((p=h.exec(s))!==null)f.add(p[1]);r.push({name:i,path:o,description:c,components:[...u],directives:[...f]})}return r}catch(t){return console.error("Error generating template docs:",t),[]}}async function Ju(e=[]){try{let t=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1785
+ />`}return{name:n,path:e,description:s,props:o,example:i,isWebComponent:t,tag:r}}async function Qs(e){try{if(!await qt(e))return console.warn(`Components directory does not exist: ${e}`),[];let t=await co.promises.readdir(e,{withFileTypes:!0}),r=[];for(let n of t){let o=Vt.join(e,n.name);if(n.isDirectory()){let s=await Qs(o);r.push(...s)}else if(n.isFile()&&n.name.endsWith(".stx"))r.push(o)}return r}catch(t){return console.error(`Error finding component files in ${e}:`,t),[]}}async function Xu(e,t){try{if(!await qt(e))return[];let r=await Qs(e),n=[],o=new Map;if(t?.components?.length)for(let s of t.components)o.set(s.file,s);for(let s of r){let i=o.get(s),a=!!i,c=i?.tag,l=await qu(s,a,c);n.push(l)}return n}catch(r){return console.error("Error generating component docs:",r),[]}}async function Ju(e){try{if(!await qt(e))return[];let t=await co.promises.readdir(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isFile()||!n.name.endsWith(".stx"))continue;let o=Vt.join(e,n.name),s=await Bun.file(o).text(),i=Vt.basename(o,".stx"),a=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),c=a?a[1].split(`
1786
+ `).map((g)=>g.trim().replace(/^\*\s*/,"")).join(" ").trim():"",l=/@component\(\s*['"]([^'"]+)['"]/g,d=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,u=new Set,p;while((p=l.exec(s))!==null)u.add(p[1]);while((p=d.exec(s))!==null)if(p[1]&&p[1]!=="slot")u.add(p[1]);let h=/@([a-z]+)(?:\s*\(|\s+|$)/g,f=new Set;while((p=h.exec(s))!==null)f.add(p[1]);r.push({name:i,path:o,description:c,components:[...u],directives:[...f]})}return r}catch(t){return console.error("Error generating template docs:",t),[]}}async function Yu(e=[]){try{let t=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1787
1787
  <p>Welcome, {{ user.name }}!</p>
1788
1788
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1789
1789
  <p>Welcome back!</p>
@@ -1803,7 +1803,7 @@ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.
1803
1803
  <p>Page {{ page }}</p>
1804
1804
  @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
1805
1805
  {{ This will be displayed as-is }}
1806
- @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let r of e)t.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return t}catch(t){return console.error("Error generating directive docs:",t),[]}}function Yu(e=[],t=[],r=[],n){let o=`# stx Documentation
1806
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let r of e)t.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return t}catch(t){return console.error("Error generating directive docs:",t),[]}}function Ku(e=[],t=[],r=[],n){let o=`# stx Documentation
1807
1807
 
1808
1808
  `;if(n)o+=`${n}
1809
1809
 
@@ -1845,7 +1845,7 @@ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.
1845
1845
 
1846
1846
  `,o+=`#### Example
1847
1847
 
1848
- `,o+="```html\n",o+=s.example,o+="\n```\n\n"}return o}function Ku(e=[],t=[],r=[],n){let o=`<!DOCTYPE html>
1848
+ `,o+="```html\n",o+=s.example,o+="\n```\n\n"}return o}function Gu(e=[],t=[],r=[],n){let o=`<!DOCTYPE html>
1849
1849
  <html lang="en">
1850
1850
  <head>
1851
1851
  <meta charset="UTF-8">
@@ -1916,15 +1916,15 @@ Press ${m.cyan}h${m.reset} + ${m.cyan}Enter${m.reset} to show shortcuts`),Je(oe.
1916
1916
  <td>@${s.name}</td>
1917
1917
  <td>${s.description||"-"}</td>
1918
1918
  <td>${s.hasEndTag?"Yes":"No"}</td>
1919
- </tr>`;o+="</tbody></table>";for(let s of r)if(s.example)o+=`<h3>@${s.name}</h3>`,o+=`<p>${s.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${s.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function Gu(e=[],t=[],r=[],n){return JSON.stringify({components:e,templates:t,directives:r,extraContent:n||""},null,2)}async function Zu(e){try{let{componentsDir:t,templatesDir:r,webComponentsConfig:n,customDirectives:o,config:s}=e;if(!s.enabled)return!1;let i=s.outputDir||"docs";if(await ao.promises.mkdir(i,{recursive:!0}),console.log("Generating documentation..."),t)console.log(`Components directory: ${t}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${i}`);let a=[];if(s.components!==!1&&t)console.log("Generating component documentation..."),a=await qu(t,n),console.log(`Found ${a.length} components`);let c=[];if(s.templates!==!1&&r)console.log("Generating template documentation..."),c=await Xu(r),console.log(`Found ${c.length} templates`);let l=[];if(s.directives!==!1)console.log("Generating directive documentation..."),l=await Ju(o),console.log(`Found ${l.length} directives`);let d=s.format||"markdown",u=s.extraContent,p="",h="";switch(d){case"markdown":p=Yu(a,c,l,u),h="md";break;case"html":p=Ku(a,c,l,u),h="html";break;case"json":p=Gu(a,c,l,u),h="json";break;default:throw Error(`Unsupported documentation format: ${d}`)}let f=Wt.join(i,`stx-docs.${h}`);return await Bun.write(f,p),console.log(`Documentation generated: ${f}`),!0}catch(t){return console.error("Error generating documentation:",t),!1}}async function vw(e){let t={enabled:!0,outputDir:e.output||"docs",format:e.format||"markdown",components:e.components!==!1,templates:e.templates!==!1,directives:e.directives!==!1,extraContent:e.extraContent},r=e.componentsDir||je.componentsDir,n=e.templatesDir||".";return Zu({componentsDir:r,templatesDir:n,webComponentsConfig:je.webComponents,customDirectives:je.customDirectives,config:t})}import Et from"process";function qt(){if(typeof globalThis<"u"&&"caches"in globalThis&&"CF"in globalThis)return{platform:"cloudflare",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","r2","d1","durable-objects","queues"]};if(typeof globalThis<"u"&&"Deno"in globalThis)return{platform:"deno",version:globalThis.Deno.version?.deno,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","deploy","ffi"]};if(typeof globalThis<"u"&&"Bun"in globalThis)return{platform:"bun",version:globalThis.Bun.version,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["sqlite","ffi","native-modules"]};if(typeof globalThis<"u"&&"EdgeRuntime"in globalThis)return{platform:"vercel",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["edge-config","blob"]};if(typeof globalThis<"u"&&"Netlify"in globalThis)return{platform:"netlify",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!1,capabilities:["blobs","edge-functions"]};if(typeof globalThis<"u"&&"fastly"in globalThis)return{platform:"fastly",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["dictionary","backend","geolocation"]};if(Et.versions?.node)return{platform:"node",version:Et.versions.node,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["fs","child-process","native-modules"]};return{platform:"unknown",supportsStreaming:!1,supportsCrypto:!1,supportsKV:!1,supportsCache:!1,capabilities:[]}}function kw(){let e=qt();return["cloudflare","deno","vercel","netlify","fastly"].includes(e.platform)}function Tw(){return qt().platform!=="unknown"}function Qu(e){return{get(t){if(e&&t in e){let r=e[t];return typeof r==="string"?r:void 0}if(typeof globalThis<"u"&&"Deno"in globalThis)return globalThis.Deno.env.get(t);if(Et.env)return Et.env[t];return},getOrThrow(t){let r=this.get(t);if(r===void 0)throw Error(`Environment variable "${t}" is not set`);return r},has(t){return this.get(t)!==void 0},all(){let t={};if(e){for(let[r,n]of Object.entries(e))if(typeof n==="string")t[r]=n}if(typeof globalThis<"u"&&"Deno"in globalThis){let r=globalThis.Deno.env.toObject();Object.assign(t,r)}if(Et.env){for(let[r,n]of Object.entries(Et.env))if(n!==void 0)t[r]=n}return t}}}function ep(e){let t=qt();if(t.platform==="cloudflare"&&e)return e;if(t.platform==="deno"&&"Deno"in globalThis)return tp();if(t.platform==="node"||t.platform==="bun")return rp();return}function tp(){let e=null,t=async()=>{if(!e)e=await globalThis.Deno.openKv();return e};return{async get(r){return(await(await t()).get(["stx",r])).value},async getWithMetadata(r){let n=await t(),o=await n.get(["stx",r]),s=await n.get(["stx-meta",r]);return{value:o.value,metadata:s.value}},async put(r,n,o){let s=await t(),i=o?.expirationTtl?o.expirationTtl*1000:void 0;if(await s.set(["stx",r],n,i?{expireIn:i}:void 0),o?.metadata)await s.set(["stx-meta",r],o.metadata,i?{expireIn:i}:void 0)},async delete(r){let n=await t();await n.delete(["stx",r]),await n.delete(["stx-meta",r])},async list(r){let n=await t(),o=r?.prefix?["stx",r.prefix]:["stx"],s=n.list({prefix:o,limit:r?.limit||100}),i=[];for await(let a of s){let c=a.key.slice(1).join("/");if(!c.startsWith("stx-meta/"))i.push({name:c})}return{keys:i,list_complete:!0}}}}function rp(){let e=new Map,t=()=>{let r=Date.now();for(let[n,o]of e.entries())if(o.expiration&&o.expiration<r)e.delete(n)};return{async get(r){t();let n=e.get(r);if(!n)return null;if(n.expiration&&n.expiration<Date.now())return e.delete(r),null;return n.value},async getWithMetadata(r){t();let n=e.get(r);if(!n)return{value:null,metadata:null};if(n.expiration&&n.expiration<Date.now())return e.delete(r),{value:null,metadata:null};return{value:n.value,metadata:n.metadata||null}},async put(r,n,o){let s=o?.expiration?o.expiration*1000:o?.expirationTtl?Date.now()+o.expirationTtl*1000:void 0;e.set(r,{value:n,metadata:o?.metadata,expiration:s})},async delete(r){e.delete(r)},async list(r){t();let n=[];for(let[o,s]of e.entries()){if(r?.prefix&&!o.startsWith(r.prefix))continue;if(n.push({name:o,expiration:s.expiration,metadata:s.metadata}),r?.limit&&n.length>=r.limit)break}return{keys:n,list_complete:!0}}}}function np(){let e=qt();if(e.platform==="cloudflare"&&"caches"in globalThis)return op();if(e.supportsStreaming)return sp();return}function op(){return{async match(e){return(await caches.default).match(e)},async put(e,t){await(await caches.default).put(e,t.clone())},async delete(e){return(await caches.default).delete(e)}}}function sp(){let e=new Map;return{async match(r){let n=r.url,o=e.get(n);if(!o)return;if(Date.now()>o.expiration){e.delete(n);return}return o.response.clone()},async put(r,n){let o=r.url,s=n.headers.get("Cache-Control"),i=60000;if(s){let a=s.match(/max-age=(\d+)/);if(a)i=Number.parseInt(a[1],10)*1000}e.set(o,{response:n.clone(),expiration:Date.now()+i})},async delete(r){return e.delete(r.url)}}}function ip(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function ap(e,t){if(t.platform==="cloudflare"){let r=e.cf;if(r)return{city:r.city,country:r.country,countryCode:r.country,region:r.region,latitude:r.latitude?Number.parseFloat(r.latitude):void 0,longitude:r.longitude?Number.parseFloat(r.longitude):void 0,timezone:r.timezone}}if(t.platform==="vercel"){let r={},n=e.headers.get("x-vercel-ip-city"),o=e.headers.get("x-vercel-ip-country"),s=e.headers.get("x-vercel-ip-country-region"),i=e.headers.get("x-vercel-ip-latitude"),a=e.headers.get("x-vercel-ip-longitude");if(n)r.city=decodeURIComponent(n);if(o)r.countryCode=o;if(s)r.region=s;if(i)r.latitude=Number.parseFloat(i);if(a)r.longitude=Number.parseFloat(a);return Object.keys(r).length>0?r:void 0}if(t.platform==="netlify"){let r={},n=e.headers.get("x-nf-geo-city"),o=e.headers.get("x-nf-geo-country");if(n)r.city=n;if(o)r.countryCode=o;return Object.keys(r).length>0?r:void 0}return}function co(e,t,r){let n=new Headers(e.headers);if(t.origins==="*")n.set("Access-Control-Allow-Origin","*");else if(t.origins&&r&&t.origins.includes(r))n.set("Access-Control-Allow-Origin",r),n.set("Vary","Origin");if(t.methods)n.set("Access-Control-Allow-Methods",t.methods.join(", "));if(t.headers)n.set("Access-Control-Allow-Headers",t.headers.join(", "));if(t.exposeHeaders)n.set("Access-Control-Expose-Headers",t.exposeHeaders.join(", "));if(t.credentials)n.set("Access-Control-Allow-Credentials","true");if(t.maxAge)n.set("Access-Control-Max-Age",String(t.maxAge));return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Vr(e){let t=qt();return async(r,n)=>{let o=performance.now(),s=ip(),i={runtime:t,platform:n||{},requestId:s,geo:ap(r,t),timing:{start:o,getElapsed:()=>performance.now()-o},kv:ep(n?.KV),cache:np(),env:Qu(n?.env)};try{if(r.method==="OPTIONS"&&e.cors){let c=new Response(null,{status:204});return c=co(c,e.cors,r.headers.get("Origin")||void 0),c}if(e.cache?.enabled&&r.method==="GET"&&i.cache){if(Qs(r,e.cache)){let c=await i.cache.match(r);if(c){let l=new Response(c.body,c);return l.headers.set("X-Cache","HIT"),l.headers.set("X-Request-Id",s),e.cors?co(l,e.cors,r.headers.get("Origin")||void 0):l}}}let a;if(e.middleware&&e.middleware.length>0)a=await cp(r,i,e.middleware,async()=>{let c=await e.render(r,i);return typeof c==="string"?new Response(c,{headers:{"Content-Type":"text/html; charset=utf-8"}}):c});else{let c=await e.render(r,i);a=typeof c==="string"?new Response(c,{headers:{"Content-Type":"text/html; charset=utf-8"}}):c}if(a.headers.set("X-Request-Id",s),a.headers.set("X-Response-Time",`${i.timing.getElapsed().toFixed(2)}ms`),e.cache?.enabled&&r.method==="GET"&&i.cache){if(Qs(r,e.cache)&&a.status===200){let c=e.cache.ttl||60,l=a.clone();l.headers.set("Cache-Control",`public, max-age=${c}`),await i.cache.put(r,l),a.headers.set("X-Cache","MISS")}}if(e.cors)a=co(a,e.cors,r.headers.get("Origin")||void 0);return a}catch(a){let c=a instanceof Error?a:Error(String(a));if(e.onError)return e.onError(c,r);return new Response(`Internal Server Error: ${c.message}`,{status:500,headers:{"Content-Type":"text/plain","X-Request-Id":s}})}}}function Qs(e,t){let r=new URL(e.url).pathname;if(t.excludePaths){for(let n of t.excludePaths)if(n.test(r))return!1}if(t.includePaths){for(let n of t.includePaths)if(n.test(r))return!0;return!1}return!0}async function cp(e,t,r,n){let o=0,s=async()=>{if(o>=r.length)return n();let i=r[o];return o++,i(e,t,s)};return s()}function Cw(e,t){let r=new Headers(t?.headers);return r.set("Content-Type","text/html; charset=utf-8"),r.set("Transfer-Encoding","chunked"),new Response(e,{...t,headers:r})}function Ew(){let e=new TextEncoder;return new TransformStream({transform(t,r){r.enqueue(e.encode(t))}})}function _w(e){let t=new TextEncoder;return new ReadableStream({async start(r){for await(let n of e)r.enqueue(t.encode(n));r.close()}})}function Aw(e){let t=Vr(e);return{async fetch(r,n,o){return t(r,{env:n,ctx:o,KV:n.KV})}}}function jw(e){let t=Vr(e);return(r)=>t(r,{})}function Rw(e){let t=Vr(e);return(r)=>t(r,{})}function Mw(e){let t=Vr(e);return(r,n)=>{return t(r,{netlifyContext:n})}}function Dw(e){let t=e.headers.get("Cookie");if(!t)return{};let r={};for(let n of t.split(";")){let[o,s]=n.split("=").map((i)=>i.trim());if(o&&s)r[o]=decodeURIComponent(s)}return r}function Pw(e,t,r){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r?.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r?.expires)n+=`; Expires=${r.expires.toUTCString()}`;if(r?.path)n+=`; Path=${r.path}`;if(r?.domain)n+=`; Domain=${r.domain}`;if(r?.secure)n+="; Secure";if(r?.httpOnly)n+="; HttpOnly";if(r?.sameSite)n+=`; SameSite=${r.sameSite}`;return n}function Ow(e,t){let r=new Headers(t?.headers);return r.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),{...t,headers:r})}function Iw(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}function Lw(e="Not Found"){return new Response(e,{status:404,headers:{"Content-Type":"text/plain"}})}var{WebView:lp}=globalThis.Bun;import{existsSync as ri,mkdirSync as ni,readdirSync as dp,statSync as oi}from"fs";import _t from"path";var lo=16384;function up(e){if(/^https?:\/\//.test(e)||e.startsWith("file://"))return e;return`file://${_t.resolve(e)}`}function ei(e,t,r,n){return new Promise((o)=>{let s=!1,i,a,c=()=>{if(!s){if(s=!0,clearTimeout(a),i)clearTimeout(i);e.onNavigated=void 0,o()}};a=setTimeout(c,n),e.onNavigated=()=>{if(!s)i=setTimeout(c,r)};try{let l=e.navigate(t);if(l&&typeof l.catch==="function")l.catch(c)}catch{c()}})}async function ti(e,t,r){let n=`!!document.querySelector(${JSON.stringify(t)})`,o=Date.now()+r;while(Date.now()<o){try{if(await e.evaluate(n))return}catch{}await new Promise((s)=>setTimeout(s,100))}}async function pp(e){try{let t=await e.evaluate("Math.ceil(Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0))");return typeof t==="number"&&Number.isFinite(t)&&t>0?Math.min(t,lo):0}catch{return 0}}async function fp(e,t,r={}){let n=Math.min(r.width??1440,lo),o=Math.min(r.height??2200,lo),s=r.waitMs??800,i=r.timeoutMs??15000,a=r.format??"png",c=up(e),l=(u)=>new lp({width:n,height:u,headless:!0,...r.backend?{backend:r.backend}:{}}),d=l(o);try{if(await ei(d,c,s,i),r.waitSelector)await ti(d,r.waitSelector,i);if(r.fullPage){let p=await pp(d);if(p>o){if(d.close(),d=l(p),await ei(d,c,s,i),r.waitSelector)await ti(d,r.waitSelector,i)}}let u=await d.screenshot({encoding:"buffer",format:a});ni(_t.dirname(_t.resolve(t)),{recursive:!0}),await Bun.write(t,u)}finally{d.close()}if(!ri(t))throw Error(`Screenshot was not produced for ${e}`);return{input:e,output:t,bytes:oi(t).size}}async function Uw(e,t,r={}){ni(t,{recursive:!0});let n;if(!/^https?:\/\//.test(e)&&ri(e)&&oi(e).isDirectory())n=dp(e).filter((i)=>i.endsWith(".html")).map((i)=>_t.join(e,i));else n=[e];let o=r.format??"png",s=[];for(let i of n){let a=/^https?:\/\//.test(i)?new URL(i).pathname.replace(/\W+/g,"-").replace(/^-|-$/g,"")||"index":_t.basename(i).replace(/\.html?$/,"");s.push(await fp(i,_t.join(t,`${a}.${o}`),r))}return s}var ii={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function mp(e,t={}){let r={...ii,...t};if(e.trim()==="")return`
1920
- `;let n=e;if(r.trimTrailingWhitespace)n=n.replace(/[ \t]+$/gm,"");if(n=gp(n,r),n=wp(n,r),n=yp(n,r),r.trimTrailingWhitespace)n=n.replace(/[ \t]+$/gm,""),n=n.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(n=n.replace(/\r\n/g,`
1919
+ </tr>`;o+="</tbody></table>";for(let s of r)if(s.example)o+=`<h3>@${s.name}</h3>`,o+=`<p>${s.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${s.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return o+="</body></html>",o}function Zu(e=[],t=[],r=[],n){return JSON.stringify({components:e,templates:t,directives:r,extraContent:n||""},null,2)}async function Qu(e){try{let{componentsDir:t,templatesDir:r,webComponentsConfig:n,customDirectives:o,config:s}=e;if(!s.enabled)return!1;let i=s.outputDir||"docs";if(await co.promises.mkdir(i,{recursive:!0}),console.log("Generating documentation..."),t)console.log(`Components directory: ${t}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${i}`);let a=[];if(s.components!==!1&&t)console.log("Generating component documentation..."),a=await Xu(t,n),console.log(`Found ${a.length} components`);let c=[];if(s.templates!==!1&&r)console.log("Generating template documentation..."),c=await Ju(r),console.log(`Found ${c.length} templates`);let l=[];if(s.directives!==!1)console.log("Generating directive documentation..."),l=await Yu(o),console.log(`Found ${l.length} directives`);let d=s.format||"markdown",u=s.extraContent,p="",h="";switch(d){case"markdown":p=Ku(a,c,l,u),h="md";break;case"html":p=Gu(a,c,l,u),h="html";break;case"json":p=Zu(a,c,l,u),h="json";break;default:throw Error(`Unsupported documentation format: ${d}`)}let f=Vt.join(i,`stx-docs.${h}`);return await Bun.write(f,p),console.log(`Documentation generated: ${f}`),!0}catch(t){return console.error("Error generating documentation:",t),!1}}async function $w(e){let t={enabled:!0,outputDir:e.output||"docs",format:e.format||"markdown",components:e.components!==!1,templates:e.templates!==!1,directives:e.directives!==!1,extraContent:e.extraContent},r=e.componentsDir||Re.componentsDir,n=e.templatesDir||".";return Qu({componentsDir:r,templatesDir:n,webComponentsConfig:Re.webComponents,customDirectives:Re.customDirectives,config:t})}import _t from"process";function Xt(){if(typeof globalThis<"u"&&"caches"in globalThis&&"CF"in globalThis)return{platform:"cloudflare",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","r2","d1","durable-objects","queues"]};if(typeof globalThis<"u"&&"Deno"in globalThis)return{platform:"deno",version:globalThis.Deno.version?.deno,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["kv","deploy","ffi"]};if(typeof globalThis<"u"&&"Bun"in globalThis)return{platform:"bun",version:globalThis.Bun.version,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["sqlite","ffi","native-modules"]};if(typeof globalThis<"u"&&"EdgeRuntime"in globalThis)return{platform:"vercel",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["edge-config","blob"]};if(typeof globalThis<"u"&&"Netlify"in globalThis)return{platform:"netlify",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!1,capabilities:["blobs","edge-functions"]};if(typeof globalThis<"u"&&"fastly"in globalThis)return{platform:"fastly",supportsStreaming:!0,supportsCrypto:!0,supportsKV:!0,supportsCache:!0,capabilities:["dictionary","backend","geolocation"]};if(_t.versions?.node)return{platform:"node",version:_t.versions.node,supportsStreaming:!0,supportsCrypto:!0,supportsKV:!1,supportsCache:!1,capabilities:["fs","child-process","native-modules"]};return{platform:"unknown",supportsStreaming:!1,supportsCrypto:!1,supportsKV:!1,supportsCache:!1,capabilities:[]}}function Tw(){let e=Xt();return["cloudflare","deno","vercel","netlify","fastly"].includes(e.platform)}function Cw(){return Xt().platform!=="unknown"}function ep(e){return{get(t){if(e&&t in e){let r=e[t];return typeof r==="string"?r:void 0}if(typeof globalThis<"u"&&"Deno"in globalThis)return globalThis.Deno.env.get(t);if(_t.env)return _t.env[t];return},getOrThrow(t){let r=this.get(t);if(r===void 0)throw Error(`Environment variable "${t}" is not set`);return r},has(t){return this.get(t)!==void 0},all(){let t={};if(e){for(let[r,n]of Object.entries(e))if(typeof n==="string")t[r]=n}if(typeof globalThis<"u"&&"Deno"in globalThis){let r=globalThis.Deno.env.toObject();Object.assign(t,r)}if(_t.env){for(let[r,n]of Object.entries(_t.env))if(n!==void 0)t[r]=n}return t}}}function tp(e){let t=Xt();if(t.platform==="cloudflare"&&e)return e;if(t.platform==="deno"&&"Deno"in globalThis)return rp();if(t.platform==="node"||t.platform==="bun")return np();return}function rp(){let e=null,t=async()=>{if(!e)e=await globalThis.Deno.openKv();return e};return{async get(r){return(await(await t()).get(["stx",r])).value},async getWithMetadata(r){let n=await t(),o=await n.get(["stx",r]),s=await n.get(["stx-meta",r]);return{value:o.value,metadata:s.value}},async put(r,n,o){let s=await t(),i=o?.expirationTtl?o.expirationTtl*1000:void 0;if(await s.set(["stx",r],n,i?{expireIn:i}:void 0),o?.metadata)await s.set(["stx-meta",r],o.metadata,i?{expireIn:i}:void 0)},async delete(r){let n=await t();await n.delete(["stx",r]),await n.delete(["stx-meta",r])},async list(r){let n=await t(),o=r?.prefix?["stx",r.prefix]:["stx"],s=n.list({prefix:o,limit:r?.limit||100}),i=[];for await(let a of s){let c=a.key.slice(1).join("/");if(!c.startsWith("stx-meta/"))i.push({name:c})}return{keys:i,list_complete:!0}}}}function np(){let e=new Map,t=()=>{let r=Date.now();for(let[n,o]of e.entries())if(o.expiration&&o.expiration<r)e.delete(n)};return{async get(r){t();let n=e.get(r);if(!n)return null;if(n.expiration&&n.expiration<Date.now())return e.delete(r),null;return n.value},async getWithMetadata(r){t();let n=e.get(r);if(!n)return{value:null,metadata:null};if(n.expiration&&n.expiration<Date.now())return e.delete(r),{value:null,metadata:null};return{value:n.value,metadata:n.metadata||null}},async put(r,n,o){let s=o?.expiration?o.expiration*1000:o?.expirationTtl?Date.now()+o.expirationTtl*1000:void 0;e.set(r,{value:n,metadata:o?.metadata,expiration:s})},async delete(r){e.delete(r)},async list(r){t();let n=[];for(let[o,s]of e.entries()){if(r?.prefix&&!o.startsWith(r.prefix))continue;if(n.push({name:o,expiration:s.expiration,metadata:s.metadata}),r?.limit&&n.length>=r.limit)break}return{keys:n,list_complete:!0}}}}function op(){let e=Xt();if(e.platform==="cloudflare"&&"caches"in globalThis)return sp();if(e.supportsStreaming)return ip();return}function sp(){return{async match(e){return(await caches.default).match(e)},async put(e,t){await(await caches.default).put(e,t.clone())},async delete(e){return(await caches.default).delete(e)}}}function ip(){let e=new Map;return{async match(r){let n=r.url,o=e.get(n);if(!o)return;if(Date.now()>o.expiration){e.delete(n);return}return o.response.clone()},async put(r,n){let o=r.url,s=n.headers.get("Cache-Control"),i=60000;if(s){let a=s.match(/max-age=(\d+)/);if(a)i=Number.parseInt(a[1],10)*1000}e.set(o,{response:n.clone(),expiration:Date.now()+i})},async delete(r){return e.delete(r.url)}}}function ap(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function cp(e,t){if(t.platform==="cloudflare"){let r=e.cf;if(r)return{city:r.city,country:r.country,countryCode:r.country,region:r.region,latitude:r.latitude?Number.parseFloat(r.latitude):void 0,longitude:r.longitude?Number.parseFloat(r.longitude):void 0,timezone:r.timezone}}if(t.platform==="vercel"){let r={},n=e.headers.get("x-vercel-ip-city"),o=e.headers.get("x-vercel-ip-country"),s=e.headers.get("x-vercel-ip-country-region"),i=e.headers.get("x-vercel-ip-latitude"),a=e.headers.get("x-vercel-ip-longitude");if(n)r.city=decodeURIComponent(n);if(o)r.countryCode=o;if(s)r.region=s;if(i)r.latitude=Number.parseFloat(i);if(a)r.longitude=Number.parseFloat(a);return Object.keys(r).length>0?r:void 0}if(t.platform==="netlify"){let r={},n=e.headers.get("x-nf-geo-city"),o=e.headers.get("x-nf-geo-country");if(n)r.city=n;if(o)r.countryCode=o;return Object.keys(r).length>0?r:void 0}return}function lo(e,t,r){let n=new Headers(e.headers);if(t.origins==="*")n.set("Access-Control-Allow-Origin","*");else if(t.origins&&r&&t.origins.includes(r))n.set("Access-Control-Allow-Origin",r),n.set("Vary","Origin");if(t.methods)n.set("Access-Control-Allow-Methods",t.methods.join(", "));if(t.headers)n.set("Access-Control-Allow-Headers",t.headers.join(", "));if(t.exposeHeaders)n.set("Access-Control-Expose-Headers",t.exposeHeaders.join(", "));if(t.credentials)n.set("Access-Control-Allow-Credentials","true");if(t.maxAge)n.set("Access-Control-Max-Age",String(t.maxAge));return new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function qr(e){let t=Xt();return async(r,n)=>{let o=performance.now(),s=ap(),i={runtime:t,platform:n||{},requestId:s,geo:cp(r,t),timing:{start:o,getElapsed:()=>performance.now()-o},kv:tp(n?.KV),cache:op(),env:ep(n?.env)};try{if(r.method==="OPTIONS"&&e.cors){let c=new Response(null,{status:204});return c=lo(c,e.cors,r.headers.get("Origin")||void 0),c}if(e.cache?.enabled&&r.method==="GET"&&i.cache){if(ei(r,e.cache)){let c=await i.cache.match(r);if(c){let l=new Response(c.body,c);return l.headers.set("X-Cache","HIT"),l.headers.set("X-Request-Id",s),e.cors?lo(l,e.cors,r.headers.get("Origin")||void 0):l}}}let a;if(e.middleware&&e.middleware.length>0)a=await lp(r,i,e.middleware,async()=>{let c=await e.render(r,i);return typeof c==="string"?new Response(c,{headers:{"Content-Type":"text/html; charset=utf-8"}}):c});else{let c=await e.render(r,i);a=typeof c==="string"?new Response(c,{headers:{"Content-Type":"text/html; charset=utf-8"}}):c}if(a.headers.set("X-Request-Id",s),a.headers.set("X-Response-Time",`${i.timing.getElapsed().toFixed(2)}ms`),e.cache?.enabled&&r.method==="GET"&&i.cache){if(ei(r,e.cache)&&a.status===200){let c=e.cache.ttl||60,l=a.clone();l.headers.set("Cache-Control",`public, max-age=${c}`),await i.cache.put(r,l),a.headers.set("X-Cache","MISS")}}if(e.cors)a=lo(a,e.cors,r.headers.get("Origin")||void 0);return a}catch(a){let c=a instanceof Error?a:Error(String(a));if(e.onError)return e.onError(c,r);return new Response(`Internal Server Error: ${c.message}`,{status:500,headers:{"Content-Type":"text/plain","X-Request-Id":s}})}}}function ei(e,t){let r=new URL(e.url).pathname;if(t.excludePaths){for(let n of t.excludePaths)if(n.test(r))return!1}if(t.includePaths){for(let n of t.includePaths)if(n.test(r))return!0;return!1}return!0}async function lp(e,t,r,n){let o=0,s=async()=>{if(o>=r.length)return n();let i=r[o];return o++,i(e,t,s)};return s()}function Ew(e,t){let r=new Headers(t?.headers);return r.set("Content-Type","text/html; charset=utf-8"),r.set("Transfer-Encoding","chunked"),new Response(e,{...t,headers:r})}function _w(){let e=new TextEncoder;return new TransformStream({transform(t,r){r.enqueue(e.encode(t))}})}function Aw(e){let t=new TextEncoder;return new ReadableStream({async start(r){for await(let n of e)r.enqueue(t.encode(n));r.close()}})}function jw(e){let t=qr(e);return{async fetch(r,n,o){return t(r,{env:n,ctx:o,KV:n.KV})}}}function Rw(e){let t=qr(e);return(r)=>t(r,{})}function Mw(e){let t=qr(e);return(r)=>t(r,{})}function Dw(e){let t=qr(e);return(r,n)=>t(r,{netlifyContext:n})}function Pw(e){let t=e.headers.get("Cookie");if(!t)return{};let r={};for(let n of t.split(";")){let[o,s]=n.split("=").map((i)=>i.trim());if(o&&s)r[o]=decodeURIComponent(s)}return r}function Ow(e,t,r){let n=`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(r?.maxAge!==void 0)n+=`; Max-Age=${r.maxAge}`;if(r?.expires)n+=`; Expires=${r.expires.toUTCString()}`;if(r?.path)n+=`; Path=${r.path}`;if(r?.domain)n+=`; Domain=${r.domain}`;if(r?.secure)n+="; Secure";if(r?.httpOnly)n+="; HttpOnly";if(r?.sameSite)n+=`; SameSite=${r.sameSite}`;return n}function Iw(e,t){let r=new Headers(t?.headers);return r.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),{...t,headers:r})}function Lw(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}function Fw(e="Not Found"){return new Response(e,{status:404,headers:{"Content-Type":"text/plain"}})}var{WebView:dp}=globalThis.Bun;import{existsSync as ni,mkdirSync as oi,readdirSync as up,statSync as si}from"fs";import At from"path";var uo=16384;function pp(e){if(/^https?:\/\//.test(e)||e.startsWith("file://"))return e;return`file://${At.resolve(e)}`}function ti(e,t,r,n){return new Promise((o)=>{let s=!1,i,a,c=()=>{if(!s){if(s=!0,clearTimeout(a),i)clearTimeout(i);e.onNavigated=void 0,o()}};a=setTimeout(c,n),e.onNavigated=()=>{if(!s)i=setTimeout(c,r)};try{let l=e.navigate(t);if(l&&typeof l.catch==="function")l.catch(c)}catch{c()}})}async function ri(e,t,r){let n=`!!document.querySelector(${JSON.stringify(t)})`,o=Date.now()+r;while(Date.now()<o){try{if(await e.evaluate(n))return}catch{}await new Promise((s)=>setTimeout(s,100))}}async function fp(e){try{let t=await e.evaluate("Math.ceil(Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight, document.body ? document.body.scrollHeight : 0, document.body ? document.body.offsetHeight : 0))");return typeof t==="number"&&Number.isFinite(t)&&t>0?Math.min(t,uo):0}catch{return 0}}async function mp(e,t,r={}){let n=Math.min(r.width??1440,uo),o=Math.min(r.height??2200,uo),s=r.waitMs??800,i=r.timeoutMs??15000,a=r.format??"png",c=pp(e),l=(u)=>new dp({width:n,height:u,headless:!0,...r.backend?{backend:r.backend}:{}}),d=l(o);try{if(await ti(d,c,s,i),r.waitSelector)await ri(d,r.waitSelector,i);if(r.fullPage){let p=await fp(d);if(p>o){if(d.close(),d=l(p),await ti(d,c,s,i),r.waitSelector)await ri(d,r.waitSelector,i)}}let u=await d.screenshot({encoding:"buffer",format:a});oi(At.dirname(At.resolve(t)),{recursive:!0}),await Bun.write(t,u)}finally{d.close()}if(!ni(t))throw Error(`Screenshot was not produced for ${e}`);return{input:e,output:t,bytes:si(t).size}}async function Hw(e,t,r={}){oi(t,{recursive:!0});let n;if(!/^https?:\/\//.test(e)&&ni(e)&&si(e).isDirectory())n=up(e).filter((i)=>i.endsWith(".html")).map((i)=>At.join(e,i));else n=[e];let o=r.format??"png",s=[];for(let i of n){let a=/^https?:\/\//.test(i)?new URL(i).pathname.replace(/\W+/g,"-").replace(/^-|-$/g,"")||"index":At.basename(i).replace(/\.html?$/,"");s.push(await mp(i,At.join(t,`${a}.${o}`),r))}return s}var ai={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function hp(e,t={}){let r={...ai,...t};if(e.trim()==="")return`
1920
+ `;let n=e;if(r.trimTrailingWhitespace)n=n.replace(/[ \t]+$/gm,"");if(n=yp(n,r),n=vp(n,r),n=xp(n,r),r.trimTrailingWhitespace)n=n.replace(/[ \t]+$/gm,""),n=n.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(n=n.replace(/\r\n/g,`
1921
1921
  `).replace(/\r/g,`
1922
1922
  `),!n.endsWith(`
1923
1923
  `))n+=`
1924
- `;return n}function Ww(e,t={}){let r={...ii,...t};if(e.trim()==="")return`
1924
+ `;return n}function Vw(e,t={}){let r={...ai,...t};if(e.trim()==="")return`
1925
1925
  `;let n=e;if(n=n.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(o,s,i,a,c)=>{let l=a.split(`
1926
1926
  `),d=l.filter((f)=>f.trim().length>0);if(d.length===0)return o;let u=Math.min(...d.map((f)=>{let g=f.match(/^( *)/);return g?g[1].length:0})),p=l.map((f)=>{if(f.trim().length===0)return"";return f.substring(u)}).join(`
1927
- `),h=mp(p,r).trimEnd().split(`
1927
+ `),h=hp(p,r).trimEnd().split(`
1928
1928
  `).map((f)=>{if(f.trim().length===0)return"";return s+f}).join(`
1929
1929
  `);return`${s}\`\`\`${i}
1930
1930
  ${h}
@@ -1932,7 +1932,7 @@ ${s}\`\`\``}),r.trimTrailingWhitespace)n=n.replace(/[ \t]+$/gm,"");if(n=n.replac
1932
1932
  `).replace(/\r/g,`
1933
1933
  `),!n.endsWith(`
1934
1934
  `))n+=`
1935
- `;return n}function hp(e){let t=e,r=[],n="__PROTECTED_BLOCK_";return t=t.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(o)=>{let s=r.length;return r.push(o),`${n}${s}__`}),t=t.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1935
+ `;return n}function gp(e){let t=e,r=[],n="__PROTECTED_BLOCK_";return t=t.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(o)=>{let s=r.length;return r.push(o),`${n}${s}__`}),t=t.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1936
1936
  $1
1937
1937
  `),t=t.replace(/(@end\w+)/g,`
1938
1938
  $1
@@ -1943,13 +1943,13 @@ $1
1943
1943
  `),t=t.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(o,s,i,a)=>{let c=a.substring(i+o.length,Math.min(a.length,i+o.length+20)),l=o.match(/<(\w+)/)?.[1];if(l&&c.match(new RegExp(`^</${l}>`)))return o;return`
1944
1944
  ${o}`}),t=t.replace(/(>)(<\/)/g,(o,s,i,a,c)=>{let l=c.substring(Math.max(0,a-50),a),d=c.substring(a+o.length,Math.min(c.length,a+o.length+20)).match(/^(\w+)>/)?.[1],u=l.match(/<(\w+)[^>]*$/)?.[1];if(u&&d&&u===d)return o;return`${s}
1945
1945
  ${i}`}),t=t.replace(/(<\/[^>]+>)(?=<|$)/g,(o,s,i,a)=>{let c=a.substring(Math.max(0,i-20),i),l=o.match(/<\/(\w+)>/)?.[1],d=new RegExp(`<${l}[^>]*>$`);if(l&&c.match(d))return o;return`${o}
1946
- `}),t=t.replace(new RegExp(`${n}(\\d+)__`,"g"),(o,s)=>{return r[Number.parseInt(s,10)]}),t=t.replace(/\n{2,}/g,`
1946
+ `}),t=t.replace(new RegExp(`${n}(\\d+)__`,"g"),(o,s)=>r[Number.parseInt(s,10)]),t=t.replace(/\n{2,}/g,`
1947
1947
  `),t=t.split(`
1948
1948
  `).map((o)=>o.trim()).join(`
1949
- `),t=t.replace(/^\n+/,"").replace(/\n+$/,""),t}function gp(e,t){let r=hp(e).split(`
1950
- `),n=[],o=0,s=!1,i=t.useTabs?"\t":" ".repeat(t.indentSize);for(let a=0;a<r.length;a++){let c=r[a],l=c.trim();if(l===""){n.push("");continue}let d=l.match(/<script\b/i),u=l.match(/<\/script>/i);if(s&&!u){n.push(c);continue}let p=l===">";if(si(l)&&!l.startsWith("<")&&!l.startsWith("@")){n.push(i.repeat(o)+l);continue}let h=l.startsWith("@end"),f=l.startsWith("@else")||l.startsWith("@elseif"),g=l.startsWith("@")&&bp(l),x=l.startsWith("<!DOCTYPE")||l.startsWith("<!doctype"),y=l.startsWith("<!--"),b=l.startsWith("</"),w=l.startsWith("<")&&!b&&!y&&!x,v=l.includes("/>")||xp(l),S=si(l);if(b||h)o=Math.max(0,o-1);let T=f?Math.max(0,o-1):o;if(p)n.push(c);else n.push(i.repeat(T)+l);if(w&&!v&&!S&&!p||g)o++;if(d)s=!0;if(u)s=!1}return n.join(`
1951
- `)}function yp(e,t){if(e=e.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,n,o)=>{let s=o.trim().replace(/\s+/g," ");return`@${n}(${s})`}),e=e.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,n,o)=>{if(o.trim()==="")return`@${n}`;return`@${n}(${o.trim()})`}),t.normalizeWhitespace)e=e.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,n)=>{return`{{ ${n.trim()} }}`}),e=e.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,n)=>{return`{!! ${n.trim()} !!}`});return e}function xp(e){let t=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(e.includes("/>"))return!0;let r=e.match(/<(\w+)/);if(r){let n=r[1];return t.includes(n.toLowerCase())}return!1}function si(e){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(e)}function bp(e){let t=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of t)if(e.startsWith(`@${r}`))return!e.includes(`@end${r}`);return!1}function wp(e,t){if(!t.sortAttributes)return e;return e.replace(/<(\w+)([^>]*)>/g,(r,n,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
1952
- `)||o.includes("@"))return r;let s=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,i=[],a;while((a=s.exec(o))!==null)i.push({name:a[1],value:a[2]});i.sort((l,d)=>{if(l.name==="id")return-1;if(d.name==="id")return 1;if(l.name==="class")return-1;if(d.name==="class")return 1;return l.name.localeCompare(d.name)});let c=i.map((l)=>l.value?`${l.name}=${l.value}`:l.name).join(" ");return`<${n}${c?` ${c}`:""}>`})}import ai from"fs";import uo from"path";var Jw={basic:{description:"Simple page with script, style, and template sections"},component:{description:"Reusable component with props and slots"},layout:{description:"Layout template with sections and yields"},blog:{description:"Blog post with frontmatter-style variables"},api:{description:"API endpoint template with JSON response"},app:{description:"Full app with stores and components"}};async function Yw(e="index.stx",t={}){try{let r=t.force||!1,n=uo.resolve(process.cwd(),e);if(await Bun.file(n).exists()){if(!r)throw Error(`File ${e} already exists. Use --force to overwrite.`);console.warn(`File ${e} already exists. Overwriting...`)}let o=uo.dirname(n);if(!ai.existsSync(o))ai.mkdirSync(o,{recursive:!0});let s;if(t.template){let i=uo.resolve(process.cwd(),t.template);if(!await Bun.file(i).exists())throw Error(`Template file ${t.template} does not exist.`);if(!i.endsWith(".stx"))console.warn(`Warning: Template file ${t.template} does not have a .stx extension. Using it anyway.`);s=await Bun.file(i).text(),console.warn(`Using template from ${t.template}`)}else if(t.preset)s=ci(t.preset),console.warn(`Using '${t.preset}' preset template`);else s=ci("basic");return await Bun.write(n,s),console.warn(`Created new stx file: ${e}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function ci(e){switch(e){case"basic":return li();case"component":return vp();case"layout":return $p();case"blog":return Sp();case"api":return kp();case"app":return Tp();default:return li()}}function li(){return`<script>
1949
+ `),t=t.replace(/^\n+/,"").replace(/\n+$/,""),t}function yp(e,t){let r=gp(e).split(`
1950
+ `),n=[],o=0,s=!1,i=t.useTabs?"\t":" ".repeat(t.indentSize);for(let a=0;a<r.length;a++){let c=r[a],l=c.trim();if(l===""){n.push("");continue}let d=l.match(/<script\b/i),u=l.match(/<\/script>/i);if(s&&!u){n.push(c);continue}let p=l===">";if(ii(l)&&!l.startsWith("<")&&!l.startsWith("@")){n.push(i.repeat(o)+l);continue}let h=l.startsWith("@end"),f=l.startsWith("@else")||l.startsWith("@elseif"),g=l.startsWith("@")&&wp(l),x=l.startsWith("<!DOCTYPE")||l.startsWith("<!doctype"),y=l.startsWith("<!--"),b=l.startsWith("</"),w=l.startsWith("<")&&!b&&!y&&!x,v=l.includes("/>")||bp(l),k=ii(l);if(b||h)o=Math.max(0,o-1);let C=f?Math.max(0,o-1):o;if(p)n.push(c);else n.push(i.repeat(C)+l);if(w&&!v&&!k&&!p||g)o++;if(d)s=!0;if(u)s=!1}return n.join(`
1951
+ `)}function xp(e,t){if(e=e.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,n,o)=>{let s=o.trim().replace(/\s+/g," ");return`@${n}(${s})`}),e=e.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,n,o)=>{if(o.trim()==="")return`@${n}`;return`@${n}(${o.trim()})`}),t.normalizeWhitespace)e=e.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,n)=>`{{ ${n.trim()} }}`),e=e.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,n)=>`{!! ${n.trim()} !!}`);return e}function bp(e){let t=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(e.includes("/>"))return!0;let r=e.match(/<(\w+)/);if(r){let n=r[1];return t.includes(n.toLowerCase())}return!1}function ii(e){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(e)}function wp(e){let t=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of t)if(e.startsWith(`@${r}`))return!e.includes(`@end${r}`);return!1}function vp(e,t){if(!t.sortAttributes)return e;return e.replace(/<(\w+)([^>]*)>/g,(r,n,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
1952
+ `)||o.includes("@"))return r;let s=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,i=[],a;while((a=s.exec(o))!==null)i.push({name:a[1],value:a[2]});i.sort((l,d)=>{if(l.name==="id")return-1;if(d.name==="id")return 1;if(l.name==="class")return-1;if(d.name==="class")return 1;return l.name.localeCompare(d.name)});let c=i.map((l)=>l.value?`${l.name}=${l.value}`:l.name).join(" ");return`<${n}${c?` ${c}`:""}>`})}import ci from"fs";import po from"path";var Yw={basic:{description:"Simple page with script, style, and template sections"},component:{description:"Reusable component with props and slots"},layout:{description:"Layout template with sections and yields"},blog:{description:"Blog post with frontmatter-style variables"},api:{description:"API endpoint template with JSON response"},app:{description:"Full app with stores and components"}};async function Kw(e="index.stx",t={}){try{let r=t.force||!1,n=po.resolve(process.cwd(),e);if(await Bun.file(n).exists()){if(!r)throw Error(`File ${e} already exists. Use --force to overwrite.`);console.warn(`File ${e} already exists. Overwriting...`)}let o=po.dirname(n);if(!ci.existsSync(o))ci.mkdirSync(o,{recursive:!0});let s;if(t.template){let i=po.resolve(process.cwd(),t.template);if(!await Bun.file(i).exists())throw Error(`Template file ${t.template} does not exist.`);if(!i.endsWith(".stx"))console.warn(`Warning: Template file ${t.template} does not have a .stx extension. Using it anyway.`);s=await Bun.file(i).text(),console.warn(`Using template from ${t.template}`)}else if(t.preset)s=li(t.preset),console.warn(`Using '${t.preset}' preset template`);else s=li("basic");return await Bun.write(n,s),console.warn(`Created new stx file: ${e}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function li(e){switch(e){case"basic":return di();case"component":return $p();case"layout":return Sp();case"blog":return kp();case"api":return Tp();case"app":return Cp();default:return di()}}function di(){return`<script>
1953
1953
  const title = "My stx Page"
1954
1954
  const description = "A page built with stx"
1955
1955
  const features = [
@@ -1974,7 +1974,7 @@ const features = [
1974
1974
  </div>
1975
1975
  @endforeach
1976
1976
  </main>
1977
- @endsection`}function vp(){return`{{-- Component: Card --}}
1977
+ @endsection`}function $p(){return`{{-- Component: Card --}}
1978
1978
  {{-- Props: title, variant, collapsible --}}
1979
1979
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1980
1980
  <script>
@@ -2019,7 +2019,7 @@ const features = [
2019
2019
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
2020
2020
  .card__body { padding: 1rem; }
2021
2021
  .card.collapsed .card__body { display: none; }
2022
- </style>`}function $p(){return`<!DOCTYPE html>
2022
+ </style>`}function Sp(){return`<!DOCTYPE html>
2023
2023
  <html lang="en">
2024
2024
  <head>
2025
2025
  <meta charset="UTF-8">
@@ -2070,7 +2070,7 @@ const features = [
2070
2070
 
2071
2071
  @yield('scripts')
2072
2072
  </body>
2073
- </html>`}function Sp(){return`<script>
2073
+ </html>`}function kp(){return`<script>
2074
2074
  // Article metadata
2075
2075
  const title = "My Blog Post"
2076
2076
  const author = "Your Name"
@@ -2115,7 +2115,7 @@ const features = [
2115
2115
  <p>Wrap up your thoughts here.</p>
2116
2116
  </div>
2117
2117
  </article>
2118
- @endsection`}function kp(){return`<script>
2118
+ @endsection`}function Tp(){return`<script>
2119
2119
  // API endpoint configuration
2120
2120
  const endpoint = "/api/data"
2121
2121
  const method = "GET"
@@ -2150,7 +2150,7 @@ const features = [
2150
2150
  }
2151
2151
  @else
2152
2152
  {{ JSON.stringify(data, null, 2) }}
2153
- @endif`}function Tp(){return`<!DOCTYPE html>
2153
+ @endif`}function Cp(){return`<!DOCTYPE html>
2154
2154
  <html lang="en">
2155
2155
  <head>
2156
2156
  <meta charset="UTF-8">
@@ -2375,37 +2375,37 @@ const features = [
2375
2375
  })();
2376
2376
  </script>
2377
2377
  </body>
2378
- </html>`}import Xt from"fs";import Ke from"path";import*as di from"readline";var $={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},lt={help:{description:"Show available commands",usage:"help [command]",handler:async(e,t)=>{if(e[0]&&lt[e[0]]){let r=lt[e[0]];console.log(`
2379
- ${$.bold}${e[0]}${$.reset} - ${r.description}`),console.log(` Usage: ${$.cyan}${r.usage}${$.reset}
2378
+ </html>`}import Jt from"fs";import Ge from"path";import*as ui from"readline";var S={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},dt={help:{description:"Show available commands",usage:"help [command]",handler:async(e,t)=>{if(e[0]&&dt[e[0]]){let r=dt[e[0]];console.log(`
2379
+ ${S.bold}${e[0]}${S.reset} - ${r.description}`),console.log(` Usage: ${S.cyan}${r.usage}${S.reset}
2380
2380
  `)}else{console.log(`
2381
- ${$.bold}Available Commands:${$.reset}
2382
- `);for(let[r,n]of Object.entries(lt))console.log(` ${$.cyan}${r.padEnd(12)}${$.reset} ${n.description}`);console.log(`
2383
- ${$.dim}Type 'help <command>' for more details${$.reset}
2384
- `)}}},render:{description:"Render a template file",usage:"render <file> [--raw]",handler:async(e,t)=>{if(!e[0]){console.log(`${$.red}Error: Please specify a file to render${$.reset}`);return}let r=Ke.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${$.red}Error: File not found: ${r}${$.reset}`);return}try{let n=await Bun.file(r).text(),o=e.includes("--raw");console.log(`
2385
- ${$.dim}Rendering ${r}...${$.reset}
2386
- `);let s=await se(n,t.context,r,{},new Set);if(t.lastResult=s,o)console.log(s);else s.split(`
2387
- `).forEach((i,a)=>{let c=String(a+1).padStart(3," ");console.log(`${$.dim}${c}${$.reset} ${i}`)});console.log()}catch(n){console.log(`${$.red}Error rendering template:${$.reset}`,n)}}},eval:{description:"Evaluate an expression",usage:"eval <expression>",handler:async(e,t)=>{if(!e.length){console.log(`${$.red}Error: Please provide an expression to evaluate${$.reset}`);return}let r=e.join(" ");try{let n=`{{ ${r} }}`,o=(await po(n,t.context,"eval")).trim();t.lastResult=o,console.log(`${$.green}\u2192${$.reset} ${o}`)}catch(n){console.log(`${$.red}Error:${$.reset}`,n)}}},set:{description:"Set a context variable",usage:"set <key> <value>",handler:async(e,t)=>{if(e.length<2){console.log(`${$.red}Error: Usage: set <key> <value>${$.reset}`);return}let r=e[0],n=e.slice(1).join(" "),o;try{o=JSON.parse(n)}catch{o=n}t.context[r]=o,console.log(`${$.green}\u2713${$.reset} ${r} = ${JSON.stringify(o)}`)}},unset:{description:"Remove a context variable",usage:"unset <key>",handler:async(e,t)=>{if(!e[0]){console.log(`${$.red}Error: Please specify a variable to remove${$.reset}`);return}if(e[0]in t.context)delete t.context[e[0]],console.log(`${$.green}\u2713${$.reset} Removed ${e[0]}`);else console.log(`${$.yellow}Variable not found: ${e[0]}${$.reset}`)}},context:{description:"Show current context variables",usage:"context",handler:async(e,t)=>{let r=Object.keys(t.context);if(r.length===0){console.log(`${$.dim}Context is empty${$.reset}`);return}console.log(`
2388
- ${$.bold}Context Variables:${$.reset}
2389
- `);for(let n of r){let o=t.context[n],s=Array.isArray(o)?"array":typeof o,i=JSON.stringify(o).slice(0,50);console.log(` ${$.cyan}${n}${$.reset} ${$.dim}(${s})${$.reset}: ${i}${i.length>=50?"...":""}`)}console.log()}},clear:{description:"Clear context or screen",usage:"clear [context|screen]",handler:async(e,t)=>{if(e[0]==="context"||!e[0])t.context={},console.log(`${$.green}\u2713${$.reset} Context cleared`);if(e[0]==="screen"||!e[0])console.clear()}},cd:{description:"Change working directory",usage:"cd <directory>",handler:async(e,t)=>{if(!e[0]){console.log(`${$.cyan}${t.cwd}${$.reset}`);return}let r=Ke.resolve(t.cwd,e[0]);if(!Xt.existsSync(r)){console.log(`${$.red}Error: Directory not found: ${r}${$.reset}`);return}if(!Xt.statSync(r).isDirectory()){console.log(`${$.red}Error: Not a directory: ${r}${$.reset}`);return}t.cwd=r,console.log(`${$.green}\u2713${$.reset} ${r}`)}},ls:{description:"List files in current directory",usage:"ls [pattern]",handler:async(e,t)=>{let r=e[0]||"*",n=new Bun.Glob(r),o=[];for await(let c of n.scan({cwd:t.cwd,onlyFiles:!1}))o.push(c);if(o.length===0){console.log(`${$.dim}No files found${$.reset}`);return}o.sort();let s=o.filter((c)=>c.endsWith(".stx")),i=o.filter((c)=>c.endsWith(".md")),a=o.filter((c)=>!c.endsWith(".stx")&&!c.endsWith(".md"));if(s.length>0)console.log(`
2390
- ${$.bold}Templates:${$.reset}`),s.forEach((c)=>console.log(` ${$.green}${c}${$.reset}`));if(i.length>0)console.log(`
2391
- ${$.bold}Markdown:${$.reset}`),i.forEach((c)=>console.log(` ${$.blue}${c}${$.reset}`));if(a.length>0)console.log(`
2392
- ${$.bold}Other:${$.reset}`),a.forEach((c)=>console.log(` ${$.dim}${c}${$.reset}`));console.log()}},cat:{description:"Show file contents",usage:"cat <file>",handler:async(e,t)=>{if(!e[0]){console.log(`${$.red}Error: Please specify a file${$.reset}`);return}let r=Ke.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${$.red}Error: File not found: ${r}${$.reset}`);return}let n=(await Bun.file(r).text()).split(`
2393
- `);console.log(),n.forEach((o,s)=>{let i=String(s+1).padStart(3," ");console.log(`${$.dim}${i}${$.reset} ${o}`)}),console.log()}},load:{description:"Load context from JSON file",usage:"load <file.json>",handler:async(e,t)=>{if(!e[0]){console.log(`${$.red}Error: Please specify a JSON file${$.reset}`);return}let r=Ke.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${$.red}Error: File not found: ${r}${$.reset}`);return}try{let n=await Bun.file(r).text(),o=JSON.parse(n);t.context={...t.context,...o},console.log(`${$.green}\u2713${$.reset} Loaded ${Object.keys(o).length} variables from ${e[0]}`)}catch(n){console.log(`${$.red}Error parsing JSON:${$.reset}`,n)}}},save:{description:"Save context to JSON file",usage:"save <file.json>",handler:async(e,t)=>{if(!e[0]){console.log(`${$.red}Error: Please specify a file name${$.reset}`);return}let r=Ke.resolve(t.cwd,e[0]);try{await Bun.write(r,JSON.stringify(t.context,null,2)),console.log(`${$.green}\u2713${$.reset} Context saved to ${e[0]}`)}catch(n){console.log(`${$.red}Error saving file:${$.reset}`,n)}}},history:{description:"Show command history",usage:"history [count]",handler:async(e,t)=>{let r=e[0]?Number.parseInt(e[0],10):20,n=t.history.slice(-r);if(n.length===0){console.log(`${$.dim}No history${$.reset}`);return}console.log(),n.forEach((o,s)=>{let i=String(t.history.length-n.length+s+1).padStart(3," ");console.log(`${$.dim}${i}${$.reset} ${o}`)}),console.log()}},exit:{description:"Exit interactive mode",usage:"exit",handler:async(e,t)=>{t.running=!1,console.log(`
2394
- ${$.dim}Goodbye!${$.reset}
2395
- `)}},quit:{description:"Exit interactive mode (alias for exit)",usage:"quit",handler:async(e,t)=>lt.exit.handler(e,t)}};function Cp(e,t){let r=e.split(" "),n=r[0];if(r.length===1)return Object.keys(lt).filter((o)=>o.startsWith(n));if(["render","cat","load","cd"].includes(n)){let o=r.slice(1).join(" "),s=Ke.dirname(o)||".",i=Ke.basename(o),a=Ke.resolve(t.cwd,s);if(Xt.existsSync(a)&&Xt.statSync(a).isDirectory())try{return Xt.readdirSync(a).filter((c)=>c.startsWith(i)).map((c)=>`${n} ${s==="."?"":`${s}/`}${c}`)}catch{return[]}}if(["unset","eval","set"].includes(n)){let o=r[1]||"";return Object.keys(t.context).filter((s)=>s.startsWith(o)).map((s)=>`${n} ${s}`)}return[]}async function tv(e={}){let t={context:e.context||{},cwd:e.cwd||process.cwd(),history:[],running:!0,lastResult:null},r=di.createInterface({input:process.stdin,output:process.stdout,completer:(o)=>{return[Cp(o,t),o]},historySize:e.maxHistory||100});console.log(`
2396
- ${$.bold}${$.blue}stx Interactive Mode${$.reset}
2397
- ${$.dim}Type 'help' for available commands, 'exit' to quit${$.reset}
2398
- `);let n=()=>{let o=t.cwd.replace(process.env.HOME||"","~");r.question(`${$.cyan}stx${$.reset} ${$.dim}${o}${$.reset} ${$.green}>${$.reset} `,async(s)=>{let i=s.trim();if(!i){if(t.running)n();return}t.history.push(i);let a=i.match(/(?:[^\s"]|"[^"]*")+/g)||[],c=a[0]?.toLowerCase(),l=a.slice(1).map((d)=>d.replace(/^"|"$/g,""));if(c&&lt[c])try{await lt[c].handler(l,t)}catch(d){console.log(`${$.red}Error:${$.reset}`,d)}else if(c)if(i.includes("{{")||i.includes("}}"))try{let d=await po(i,t.context,"eval");console.log(`${$.green}\u2192${$.reset} ${d}`)}catch{console.log(`${$.red}Unknown command: ${c}${$.reset}`),console.log(`${$.dim}Type 'help' for available commands${$.reset}`)}else console.log(`${$.red}Unknown command: ${c}${$.reset}`),console.log(`${$.dim}Type 'help' for available commands${$.reset}`);if(t.running)n();else r.close()})};r.on("SIGINT",()=>{console.log(`
2399
- ${$.dim}(Use 'exit' to quit)${$.reset}`),n()}),n()}async function Ep(e){let t=e.headers.get("content-type")||"",r={},n=(o,s)=>{let i=r[o];if(i===void 0)r[o]=s;else if(Array.isArray(i))i.push(s);else r[o]=[i,s]};if(t.includes("multipart/form-data")){let o=await e.formData();for(let[s,i]of o.entries())if(typeof i==="string")n(s,i);return r}if(t.includes("application/x-www-form-urlencoded")){for(let[o,s]of new URLSearchParams(await e.text()).entries())n(o,s);return r}return r}function fo(e){if(!e)return!1;let t=e.toUpperCase();return t!=="GET"&&t!=="HEAD"}async function ui(e,t={}){let r=t.request,n=t.method??r?.method;if(!r||!fo(n))return{ran:!1};if(typeof e.action!=="function")return{ran:!1};let o={};try{o=await Ep(r)}catch{}let s=await e.action({request:r,form:o,params:t.params??{},query:e.query??{},cookies:t.cookies??{}});if(s&&typeof s==="object"){let i=s.redirect;if(typeof i==="string"&&i)return{redirect:i,ran:!0};Object.assign(e,s)}return{ran:!0}}function pi(e){return new Response(null,{status:303,headers:{Location:e,"Cache-Control":"no-store"}})}import{createHash as _p}from"crypto";import{existsSync as Jt,mkdirSync as Ap,readFileSync as mo,writeFileSync as jp,readdirSync as Rp,statSync as Mp}from"fs";import{basename as Yt,dirname as ze,extname as Kt,join as Me,relative as fi,resolve as av}from"path";import{gzipSync as Dp}from"zlib";var mi={outDir:"dist",publicPath:"/",sourcemaps:!0,minify:{js:!0,css:!0,html:!0,dropConsole:!0,dropDebugger:!0,mangle:!0},splitting:{vendor:!0,minSize:20000,maxSize:250000,chunkNames:"deterministic"},css:{extract:!0,minify:!0,filename:"assets/[name].[hash].css"},assets:{inlineLimit:4096,filename:"assets/[name].[hash][ext]",hash:!0,hashLength:8,include:["png","jpg","jpeg","gif","svg","webp","woff","woff2","ttf","eot"]},compression:{gzip:!0,brotli:!0,threshold:1024,deleteOriginal:!1}};class ho{config;startTime=0;outputs=[];chunks=[];assets=[];warnings=[];errors=[];moduleGraph=new Map;assetHashes=new Map;constructor(e){this.config={...mi,...e}}async build(){this.startTime=Date.now(),this.outputs=[],this.chunks=[],this.assets=[],this.warnings=[],this.errors=[];try{this.ensureDir(this.config.outDir),await this.runPluginHook("setup"),await this.runPluginHook("buildStart");let e=this.collectEntries();for(let[r,n]of e)await this.buildEntry(r,n);if(this.config.css?.extract)await this.extractCss();if(await this.processAssets(),this.config.splitting)await this.performCodeSplitting();if(this.config.minify)await this.minifyOutputs();if(this.config.sourcemaps)await this.generateSourceMaps();if(await this.fingerprintAssets(),this.config.compression)await this.compressOutputs();if(this.config.analyze)await this.analyzeBundle();let t=this.getResult();return await this.runPluginHook("buildEnd",t),t}catch(e){return this.errors.push(String(e)),this.getResult()}}collectEntries(){let e=new Map,{entry:t}=this.config;if(typeof t==="string")e.set("main",t);else if(Array.isArray(t))t.forEach((r,n)=>{let o=Yt(r,Kt(r));e.set(o,r)});else if(typeof t==="object")Object.entries(t).forEach(([r,n])=>{e.set(r,n)});return e}async buildEntry(e,t){if(!await Bun.file(t).exists()){this.errors.push(`Entry point not found: ${t}`);return}let r=await Bun.file(t).text(),n=Kt(t),o=r,s="js";if(n===".stx"||n===".html")s="html",o=await this.processTemplate(r,t);else if(n===".css")s="css",o=await this.processCss(r,t);else if(n===".js"||n===".ts")s="js",o=await this.processScript(r,t);o=await this.runPluginTransform(o,t);let i=this.generateHash(o),a=this.getOutputName(e,s,i),c=Me(this.config.outDir,a);this.ensureDir(ze(c)),await Bun.write(c,o),this.outputs.push({path:c,type:s,size:Buffer.byteLength(o),hash:i,sources:[t],isEntry:!0})}resolveRelativePath(e,t){if(t.startsWith("/"))return Me(ze(e),"..",t);return Me(ze(e),t)}async processTemplate(e,t){let r=e,n=[],o=[];if(r=r.replace(/<script\b([^>]*)\bstx-inline\b([^>]*)(?:><\/script>|><\/script>|\/>)/gi,(s,i,a)=>{let c=(i+a).match(/src=["']([^"']+)["']/);if(c){let l=this.resolveRelativePath(t,c[1]);if(Jt(l)){let d=mo(l,"utf-8");n.push(`// Source: ${c[1]}
2400
- ${d}`)}else this.warnings.push(`External script not found: ${l}`)}return""}),r=r.replace(/<link\b([^>]*)\bstx-inline\b([^>]*)(?:\/>|>)/gi,(s,i,a)=>{let c=(i+a).match(/href=["']([^"']+)["']/);if(c){let l=this.resolveRelativePath(t,c[1]);if(Jt(l)){let d=mo(l,"utf-8");o.push(`/* Source: ${c[1]} */
2381
+ ${S.bold}Available Commands:${S.reset}
2382
+ `);for(let[r,n]of Object.entries(dt))console.log(` ${S.cyan}${r.padEnd(12)}${S.reset} ${n.description}`);console.log(`
2383
+ ${S.dim}Type 'help <command>' for more details${S.reset}
2384
+ `)}}},render:{description:"Render a template file",usage:"render <file> [--raw]",handler:async(e,t)=>{if(!e[0]){console.log(`${S.red}Error: Please specify a file to render${S.reset}`);return}let r=Ge.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${S.red}Error: File not found: ${r}${S.reset}`);return}try{let n=await Bun.file(r).text(),o=e.includes("--raw");console.log(`
2385
+ ${S.dim}Rendering ${r}...${S.reset}
2386
+ `);let s=await ie(n,t.context,r,{},new Set);if(t.lastResult=s,o)console.log(s);else s.split(`
2387
+ `).forEach((i,a)=>{let c=String(a+1).padStart(3," ");console.log(`${S.dim}${c}${S.reset} ${i}`)});console.log()}catch(n){console.log(`${S.red}Error rendering template:${S.reset}`,n)}}},eval:{description:"Evaluate an expression",usage:"eval <expression>",handler:async(e,t)=>{if(!e.length){console.log(`${S.red}Error: Please provide an expression to evaluate${S.reset}`);return}let r=e.join(" ");try{let n=`{{ ${r} }}`,o=(await fo(n,t.context,"eval")).trim();t.lastResult=o,console.log(`${S.green}\u2192${S.reset} ${o}`)}catch(n){console.log(`${S.red}Error:${S.reset}`,n)}}},set:{description:"Set a context variable",usage:"set <key> <value>",handler:async(e,t)=>{if(e.length<2){console.log(`${S.red}Error: Usage: set <key> <value>${S.reset}`);return}let r=e[0],n=e.slice(1).join(" "),o;try{o=JSON.parse(n)}catch{o=n}t.context[r]=o,console.log(`${S.green}\u2713${S.reset} ${r} = ${JSON.stringify(o)}`)}},unset:{description:"Remove a context variable",usage:"unset <key>",handler:async(e,t)=>{if(!e[0]){console.log(`${S.red}Error: Please specify a variable to remove${S.reset}`);return}if(e[0]in t.context)delete t.context[e[0]],console.log(`${S.green}\u2713${S.reset} Removed ${e[0]}`);else console.log(`${S.yellow}Variable not found: ${e[0]}${S.reset}`)}},context:{description:"Show current context variables",usage:"context",handler:async(e,t)=>{let r=Object.keys(t.context);if(r.length===0){console.log(`${S.dim}Context is empty${S.reset}`);return}console.log(`
2388
+ ${S.bold}Context Variables:${S.reset}
2389
+ `);for(let n of r){let o=t.context[n],s=Array.isArray(o)?"array":typeof o,i=JSON.stringify(o).slice(0,50);console.log(` ${S.cyan}${n}${S.reset} ${S.dim}(${s})${S.reset}: ${i}${i.length>=50?"...":""}`)}console.log()}},clear:{description:"Clear context or screen",usage:"clear [context|screen]",handler:async(e,t)=>{if(e[0]==="context"||!e[0])t.context={},console.log(`${S.green}\u2713${S.reset} Context cleared`);if(e[0]==="screen"||!e[0])console.clear()}},cd:{description:"Change working directory",usage:"cd <directory>",handler:async(e,t)=>{if(!e[0]){console.log(`${S.cyan}${t.cwd}${S.reset}`);return}let r=Ge.resolve(t.cwd,e[0]);if(!Jt.existsSync(r)){console.log(`${S.red}Error: Directory not found: ${r}${S.reset}`);return}if(!Jt.statSync(r).isDirectory()){console.log(`${S.red}Error: Not a directory: ${r}${S.reset}`);return}t.cwd=r,console.log(`${S.green}\u2713${S.reset} ${r}`)}},ls:{description:"List files in current directory",usage:"ls [pattern]",handler:async(e,t)=>{let r=e[0]||"*",n=new Bun.Glob(r),o=[];for await(let c of n.scan({cwd:t.cwd,onlyFiles:!1}))o.push(c);if(o.length===0){console.log(`${S.dim}No files found${S.reset}`);return}o.sort();let s=o.filter((c)=>c.endsWith(".stx")),i=o.filter((c)=>c.endsWith(".md")),a=o.filter((c)=>!c.endsWith(".stx")&&!c.endsWith(".md"));if(s.length>0)console.log(`
2390
+ ${S.bold}Templates:${S.reset}`),s.forEach((c)=>console.log(` ${S.green}${c}${S.reset}`));if(i.length>0)console.log(`
2391
+ ${S.bold}Markdown:${S.reset}`),i.forEach((c)=>console.log(` ${S.blue}${c}${S.reset}`));if(a.length>0)console.log(`
2392
+ ${S.bold}Other:${S.reset}`),a.forEach((c)=>console.log(` ${S.dim}${c}${S.reset}`));console.log()}},cat:{description:"Show file contents",usage:"cat <file>",handler:async(e,t)=>{if(!e[0]){console.log(`${S.red}Error: Please specify a file${S.reset}`);return}let r=Ge.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${S.red}Error: File not found: ${r}${S.reset}`);return}let n=(await Bun.file(r).text()).split(`
2393
+ `);console.log(),n.forEach((o,s)=>{let i=String(s+1).padStart(3," ");console.log(`${S.dim}${i}${S.reset} ${o}`)}),console.log()}},load:{description:"Load context from JSON file",usage:"load <file.json>",handler:async(e,t)=>{if(!e[0]){console.log(`${S.red}Error: Please specify a JSON file${S.reset}`);return}let r=Ge.resolve(t.cwd,e[0]);if(!await Bun.file(r).exists()){console.log(`${S.red}Error: File not found: ${r}${S.reset}`);return}try{let n=await Bun.file(r).text(),o=JSON.parse(n);t.context={...t.context,...o},console.log(`${S.green}\u2713${S.reset} Loaded ${Object.keys(o).length} variables from ${e[0]}`)}catch(n){console.log(`${S.red}Error parsing JSON:${S.reset}`,n)}}},save:{description:"Save context to JSON file",usage:"save <file.json>",handler:async(e,t)=>{if(!e[0]){console.log(`${S.red}Error: Please specify a file name${S.reset}`);return}let r=Ge.resolve(t.cwd,e[0]);try{await Bun.write(r,JSON.stringify(t.context,null,2)),console.log(`${S.green}\u2713${S.reset} Context saved to ${e[0]}`)}catch(n){console.log(`${S.red}Error saving file:${S.reset}`,n)}}},history:{description:"Show command history",usage:"history [count]",handler:async(e,t)=>{let r=e[0]?Number.parseInt(e[0],10):20,n=t.history.slice(-r);if(n.length===0){console.log(`${S.dim}No history${S.reset}`);return}console.log(),n.forEach((o,s)=>{let i=String(t.history.length-n.length+s+1).padStart(3," ");console.log(`${S.dim}${i}${S.reset} ${o}`)}),console.log()}},exit:{description:"Exit interactive mode",usage:"exit",handler:async(e,t)=>{t.running=!1,console.log(`
2394
+ ${S.dim}Goodbye!${S.reset}
2395
+ `)}},quit:{description:"Exit interactive mode (alias for exit)",usage:"quit",handler:async(e,t)=>dt.exit.handler(e,t)}};function Ep(e,t){let r=e.split(" "),n=r[0];if(r.length===1)return Object.keys(dt).filter((o)=>o.startsWith(n));if(["render","cat","load","cd"].includes(n)){let o=r.slice(1).join(" "),s=Ge.dirname(o)||".",i=Ge.basename(o),a=Ge.resolve(t.cwd,s);if(Jt.existsSync(a)&&Jt.statSync(a).isDirectory())try{return Jt.readdirSync(a).filter((c)=>c.startsWith(i)).map((c)=>`${n} ${s==="."?"":`${s}/`}${c}`)}catch{return[]}}if(["unset","eval","set"].includes(n)){let o=r[1]||"";return Object.keys(t.context).filter((s)=>s.startsWith(o)).map((s)=>`${n} ${s}`)}return[]}async function rv(e={}){let t={context:e.context||{},cwd:e.cwd||process.cwd(),history:[],running:!0,lastResult:null},r=ui.createInterface({input:process.stdin,output:process.stdout,completer:(o)=>[Ep(o,t),o],historySize:e.maxHistory||100});console.log(`
2396
+ ${S.bold}${S.blue}stx Interactive Mode${S.reset}
2397
+ ${S.dim}Type 'help' for available commands, 'exit' to quit${S.reset}
2398
+ `);let n=()=>{let o=t.cwd.replace(process.env.HOME||"","~");r.question(`${S.cyan}stx${S.reset} ${S.dim}${o}${S.reset} ${S.green}>${S.reset} `,async(s)=>{let i=s.trim();if(!i){if(t.running)n();return}t.history.push(i);let a=i.match(/(?:[^\s"]|"[^"]*")+/g)||[],c=a[0]?.toLowerCase(),l=a.slice(1).map((d)=>d.replace(/^"|"$/g,""));if(c&&dt[c])try{await dt[c].handler(l,t)}catch(d){console.log(`${S.red}Error:${S.reset}`,d)}else if(c)if(i.includes("{{")||i.includes("}}"))try{let d=await fo(i,t.context,"eval");console.log(`${S.green}\u2192${S.reset} ${d}`)}catch{console.log(`${S.red}Unknown command: ${c}${S.reset}`),console.log(`${S.dim}Type 'help' for available commands${S.reset}`)}else console.log(`${S.red}Unknown command: ${c}${S.reset}`),console.log(`${S.dim}Type 'help' for available commands${S.reset}`);if(t.running)n();else r.close()})};r.on("SIGINT",()=>{console.log(`
2399
+ ${S.dim}(Use 'exit' to quit)${S.reset}`),n()}),n()}async function _p(e){let t=e.headers.get("content-type")||"",r={},n=(o,s)=>{let i=r[o];if(i===void 0)r[o]=s;else if(Array.isArray(i))i.push(s);else r[o]=[i,s]};if(t.includes("multipart/form-data")){let o=await e.formData();for(let[s,i]of o.entries())if(typeof i==="string")n(s,i);return r}if(t.includes("application/x-www-form-urlencoded")){for(let[o,s]of new URLSearchParams(await e.text()).entries())n(o,s);return r}return r}function mo(e){if(!e)return!1;let t=e.toUpperCase();return t!=="GET"&&t!=="HEAD"}async function pi(e,t={}){let r=t.request,n=t.method??r?.method;if(!r||!mo(n))return{ran:!1};if(typeof e.action!=="function")return{ran:!1};let o={};try{o=await _p(r)}catch{}let s=await e.action({request:r,form:o,params:t.params??{},query:e.query??{},cookies:t.cookies??{}});if(s&&typeof s==="object"){let i=s.redirect;if(typeof i==="string"&&i)return{redirect:i,ran:!0};Object.assign(e,s)}return{ran:!0}}function fi(e){return new Response(null,{status:303,headers:{Location:e,"Cache-Control":"no-store"}})}import{createHash as Ap}from"crypto";import{existsSync as Yt,mkdirSync as jp,readFileSync as ho,writeFileSync as Rp,readdirSync as Mp,statSync as Dp}from"fs";import{basename as Kt,dirname as Ue,extname as Gt,join as De,relative as mi,resolve as cv}from"path";import{gzipSync as Pp}from"zlib";var hi={outDir:"dist",publicPath:"/",sourcemaps:!0,minify:{js:!0,css:!0,html:!0,dropConsole:!0,dropDebugger:!0,mangle:!0},splitting:{vendor:!0,minSize:20000,maxSize:250000,chunkNames:"deterministic"},css:{extract:!0,minify:!0,filename:"assets/[name].[hash].css"},assets:{inlineLimit:4096,filename:"assets/[name].[hash][ext]",hash:!0,hashLength:8,include:["png","jpg","jpeg","gif","svg","webp","woff","woff2","ttf","eot"]},compression:{gzip:!0,brotli:!0,threshold:1024,deleteOriginal:!1}};class go{config;startTime=0;outputs=[];chunks=[];assets=[];warnings=[];errors=[];moduleGraph=new Map;assetHashes=new Map;constructor(e){this.config={...hi,...e}}async build(){this.startTime=Date.now(),this.outputs=[],this.chunks=[],this.assets=[],this.warnings=[],this.errors=[];try{this.ensureDir(this.config.outDir),await this.runPluginHook("setup"),await this.runPluginHook("buildStart");let e=this.collectEntries();for(let[r,n]of e)await this.buildEntry(r,n);if(this.config.css?.extract)await this.extractCss();if(await this.processAssets(),this.config.splitting)await this.performCodeSplitting();if(this.config.minify)await this.minifyOutputs();if(this.config.sourcemaps)await this.generateSourceMaps();if(await this.fingerprintAssets(),this.config.compression)await this.compressOutputs();if(this.config.analyze)await this.analyzeBundle();let t=this.getResult();return await this.runPluginHook("buildEnd",t),t}catch(e){return this.errors.push(String(e)),this.getResult()}}collectEntries(){let e=new Map,{entry:t}=this.config;if(typeof t==="string")e.set("main",t);else if(Array.isArray(t))t.forEach((r,n)=>{let o=Kt(r,Gt(r));e.set(o,r)});else if(typeof t==="object")Object.entries(t).forEach(([r,n])=>{e.set(r,n)});return e}async buildEntry(e,t){if(!await Bun.file(t).exists()){this.errors.push(`Entry point not found: ${t}`);return}let r=await Bun.file(t).text(),n=Gt(t),o=r,s="js";if(n===".stx"||n===".html")s="html",o=await this.processTemplate(r,t);else if(n===".css")s="css",o=await this.processCss(r,t);else if(n===".js"||n===".ts")s="js",o=await this.processScript(r,t);o=await this.runPluginTransform(o,t);let i=this.generateHash(o),a=this.getOutputName(e,s,i),c=De(this.config.outDir,a);this.ensureDir(Ue(c)),await Bun.write(c,o),this.outputs.push({path:c,type:s,size:Buffer.byteLength(o),hash:i,sources:[t],isEntry:!0})}resolveRelativePath(e,t){if(t.startsWith("/"))return De(Ue(e),"..",t);return De(Ue(e),t)}async processTemplate(e,t){let r=e,n=[],o=[];if(r=r.replace(/<script\b([^>]*)\bstx-inline\b([^>]*)(?:><\/script>|><\/script>|\/>)/gi,(s,i,a)=>{let c=(i+a).match(/src=["']([^"']+)["']/);if(c){let l=this.resolveRelativePath(t,c[1]);if(Yt(l)){let d=ho(l,"utf-8");n.push(`// Source: ${c[1]}
2400
+ ${d}`)}else this.warnings.push(`External script not found: ${l}`)}return""}),r=r.replace(/<link\b([^>]*)\bstx-inline\b([^>]*)(?:\/>|>)/gi,(s,i,a)=>{let c=(i+a).match(/href=["']([^"']+)["']/);if(c){let l=this.resolveRelativePath(t,c[1]);if(Yt(l)){let d=ho(l,"utf-8");o.push(`/* Source: ${c[1]} */
2401
2401
  ${d}`)}else this.warnings.push(`External stylesheet not found: ${l}`)}return""}),r=r.replace(/<script\b(?![^>]*\bstx-inline\b)([^>]*)>([\s\S]*?)<\/script>/gi,(s,i,a)=>{if(/\bsrc=/.test(i))return s;if(a.trim())n.push(a);return""}),r=r.replace(/<style\b[^>]*>([\s\S]*?)<\/style>/gi,(s,i)=>{if(i.trim())o.push(i);return""}),n.length>0){let s=n.join(`
2402
2402
 
2403
- `),i=this.generateHash(s).slice(0,8),a=`assets/app.${i}.js`,c=Me(this.config.outDir,a);this.ensureDir(ze(c)),await Bun.write(c,s),this.outputs.push({path:c,type:"js",size:Buffer.byteLength(s),hash:i,sources:[t]});let l=r.lastIndexOf("</body>");if(l!==-1)r=r.slice(0,l)+`<script src="${this.config.publicPath}${a}"></script>
2403
+ `),i=this.generateHash(s).slice(0,8),a=`assets/app.${i}.js`,c=De(this.config.outDir,a);this.ensureDir(Ue(c)),await Bun.write(c,s),this.outputs.push({path:c,type:"js",size:Buffer.byteLength(s),hash:i,sources:[t]});let l=r.lastIndexOf("</body>");if(l!==-1)r=r.slice(0,l)+`<script src="${this.config.publicPath}${a}"></script>
2404
2404
  `+r.slice(l)}if(o.length>0){let s=o.join(`
2405
2405
 
2406
- `),i=this.generateHash(s).slice(0,8),a=`assets/app.${i}.css`,c=Me(this.config.outDir,a);this.ensureDir(ze(c)),await Bun.write(c,s),this.outputs.push({path:c,type:"css",size:Buffer.byteLength(s),hash:i,sources:[t]}),r=r.replace("</head>",`<link rel="stylesheet" href="${this.config.publicPath}${a}">
2406
+ `),i=this.generateHash(s).slice(0,8),a=`assets/app.${i}.css`,c=De(this.config.outDir,a);this.ensureDir(Ue(c)),await Bun.write(c,s),this.outputs.push({path:c,type:"css",size:Buffer.byteLength(s),hash:i,sources:[t]}),r=r.replace("</head>",`<link rel="stylesheet" href="${this.config.publicPath}${a}">
2407
2407
  </head>`)}return r}async processCss(e,t){let r=e;if(typeof this.config.minify==="object"&&this.config.minify.css)r=this.minifyCss(r);return r}async processScript(e,t){let r=e;if(this.config.define)for(let[n,o]of Object.entries(this.config.define))r=r.replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o);return r}async extractCss(){let e=[];for(let s of this.outputs)if(s.type==="css"){let i=await Bun.file(s.path).text();e.push(i)}if(e.length===0)return;let t=e.join(`
2408
- `),r=this.generateHash(t).slice(0,8),n=(this.config.css?.filename||"assets/[name].[hash].css").replace("[name]","styles").replace("[hash]",r),o=Me(this.config.outDir,n);this.ensureDir(ze(o)),await Bun.write(o,t),this.outputs.push({path:o,type:"css",size:Buffer.byteLength(t),hash:r})}async processAssets(){let e=Me(ze(this.config.outDir),"public");if(!Jt(e))return;let t=this.config.assets||{},r=t.include||[];this.walkDir(e,(n)=>{let o=Kt(n).slice(1).toLowerCase();if(!r.includes(o))return;let s=mo(n),i=s.length;if(t.inlineLimit&&i<t.inlineLimit)return;let a=t.hash?this.generateHash(s).slice(0,t.hashLength||8):"",c=(t.filename||"assets/[name].[hash][ext]").replace("[name]",Yt(n,Kt(n))).replace("[hash]",a).replace("[ext]",Kt(n)),l=Me(this.config.outDir,c);this.ensureDir(ze(l)),jp(l,s),this.assetHashes.set(n,c),this.assets.push({name:Yt(n),file:c,size:i,source:n}),this.outputs.push({path:l,type:"asset",size:i,hash:a,sources:[n]})})}async performCodeSplitting(){if((typeof this.config.splitting==="object"?this.config.splitting:{}).vendor){let e=[];this.chunks.push({name:"vendor",file:"assets/vendor.js",size:0,modules:e,isVendor:!0,imports:[],dynamicImports:[]})}}async minifyOutputs(){let e=typeof this.config.minify==="object"?this.config.minify:{};for(let t of this.outputs){let r=await Bun.file(t.path).text(),n=r;if(t.type==="js"&&e.js)n=this.minifyJs(r);else if(t.type==="css"&&e.css)n=this.minifyCss(r);else if(t.type==="html"&&e.html)n=this.minifyHtml(r);if(n!==r)await Bun.write(t.path,n),t.size=Buffer.byteLength(n)}}minifyJs(e){let t=typeof this.config.minify==="object"?this.config.minify:{},r=e;if(r=r.replace(/\/\*[\s\S]*?\*\//g,""),r=r.replace(/\/\/.*$/gm,""),t.dropConsole)r=r.replace(/console\.(log|debug|info|warn)\([^)]*\);?/g,"");if(t.dropDebugger)r=r.replace(/debugger;?/g,"");return r=r.replace(/\s+/g," "),r=r.replace(/\s*([{};,:])\s*/g,"$1"),r=r.replace(/;\}/g,"}"),r.trim()}minifyCss(e){let t=e;return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t=t.replace(/\s+/g," "),t=t.replace(/\s*([{};:,>+~])\s*/g,"$1"),t=t.replace(/;}/g,"}"),t=t.replace(/[^{}]+\{\s*\}/g,""),t.trim()}minifyHtml(e){let t=e;return t=t.replace(/<!--(?!\[if)[\s\S]*?-->/g,""),t=t.replace(/>\s+</g,"><"),t=t.replace(/\s+>/g,">"),t=t.replace(/<\s+/g,"<"),t=t.replace(/\s{2,}/g," "),t.trim()}async generateSourceMaps(){if(!this.config.sourcemaps)return;for(let e of this.outputs)if(e.type==="js"||e.type==="css"){let t=await Bun.file(e.path).text(),r=[];for(let a of e.sources||[])if(await Bun.file(a).exists())r.push(await Bun.file(a).text());else r.push(null);let n={version:3,file:Yt(e.path),sources:e.sources||[],sourcesContent:r,mappings:"",names:[]},o=`${e.path}.map`;await Bun.write(o,JSON.stringify(n));let s=new Uint8Array([10,47,47,35,32,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,61]),i=this.config.sourcemaps==="inline"?`data:application/json;base64,${Buffer.from(JSON.stringify(n)).toString("base64")}`:Yt(o);if(this.config.sourcemaps!=="hidden")await Bun.write(e.path,Buffer.concat([Buffer.from(t),Buffer.from(s),Buffer.from(i)]));this.outputs.push({path:o,type:"map",size:Mp(o).size})}}async fingerprintAssets(){for(let e of this.outputs)if(e.type==="html"){let t=await Bun.file(e.path).text();for(let[r,n]of this.assetHashes){let o=fi(ze(e.path),r);t=t.replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),`${this.config.publicPath}${n}`)}await Bun.write(e.path,t)}}async compressOutputs(){let e=this.config.compression||{},t=e.threshold||1024;for(let r of this.outputs){if(r.type==="map")continue;if(r.size<t)continue;let n=Buffer.from(await Bun.file(r.path).arrayBuffer());if(e.gzip){let o=Dp(n,{level:9}),s=`${r.path}.gz`;await Bun.write(s,o),r.gzipSize=o.length}if(e.brotli)try{let{brotliCompressSync:o}=await import("zlib"),s=o(n);await Bun.write(`${r.path}.br`,s)}catch{}}}async analyzeBundle(){let e=typeof this.config.analyze==="object"?this.config.analyze:{},t=e.format||"text",r={outputs:this.outputs.map((i)=>({path:fi(this.config.outDir,i.path),type:i.type,size:i.size,gzipSize:i.gzipSize,sizeFormatted:this.formatSize(i.size),gzipSizeFormatted:i.gzipSize?this.formatSize(i.gzipSize):void 0})),chunks:this.chunks,assets:this.assets,totalSize:this.outputs.reduce((i,a)=>i+a.size,0),totalGzipSize:this.outputs.reduce((i,a)=>i+(a.gzipSize||0),0)},n;if(t==="json")n=JSON.stringify(r,null,2);else if(t==="html")n=this.generateAnalysisHtml(r);else n=this.generateAnalysisText(r);let o=e.filename||`bundle-analysis.${t==="html"?"html":t==="json"?"json":"txt"}`,s=Me(this.config.outDir,o);await Bun.write(s,n),console.log(`
2408
+ `),r=this.generateHash(t).slice(0,8),n=(this.config.css?.filename||"assets/[name].[hash].css").replace("[name]","styles").replace("[hash]",r),o=De(this.config.outDir,n);this.ensureDir(Ue(o)),await Bun.write(o,t),this.outputs.push({path:o,type:"css",size:Buffer.byteLength(t),hash:r})}async processAssets(){let e=De(Ue(this.config.outDir),"public");if(!Yt(e))return;let t=this.config.assets||{},r=t.include||[];this.walkDir(e,(n)=>{let o=Gt(n).slice(1).toLowerCase();if(!r.includes(o))return;let s=ho(n),i=s.length;if(t.inlineLimit&&i<t.inlineLimit)return;let a=t.hash?this.generateHash(s).slice(0,t.hashLength||8):"",c=(t.filename||"assets/[name].[hash][ext]").replace("[name]",Kt(n,Gt(n))).replace("[hash]",a).replace("[ext]",Gt(n)),l=De(this.config.outDir,c);this.ensureDir(Ue(l)),Rp(l,s),this.assetHashes.set(n,c),this.assets.push({name:Kt(n),file:c,size:i,source:n}),this.outputs.push({path:l,type:"asset",size:i,hash:a,sources:[n]})})}async performCodeSplitting(){if((typeof this.config.splitting==="object"?this.config.splitting:{}).vendor){let e=[];this.chunks.push({name:"vendor",file:"assets/vendor.js",size:0,modules:e,isVendor:!0,imports:[],dynamicImports:[]})}}async minifyOutputs(){let e=typeof this.config.minify==="object"?this.config.minify:{};for(let t of this.outputs){let r=await Bun.file(t.path).text(),n=r;if(t.type==="js"&&e.js)n=this.minifyJs(r);else if(t.type==="css"&&e.css)n=this.minifyCss(r);else if(t.type==="html"&&e.html)n=this.minifyHtml(r);if(n!==r)await Bun.write(t.path,n),t.size=Buffer.byteLength(n)}}minifyJs(e){let t=typeof this.config.minify==="object"?this.config.minify:{},r=e;if(r=r.replace(/\/\*[\s\S]*?\*\//g,""),r=r.replace(/\/\/.*$/gm,""),t.dropConsole)r=r.replace(/console\.(log|debug|info|warn)\([^)]*\);?/g,"");if(t.dropDebugger)r=r.replace(/debugger;?/g,"");return r=r.replace(/\s+/g," "),r=r.replace(/\s*([{};,:])\s*/g,"$1"),r=r.replace(/;\}/g,"}"),r.trim()}minifyCss(e){let t=e;return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t=t.replace(/\s+/g," "),t=t.replace(/\s*([{};:,>+~])\s*/g,"$1"),t=t.replace(/;}/g,"}"),t=t.replace(/[^{}]+\{\s*\}/g,""),t.trim()}minifyHtml(e){let t=e;return t=t.replace(/<!--(?!\[if)[\s\S]*?-->/g,""),t=t.replace(/>\s+</g,"><"),t=t.replace(/\s+>/g,">"),t=t.replace(/<\s+/g,"<"),t=t.replace(/\s{2,}/g," "),t.trim()}async generateSourceMaps(){if(!this.config.sourcemaps)return;for(let e of this.outputs)if(e.type==="js"||e.type==="css"){let t=await Bun.file(e.path).text(),r=[];for(let a of e.sources||[])if(await Bun.file(a).exists())r.push(await Bun.file(a).text());else r.push(null);let n={version:3,file:Kt(e.path),sources:e.sources||[],sourcesContent:r,mappings:"",names:[]},o=`${e.path}.map`;await Bun.write(o,JSON.stringify(n));let s=new Uint8Array([10,47,47,35,32,115,111,117,114,99,101,77,97,112,112,105,110,103,85,82,76,61]),i=this.config.sourcemaps==="inline"?`data:application/json;base64,${Buffer.from(JSON.stringify(n)).toString("base64")}`:Kt(o);if(this.config.sourcemaps!=="hidden")await Bun.write(e.path,Buffer.concat([Buffer.from(t),Buffer.from(s),Buffer.from(i)]));this.outputs.push({path:o,type:"map",size:Dp(o).size})}}async fingerprintAssets(){for(let e of this.outputs)if(e.type==="html"){let t=await Bun.file(e.path).text();for(let[r,n]of this.assetHashes){let o=mi(Ue(e.path),r);t=t.replace(new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),`${this.config.publicPath}${n}`)}await Bun.write(e.path,t)}}async compressOutputs(){let e=this.config.compression||{},t=e.threshold||1024;for(let r of this.outputs){if(r.type==="map")continue;if(r.size<t)continue;let n=Buffer.from(await Bun.file(r.path).arrayBuffer());if(e.gzip){let o=Pp(n,{level:9}),s=`${r.path}.gz`;await Bun.write(s,o),r.gzipSize=o.length}if(e.brotli)try{let{brotliCompressSync:o}=await import("zlib"),s=o(n);await Bun.write(`${r.path}.br`,s)}catch{}}}async analyzeBundle(){let e=typeof this.config.analyze==="object"?this.config.analyze:{},t=e.format||"text",r={outputs:this.outputs.map((i)=>({path:mi(this.config.outDir,i.path),type:i.type,size:i.size,gzipSize:i.gzipSize,sizeFormatted:this.formatSize(i.size),gzipSizeFormatted:i.gzipSize?this.formatSize(i.gzipSize):void 0})),chunks:this.chunks,assets:this.assets,totalSize:this.outputs.reduce((i,a)=>i+a.size,0),totalGzipSize:this.outputs.reduce((i,a)=>i+(a.gzipSize||0),0)},n;if(t==="json")n=JSON.stringify(r,null,2);else if(t==="html")n=this.generateAnalysisHtml(r);else n=this.generateAnalysisText(r);let o=e.filename||`bundle-analysis.${t==="html"?"html":t==="json"?"json":"txt"}`,s=De(this.config.outDir,o);await Bun.write(s,n),console.log(`
2409
2409
  \uD83D\uDCCA Bundle Analysis`),console.log("\u2500".repeat(50));for(let i of r.outputs){let a=i.gzipSizeFormatted?` (gzip: ${i.gzipSizeFormatted})`:"";console.log(` ${i.path}: ${i.sizeFormatted}${a}`)}console.log("\u2500".repeat(50)),console.log(` Total: ${this.formatSize(r.totalSize)} (gzip: ${this.formatSize(r.totalGzipSize)})`),console.log("")}generateAnalysisHtml(e){return`<!DOCTYPE html>
2410
2410
  <html>
2411
2411
  <head>
@@ -2446,44 +2446,44 @@ ${d}`)}else this.warnings.push(`External stylesheet not found: ${l}`)}return""})
2446
2446
  </table>
2447
2447
  </body>
2448
2448
  </html>`}generateAnalysisText(e){let t=["Bundle Analysis","=".repeat(50),""];for(let r of e.outputs)t.push(`${r.path}`),t.push(` Size: ${r.sizeFormatted}${r.gzipSizeFormatted?` (gzip: ${r.gzipSizeFormatted})`:""}`),t.push("");return t.push("=".repeat(50)),t.push(`Total: ${this.formatSize(e.totalSize)} (gzip: ${this.formatSize(e.totalGzipSize)})`),t.join(`
2449
- `)}async runPluginHook(e,t){if(!this.config.plugins)return;for(let r of this.config.plugins){let n=r[e];if(typeof n==="function")await n.call(r,t||this)}}async runPluginTransform(e,t){if(!this.config.plugins)return e;let r=e;for(let n of this.config.plugins)if(n.transform){let o=await n.transform(r,t);if(o!=null)r=o}return r}generateHash(e){return _p("sha256").update(e).digest("hex")}getOutputName(e,t,r){let n=t==="html"?".html":t==="css"?".css":t==="js"?".js":"";return`${e}.${r.slice(0,8)}${n}`}formatSize(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(2)} KB`;return`${(e/1048576).toFixed(2)} MB`}ensureDir(e){if(!Jt(e))Ap(e,{recursive:!0})}walkDir(e,t){if(!Jt(e))return;let r=Rp(e,{withFileTypes:!0});for(let n of r){let o=Me(e,n.name);if(n.isDirectory())this.walkDir(o,t);else t(o)}}getResult(){let e=Date.now()-this.startTime,t=this.outputs.reduce((n,o)=>n+o.size,0),r=this.outputs.reduce((n,o)=>n+(o.gzipSize||0),0);return{outputs:this.outputs,duration:e,totalSize:t,gzipSize:r,chunks:this.chunks,assets:this.assets,warnings:this.warnings,errors:this.errors}}}async function lv(e){return new ho(e).build()}function dv(e){return new ho(e)}function uv(e){return{...mi,...e}}import yi from"fs";import dt from"path";var{serve:Op}=globalThis.Bun;async function yv(e,t={}){return(await gi(e,t)).html}async function hi(e,t={}){let{html:r,context:n,redirect:o}=await gi(e,t);if(o)return{html:r,redirect:o};let{extractStreamBoundaries:s}=await import("./chunk-edrtesh7.js"),i=s(n),a=e.streamTemplates;if(a&&Object.keys(a).length>0){let{processDirectives:c}=await import("./chunk-bqdycvtc.js"),{defaultConfig:l}=await import("./chunk-cd03rk3x.js"),d=n.streamBoundaries||{},u={...l,autoShell:!1},p=Object.keys(a).map((f)=>({id:f,render:async()=>{let g=typeof d[f]==="function"?await d[f]():void 0;return c(a[f],{...n,$boundary:g},e.sourceFile,u,new Set)}})),h=new Set(p.map((f)=>f.id));i=[...(i||[]).filter((f)=>!h.has(f.id)),...p]}return{html:r,boundaries:i&&i.length>0?i:void 0}}async function gi(e,t){let r={__filename:e.sourceFile,__dirname:e.sourceFile.replace(/[/\\][^/\\]+$/,""),...t};if(!e.hasServerScripts&&!Gt(e.html))return{html:e.html,context:r};for(let s of e.serverScriptContent)try{await te(s,r,e.sourceFile)}catch(i){console.warn(`[stx] Server script error in ${e.sourceFile}:`,i)}let n=await ui(r,{request:t.request,method:t.method,params:t.params??{},cookies:t.cookies??{}});if(n.redirect)return{html:e.html,context:r,redirect:n.redirect};if(!Gt(e.html))return{html:e.html,context:r};let o=new Map;for(let[s,i]of Object.entries(e.placeholders))if(i.expression)try{let a=yo(i.expression,r);if(i.type==="raw")o.set(s,a!==void 0&&a!==null?String(a):"");else o.set(s,a!==void 0&&a!==null?Re(String(a)):"")}catch{o.set(s,"")}return{html:go(e.html,o),context:r}}async function Pp(e,t={}){if(!e.hasServerScripts&&!Gt(e.fragment))return e.fragment;let r={__filename:e.sourceFile,__dirname:e.sourceFile.replace(/[/\\][^/\\]+$/,""),...t};for(let o of e.serverScriptContent)try{await te(o,r,e.sourceFile)}catch(s){console.warn(`[stx] Server script error in ${e.sourceFile}:`,s)}if(!Gt(e.fragment))return e.fragment;let n=new Map;for(let[o,s]of Object.entries(e.placeholders))if(s.expression)try{let i=yo(s.expression,r);if(s.type==="raw")n.set(o,i!==void 0&&i!==null?String(i):"");else n.set(o,i!==void 0&&i!==null?Re(String(i)):"")}catch{n.set(o,"")}return go(e.fragment,n)}var Ip={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function Av(e={}){let t=dt.resolve(e.outputDir||".output"),r=e.port||3000,n=xi(t);if(!n)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${n.routes.length} routes...`);let o=new Map,s=new Map,i=new Map,a=new Map;for(let u of n.routes)try{let p=dt.join(t,u.compiledPath),h=JSON.parse(await Bun.file(p).text());o.set(u.pattern,h),i.set(u.pattern,Hr(h.html)),a.set(u.pattern,Wr(h.html));let f=dt.join(t,u.fragmentPath);if(await Bun.file(f).exists())s.set(u.pattern,await Bun.file(f).text())}catch(p){console.warn(`[stx] Failed to load route ${u.pattern}:`,p)}let c=new Map,l=[];for(let u of n.routes)if(u.hasParams){let{regex:p,params:h}=xo(u.pattern);l.push({regex:p,route:u,paramNames:h})}else c.set(u.pattern,u);let d=Op({port:r,async fetch(u){return wt(u,await(async()=>{let p=new URL(u.url).pathname;if(e.onRequest){let b=await e.onRequest(u);if(b)return b}if(e.apiRoutes?.[p])return e.apiRoutes[p](u);if((u.method==="GET"||u.method==="HEAD")&&p!=="/"){let b=dt.resolve(t,"public"),w;try{w=decodeURIComponent(p)}catch{w=p}if(!w.includes("\x00")){let v=dt.resolve(b,`.${w}`);if(v===b||v.startsWith(`${b}${dt.sep}`))try{if(yi.existsSync(v)&&yi.statSync(v).isFile()){let S=dt.extname(v).toLowerCase(),T=Ip[S]||"application/octet-stream",C=p.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(p);return new Response(Bun.file(v),{headers:{"Content-Type":T,"Cache-Control":C?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let h=u.headers.get("X-STX-Router")==="true",f=null,g={};if(f=c.get(p)||null,!f)for(let{regex:b,route:w,paramNames:v}of l){let S=p.match(b);if(S){f=w,v.forEach((T,C)=>{g[T]=S[C+1]});break}}if(!f){let b=c.get("/404")||null;if(b){let w=o.get(b.pattern);if(w)return new Response(w.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}if(h){let b=s.get(f.pattern);if(b){let w=i.get(f.pattern);return new Response(b,{headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...a.has(f.pattern)?{"X-STX-Runtime":a.get(f.pattern)?"true":"false"}:{},...w?{"X-STX-Layout":w.layout,"X-STX-Layout-Group":w.group}:{},"Cache-Control":"no-cache"}})}}let x=fo(u.method),y=o.get(f.pattern);if(!y){let b=c.get("/500")||null;if(b){let w=o.get(b.pattern);if(w)return new Response(w.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(!x&&!y.hasServerScripts&&Object.keys(y.placeholders).length===0)return new Response(y.html,{headers:{"Content-Type":"text/html","Cache-Control":"public, max-age=60"}});try{let{html:b,boundaries:w,redirect:v}=await hi(y,{params:g,request:u,method:u.method});if(v)return pi(v);if(w&&w.length>0){let{renderStreamingPage:S,streamToResponse:T}=await import("./chunk-edrtesh7.js");return T(S(b,w,{timeoutMs:30000}),{headers:{"Cache-Control":"no-cache"}})}return new Response(b,{headers:{"Content-Type":"text/html","Cache-Control":"no-cache"}})}catch(b){return console.error(`[stx] Hydration error for ${p}:`,b),new Response(y.html,{headers:{"Content-Type":"text/html"}})}})())}});return console.log(`[stx] Production server running at http://localhost:${r}`),console.log(`[stx] Serving ${n.routes.length} routes (${o.size} pre-loaded)`),{port:r,stop:()=>d.stop()}}var Rv="f9c3713";import{existsSync as Zt,mkdirSync as bo}from"fs";import{join as Ge,dirname as Lp,basename as Ov}from"path";import{execSync as bi}from"child_process";var Lv={default:{description:"Standard stx project with pages, components, and stores",features:["Pages","Components","Layouts","Stores","Dev server"]},minimal:{description:"Minimal setup with just the essentials",features:["Single page","Basic styles"]},full:{description:"Full-featured project with all stx capabilities",features:["Pages","Components","Layouts","Stores","API routes","PWA","i18n","Testing"]},blog:{description:"Blog template with markdown support",features:["Blog layout","Post pages","Tags","RSS feed","Markdown"]},dashboard:{description:"Admin dashboard template",features:["Sidebar","Charts","Tables","Forms","Auth pages"]},landing:{description:"Marketing landing page template",features:["Hero section","Features","Pricing","CTA","Contact form"]}};async function Fv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.template||"default",o=Ge(process.cwd(),e);if(Zt(o))return r.success=!1,r.message=`Directory ${e} already exists`,r;try{bo(o,{recursive:!0});let s=Fp(n);for(let a of s)bo(Ge(o,a),{recursive:!0});let i=Np(n,e,t);for(let[a,c]of Object.entries(i)){let l=Ge(o,a);Qt(Lp(l)),await Bun.write(l,c),r.files.push(a)}if(!t.skipGit)try{bi("git init",{cwd:o,stdio:"ignore"}),await Bun.write(Ge(o,".gitignore"),Jp()),r.files.push(".gitignore")}catch{r.errors.push("Failed to initialize git repository")}if(!t.skipInstall){let a=t.packageManager||gf();try{console.log(`
2450
- Installing dependencies with ${a}...`),bi(`${a} install`,{cwd:o,stdio:"inherit"})}catch{r.errors.push("Failed to install dependencies")}}r.message=`Created project: ${e}`,console.log(`
2449
+ `)}async runPluginHook(e,t){if(!this.config.plugins)return;for(let r of this.config.plugins){let n=r[e];if(typeof n==="function")await n.call(r,t||this)}}async runPluginTransform(e,t){if(!this.config.plugins)return e;let r=e;for(let n of this.config.plugins)if(n.transform){let o=await n.transform(r,t);if(o!=null)r=o}return r}generateHash(e){return Ap("sha256").update(e).digest("hex")}getOutputName(e,t,r){let n=t==="html"?".html":t==="css"?".css":t==="js"?".js":"";return`${e}.${r.slice(0,8)}${n}`}formatSize(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(2)} KB`;return`${(e/1048576).toFixed(2)} MB`}ensureDir(e){if(!Yt(e))jp(e,{recursive:!0})}walkDir(e,t){if(!Yt(e))return;let r=Mp(e,{withFileTypes:!0});for(let n of r){let o=De(e,n.name);if(n.isDirectory())this.walkDir(o,t);else t(o)}}getResult(){let e=Date.now()-this.startTime,t=this.outputs.reduce((n,o)=>n+o.size,0),r=this.outputs.reduce((n,o)=>n+(o.gzipSize||0),0);return{outputs:this.outputs,duration:e,totalSize:t,gzipSize:r,chunks:this.chunks,assets:this.assets,warnings:this.warnings,errors:this.errors}}}async function dv(e){return new go(e).build()}function uv(e){return new go(e)}function pv(e){return{...hi,...e}}import xi from"fs";import ut from"path";var{serve:Ip}=globalThis.Bun;async function xv(e,t={}){return(await yi(e,t)).html}async function gi(e,t={}){let{html:r,context:n,redirect:o}=await yi(e,t);if(o)return{html:r,redirect:o};let{extractStreamBoundaries:s}=await import("./chunk-5f0d9j9a.js"),i=s(n),a=e.streamTemplates;if(a&&Object.keys(a).length>0){let{processDirectives:c}=await import("./chunk-dntnakjy.js"),{defaultConfig:l}=await import("./chunk-bfjwn7yg.js"),d=n.streamBoundaries||{},u={...l,autoShell:!1},p=Object.keys(a).map((f)=>({id:f,render:async()=>{let g=typeof d[f]==="function"?await d[f]():void 0;return c(a[f],{...n,$boundary:g},e.sourceFile,u,new Set)}})),h=new Set(p.map((f)=>f.id));i=[...(i||[]).filter((f)=>!h.has(f.id)),...p]}return{html:r,boundaries:i&&i.length>0?i:void 0}}async function yi(e,t){let r={__filename:e.sourceFile,__dirname:e.sourceFile.replace(/[/\\][^/\\]+$/,""),...t};if(!e.hasServerScripts&&!Zt(e.html))return{html:e.html,context:r};for(let s of e.serverScriptContent)try{await re(s,r,e.sourceFile)}catch(i){console.warn(`[stx] Server script error in ${e.sourceFile}:`,i)}let n=await pi(r,{request:t.request,method:t.method,params:t.params??{},cookies:t.cookies??{}});if(n.redirect)return{html:e.html,context:r,redirect:n.redirect};if(!Zt(e.html))return{html:e.html,context:r};let o=new Map;for(let[s,i]of Object.entries(e.placeholders))if(i.expression)try{let a=xo(i.expression,r);if(i.type==="raw")o.set(s,a!==void 0&&a!==null?String(a):"");else o.set(s,a!==void 0&&a!==null?Me(String(a)):"")}catch{o.set(s,"")}return{html:yo(e.html,o),context:r}}async function Op(e,t={}){if(!e.hasServerScripts&&!Zt(e.fragment))return e.fragment;let r={__filename:e.sourceFile,__dirname:e.sourceFile.replace(/[/\\][^/\\]+$/,""),...t};for(let o of e.serverScriptContent)try{await re(o,r,e.sourceFile)}catch(s){console.warn(`[stx] Server script error in ${e.sourceFile}:`,s)}if(!Zt(e.fragment))return e.fragment;let n=new Map;for(let[o,s]of Object.entries(e.placeholders))if(s.expression)try{let i=xo(s.expression,r);if(s.type==="raw")n.set(o,i!==void 0&&i!==null?String(i):"");else n.set(o,i!==void 0&&i!==null?Me(String(i)):"")}catch{n.set(o,"")}return yo(e.fragment,n)}var Lp={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function jv(e={}){let t=ut.resolve(e.outputDir||".output"),r=e.port||3000,n=bi(t);if(!n)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${n.routes.length} routes...`);let o=new Map,s=new Map,i=new Map,a=new Map;for(let u of n.routes)try{let p=ut.join(t,u.compiledPath),h=JSON.parse(await Bun.file(p).text());o.set(u.pattern,h),i.set(u.pattern,Wr(h.html)),a.set(u.pattern,Vr(h.html));let f=ut.join(t,u.fragmentPath);if(await Bun.file(f).exists())s.set(u.pattern,await Bun.file(f).text())}catch(p){console.warn(`[stx] Failed to load route ${u.pattern}:`,p)}let c=new Map,l=[];for(let u of n.routes)if(u.hasParams){let{regex:p,params:h}=bo(u.pattern);l.push({regex:p,route:u,paramNames:h})}else c.set(u.pattern,u);let d=Ip({port:r,async fetch(u){return vt(u,await(async()=>{let p=new URL(u.url).pathname;if(e.onRequest){let b=await e.onRequest(u);if(b)return b}if(e.apiRoutes?.[p])return e.apiRoutes[p](u);if((u.method==="GET"||u.method==="HEAD")&&p!=="/"){let b=ut.resolve(t,"public"),w;try{w=decodeURIComponent(p)}catch{w=p}if(!w.includes("\x00")){let v=ut.resolve(b,`.${w}`);if(v===b||v.startsWith(`${b}${ut.sep}`))try{if(xi.existsSync(v)&&xi.statSync(v).isFile()){let k=ut.extname(v).toLowerCase(),C=Lp[k]||"application/octet-stream",E=p.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(p);return new Response(Bun.file(v),{headers:{"Content-Type":C,"Cache-Control":E?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let h=u.headers.get("X-STX-Router")==="true",f=null,g={};if(f=c.get(p)||null,!f)for(let{regex:b,route:w,paramNames:v}of l){let k=p.match(b);if(k){f=w,v.forEach((C,E)=>{g[C]=k[E+1]});break}}if(!f){let b=c.get("/404")||null;if(b){let w=o.get(b.pattern);if(w)return new Response(w.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}if(h){let b=s.get(f.pattern);if(b){let w=i.get(f.pattern);return new Response(b,{headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...a.has(f.pattern)?{"X-STX-Runtime":a.get(f.pattern)?"true":"false"}:{},...w?{"X-STX-Layout":w.layout,"X-STX-Layout-Group":w.group}:{},"Cache-Control":"no-cache"}})}}let x=mo(u.method),y=o.get(f.pattern);if(!y){let b=c.get("/500")||null;if(b){let w=o.get(b.pattern);if(w)return new Response(w.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(!x&&!y.hasServerScripts&&Object.keys(y.placeholders).length===0)return new Response(y.html,{headers:{"Content-Type":"text/html","Cache-Control":"public, max-age=60"}});try{let{html:b,boundaries:w,redirect:v}=await gi(y,{params:g,request:u,method:u.method});if(v)return fi(v);if(w&&w.length>0){let{renderStreamingPage:k,streamToResponse:C}=await import("./chunk-5f0d9j9a.js");return C(k(b,w,{timeoutMs:30000}),{headers:{"Cache-Control":"no-cache"}})}return new Response(b,{headers:{"Content-Type":"text/html","Cache-Control":"no-cache"}})}catch(b){return console.error(`[stx] Hydration error for ${p}:`,b),new Response(y.html,{headers:{"Content-Type":"text/html"}})}})())}});return console.log(`[stx] Production server running at http://localhost:${r}`),console.log(`[stx] Serving ${n.routes.length} routes (${o.size} pre-loaded)`),{port:r,stop:()=>d.stop()}}var Mv="f9c3713";import{existsSync as Qt,mkdirSync as wo}from"fs";import{join as Ze,dirname as Fp,basename as Iv}from"path";import{execSync as wi}from"child_process";var Fv={default:{description:"Standard stx project with pages, components, and stores",features:["Pages","Components","Layouts","Stores","Dev server"]},minimal:{description:"Minimal setup with just the essentials",features:["Single page","Basic styles"]},full:{description:"Full-featured project with all stx capabilities",features:["Pages","Components","Layouts","Stores","API routes","PWA","i18n","Testing"]},blog:{description:"Blog template with markdown support",features:["Blog layout","Post pages","Tags","RSS feed","Markdown"]},dashboard:{description:"Admin dashboard template",features:["Sidebar","Charts","Tables","Forms","Auth pages"]},landing:{description:"Marketing landing page template",features:["Hero section","Features","Pricing","CTA","Contact form"]}};async function Nv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.template||"default",o=Ze(process.cwd(),e);if(Qt(o))return r.success=!1,r.message=`Directory ${e} already exists`,r;try{wo(o,{recursive:!0});let s=Np(n);for(let a of s)wo(Ze(o,a),{recursive:!0});let i=Bp(n,e,t);for(let[a,c]of Object.entries(i)){let l=Ze(o,a);er(Fp(l)),await Bun.write(l,c),r.files.push(a)}if(!t.skipGit)try{wi("git init",{cwd:o,stdio:"ignore"}),await Bun.write(Ze(o,".gitignore"),Yp()),r.files.push(".gitignore")}catch{r.errors.push("Failed to initialize git repository")}if(!t.skipInstall){let a=t.packageManager||yf();try{console.log(`
2450
+ Installing dependencies with ${a}...`),wi(`${a} install`,{cwd:o,stdio:"inherit"})}catch{r.errors.push("Failed to install dependencies")}}r.message=`Created project: ${e}`,console.log(`
2451
2451
  \u2705 ${r.message}
2452
2452
 
2453
2453
  Next steps:
2454
2454
  cd ${e}
2455
2455
  ${t.packageManager||"bun"} run dev
2456
- `)}catch(s){r.success=!1,r.message=`Failed to create project: ${s}`}return r}function Fp(e){let t=["pages","components","layouts","partials","public"];switch(e){case"minimal":return["src","public"];case"full":return[...t,"src/stores","src/api","src/i18n","src/utils","test"];case"blog":return[...t,"src/posts","src/utils"];case"dashboard":return[...t,"src/stores","src/api","src/utils"];case"landing":return[...t,"src/sections"];default:return[...t,"src/stores"]}}function Np(e,t,r){let n={};if(n["package.json"]=Wp(t,e,r),n["stx.config.ts"]=Vp(e,r),n["README.md"]=Xp(t,e),r.typescript!==!1)n["tsconfig.json"]=qp();switch(e){case"minimal":n["src/index.stx"]=Yp();break;case"blog":n["pages/index.stx"]=Qp(),n["pages/[slug].stx"]=ef(),n["layouts/app.stx"]=tf(),n["components/PostCard.stx"]=rf();break;case"dashboard":n["pages/index.stx"]=nf(),n["pages/settings.stx"]=of(),n["layouts/app.stx"]=sf(),n["components/Sidebar.stx"]=af(),n["components/StatsCard.stx"]=cf(),n["src/stores/dashboard.ts"]=lf();break;case"landing":n["pages/index.stx"]=df(),n["layouts/app.stx"]=uf(),n["src/sections/Hero.stx"]=pf(),n["src/sections/Features.stx"]=ff(),n["src/sections/Pricing.stx"]=mf(),n["components/Button.stx"]=hf();break;case"full":n["pages/index.stx"]=wi(),n["pages/about.stx"]=Kp(),n["layouts/app.stx"]=vi(),n["components/Header.stx"]=$i(),n["components/Footer.stx"]=Si(),n["src/stores/app.ts"]=ki(),n["src/i18n/en.json"]=Gp("en"),n["test/example.test.ts"]=Zp();break;default:n["pages/index.stx"]=wi(),n["layouts/app.stx"]=vi(),n["components/Header.stx"]=$i(),n["components/Footer.stx"]=Si(),n["src/stores/app.ts"]=ki()}return n}async function Nv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"components",o=wo(e),s=Ge(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Component ${o} already exists. Use --force to overwrite.`,r;try{Qt(n);let i=Bp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created component: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create component: ${i}`}return r}async function Bv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"pages",o=e.toLowerCase().replace(/\s+/g,"-"),s=Ge(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Page ${o} already exists. Use --force to overwrite.`,r;try{Qt(n);let i=zp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created page: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create page: ${i}`}return r}async function zv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"src/stores",o=yf(e),s=Ge(n,`${o}.ts`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Store ${o} already exists. Use --force to overwrite.`,r;try{Qt(n);let i=Up(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created store: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create store: ${i}`}return r}async function Uv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"layouts",o=e.toLowerCase().replace(/\s+/g,"-"),s=Ge(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Layout ${o} already exists. Use --force to overwrite.`,r;try{Qt(n);let i=Hp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created layout: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create layout: ${i}`}return r}function Bp(e,t){let r=[];if(r.push(`{{-- Component: ${e} --}}`),t.props!==!1)r.push(`<script>
2456
+ `)}catch(s){r.success=!1,r.message=`Failed to create project: ${s}`}return r}function Np(e){let t=["pages","components","layouts","partials","public"];switch(e){case"minimal":return["src","public"];case"full":return[...t,"src/stores","src/api","src/i18n","src/utils","test"];case"blog":return[...t,"src/posts","src/utils"];case"dashboard":return[...t,"src/stores","src/api","src/utils"];case"landing":return[...t,"src/sections"];default:return[...t,"src/stores"]}}function Bp(e,t,r){let n={};if(n["package.json"]=Vp(t,e,r),n["stx.config.ts"]=qp(e,r),n["README.md"]=Jp(t,e),r.typescript!==!1)n["tsconfig.json"]=Xp();switch(e){case"minimal":n["src/index.stx"]=Kp();break;case"blog":n["pages/index.stx"]=ef(),n["pages/[slug].stx"]=tf(),n["layouts/app.stx"]=rf(),n["components/PostCard.stx"]=nf();break;case"dashboard":n["pages/index.stx"]=of(),n["pages/settings.stx"]=sf(),n["layouts/app.stx"]=af(),n["components/Sidebar.stx"]=cf(),n["components/StatsCard.stx"]=lf(),n["src/stores/dashboard.ts"]=df();break;case"landing":n["pages/index.stx"]=uf(),n["layouts/app.stx"]=pf(),n["src/sections/Hero.stx"]=ff(),n["src/sections/Features.stx"]=mf(),n["src/sections/Pricing.stx"]=hf(),n["components/Button.stx"]=gf();break;case"full":n["pages/index.stx"]=vi(),n["pages/about.stx"]=Gp(),n["layouts/app.stx"]=$i(),n["components/Header.stx"]=Si(),n["components/Footer.stx"]=ki(),n["src/stores/app.ts"]=Ti(),n["src/i18n/en.json"]=Zp("en"),n["test/example.test.ts"]=Qp();break;default:n["pages/index.stx"]=vi(),n["layouts/app.stx"]=$i(),n["components/Header.stx"]=Si(),n["components/Footer.stx"]=ki(),n["src/stores/app.ts"]=Ti()}return n}async function Bv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"components",o=vo(e),s=Ze(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Component ${o} already exists. Use --force to overwrite.`,r;try{er(n);let i=zp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created component: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create component: ${i}`}return r}async function zv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"pages",o=e.toLowerCase().replace(/\s+/g,"-"),s=Ze(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Page ${o} already exists. Use --force to overwrite.`,r;try{er(n);let i=Up(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created page: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create page: ${i}`}return r}async function Uv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"src/stores",o=xf(e),s=Ze(n,`${o}.ts`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Store ${o} already exists. Use --force to overwrite.`,r;try{er(n);let i=Hp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created store: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create store: ${i}`}return r}async function Hv(e,t={}){let r={success:!0,message:"",files:[],errors:[]},n=t.dir||"layouts",o=e.toLowerCase().replace(/\s+/g,"-"),s=Ze(n,`${o}.stx`);if(await Bun.file(s).exists()&&!t.force)return r.success=!1,r.message=`Layout ${o} already exists. Use --force to overwrite.`,r;try{er(n);let i=Wp(o,t);await Bun.write(s,i),r.files.push(s),r.message=`Created layout: ${s}`,console.log(`\u2705 ${r.message}`)}catch(i){r.success=!1,r.message=`Failed to create layout: ${i}`}return r}function zp(e,t){let r=[];if(r.push(`{{-- Component: ${e} --}}`),t.props!==!1)r.push(`<script>
2457
2457
  // Props
2458
2458
  const title = props.title || '${e}'
2459
2459
  const variant = props.variant || 'default'
2460
2460
  </script>
2461
- `);if(r.push(`<div class="${ut(e)} ${ut(e)}--{{ variant }}">
2461
+ `);if(r.push(`<div class="${pt(e)} ${pt(e)}--{{ variant }}">
2462
2462
  <h3>{{ title }}</h3>
2463
- <div class="${ut(e)}__content">
2463
+ <div class="${pt(e)}__content">
2464
2464
  {{ slot }}
2465
2465
  </div>
2466
2466
  </div>`),t.styles!==!1)r.push(`
2467
2467
  <style scoped>
2468
- .${ut(e)} {
2468
+ .${pt(e)} {
2469
2469
  padding: 1rem;
2470
2470
  border-radius: 8px;
2471
2471
  background: #f8f9fa;
2472
2472
  }
2473
2473
 
2474
- .${ut(e)}--primary {
2474
+ .${pt(e)}--primary {
2475
2475
  border-left: 3px solid #3498db;
2476
2476
  }
2477
2477
 
2478
- .${ut(e)}--success {
2478
+ .${pt(e)}--success {
2479
2479
  border-left: 3px solid #2ecc71;
2480
2480
  }
2481
2481
 
2482
- .${ut(e)}__content {
2482
+ .${pt(e)}__content {
2483
2483
  margin-top: 0.5rem;
2484
2484
  }
2485
2485
  </style>`);return r.join(`
2486
- `)}function zp(e,t){let r=wo(e.replace(/-/g," ")),n=[];if(n.push(`<script>
2486
+ `)}function Up(e,t){let r=vo(e.replace(/-/g," ")),n=[];if(n.push(`<script>
2487
2487
  const title = '${r}'
2488
2488
  const description = 'Page description'
2489
2489
  </script>
@@ -2496,7 +2496,7 @@ const description = 'Page description'
2496
2496
  <p>{{ description }}</p>
2497
2497
  </div>
2498
2498
  @endsection`),n.join(`
2499
- `)}function Up(e,t){let r=`${e}Store`,n=`${wo(e)}State`,o=`import { defineStore } from 'stx'
2499
+ `)}function Hp(e,t){let r=`${e}Store`,n=`${vo(e)}State`,o=`import { defineStore } from 'stx'
2500
2500
 
2501
2501
  interface ${n} {
2502
2502
  // Add your state properties here
@@ -2544,7 +2544,7 @@ finally {
2544
2544
  ],
2545
2545
  },
2546
2546
  `;return o+=`})
2547
- `,o}function Hp(e,t){let r=`<!DOCTYPE html>
2547
+ `,o}function Wp(e,t){let r=`<!DOCTYPE html>
2548
2548
  <html lang="en">
2549
2549
  <head>
2550
2550
  <meta charset="UTF-8">
@@ -2591,7 +2591,7 @@ finally {
2591
2591
 
2592
2592
  `;return r+=` @yield('scripts')
2593
2593
  </body>
2594
- </html>`,r}function Wp(e,t,r){let n={name:e,version:"0.0.1",type:"module",scripts:{dev:"stx dev pages/index.stx",build:"stx build",preview:"stx serve dist"},dependencies:{stx:"latest"},devDependencies:{}};if(r.typescript!==!1)n.devDependencies.typescript="^5.0.0";if(r.tailwind)n.devDependencies.tailwindcss="^3.0.0";if(t==="full")n.scripts.test="bun test",n.scripts.lint="bun run lint";return JSON.stringify(n,null,2)}function Vp(e,t){return`import { defineConfig } from 'stx'
2594
+ </html>`,r}function Vp(e,t,r){let n={name:e,version:"0.0.1",type:"module",scripts:{dev:"stx dev pages/index.stx",build:"stx build",preview:"stx serve dist"},dependencies:{stx:"latest"},devDependencies:{}};if(r.typescript!==!1)n.devDependencies.typescript="^5.0.0";if(r.tailwind)n.devDependencies.tailwindcss="^3.0.0";if(t==="full")n.scripts.test="bun test",n.scripts.lint="bun run lint";return JSON.stringify(n,null,2)}function qp(e,t){return`import { defineConfig } from 'stx'
2595
2595
 
2596
2596
  export default defineConfig({
2597
2597
  // Template directories
@@ -2612,7 +2612,7 @@ ${t.pwa?` pwa: { enabled: true },
2612
2612
  // Analytics (configure when ready)
2613
2613
  // analytics: { enabled: true, driver: 'fathom', fathom: { siteId: 'YOUR_SITE_ID' } },
2614
2614
  })
2615
- `}function qp(){return JSON.stringify({compilerOptions:{target:"ESNext",module:"ESNext",moduleResolution:"bundler",strict:!0,skipLibCheck:!0,esModuleInterop:!0,types:["bun-types"]},include:["src/**/*","test/**/*"]},null,2)}function Xp(e,t){return`# ${e}
2615
+ `}function Xp(){return JSON.stringify({compilerOptions:{target:"ESNext",module:"ESNext",moduleResolution:"bundler",strict:!0,skipLibCheck:!0,esModuleInterop:!0,types:["bun-types"]},include:["src/**/*","test/**/*"]},null,2)}function Jp(e,t){return`# ${e}
2616
2616
 
2617
2617
  A stx project created with the \`${t}\` template.
2618
2618
 
@@ -2644,7 +2644,7 @@ src/
2644
2644
 
2645
2645
  - [stx Documentation](https://stx.dev/docs)
2646
2646
  - [stx GitHub](https://github.com/stacksjs/stx)
2647
- `}function Jp(){return`# Dependencies
2647
+ `}function Yp(){return`# Dependencies
2648
2648
  node_modules/
2649
2649
  .bun/
2650
2650
 
@@ -2669,7 +2669,7 @@ Thumbs.db
2669
2669
 
2670
2670
  # Logs
2671
2671
  *.log
2672
- `}function Yp(){return`<!DOCTYPE html>
2672
+ `}function Kp(){return`<!DOCTYPE html>
2673
2673
  <html lang="en">
2674
2674
  <head>
2675
2675
  <meta charset="UTF-8">
@@ -2685,7 +2685,7 @@ Thumbs.db
2685
2685
  <p>Edit <code>src/index.stx</code> to get started.</p>
2686
2686
  </body>
2687
2687
  </html>
2688
- `}function wi(){return`<script>
2688
+ `}function vi(){return`<script>
2689
2689
  const title = 'Welcome to stx'
2690
2690
  const features = [
2691
2691
  { icon: '\u26A1', name: 'Fast', desc: 'Built on Bun for blazing speed' },
@@ -2714,7 +2714,7 @@ const features = [
2714
2714
  @endforeach
2715
2715
  </div>
2716
2716
  @endsection
2717
- `}function Kp(){return`<script>
2717
+ `}function Gp(){return`<script>
2718
2718
  const title = 'About'
2719
2719
  </script>
2720
2720
 
@@ -2726,7 +2726,7 @@ const title = 'About'
2726
2726
  <h1>{{ title }}</h1>
2727
2727
  <p>This is the about page.</p>
2728
2728
  @endsection
2729
- `}function vi(){return`<!DOCTYPE html>
2729
+ `}function $i(){return`<!DOCTYPE html>
2730
2730
  <html lang="en">
2731
2731
  <head>
2732
2732
  <meta charset="UTF-8">
@@ -2749,7 +2749,7 @@ const title = 'About'
2749
2749
  @yield('scripts')
2750
2750
  </body>
2751
2751
  </html>
2752
- `}function $i(){return`<header class="header">
2752
+ `}function Si(){return`<header class="header">
2753
2753
  <nav class="nav container">
2754
2754
  <a href="/" class="logo">stx</a>
2755
2755
  <div class="nav-links">
@@ -2766,7 +2766,7 @@ const title = 'About'
2766
2766
  .nav-links a { color: rgba(255,255,255,0.8); margin-left: 1.5rem; text-decoration: none; }
2767
2767
  .nav-links a:hover { color: white; }
2768
2768
  </style>
2769
- `}function Si(){return`<footer class="footer">
2769
+ `}function ki(){return`<footer class="footer">
2770
2770
  <div class="container">
2771
2771
  <p>&copy; {{ new Date().getFullYear() }} Built with stx</p>
2772
2772
  </div>
@@ -2775,7 +2775,7 @@ const title = 'About'
2775
2775
  <style scoped>
2776
2776
  .footer { background: #f8f9fa; padding: 2rem 0; margin-top: 4rem; text-align: center; color: #666; }
2777
2777
  </style>
2778
- `}function ki(){return`import { defineStore } from 'stx'
2778
+ `}function Ti(){return`import { defineStore } from 'stx'
2779
2779
 
2780
2780
  interface AppState {
2781
2781
  theme: 'light' | 'dark'
@@ -2802,14 +2802,14 @@ export const appStore = defineStore('app', {
2802
2802
  strategies: [{ key: 'app-preferences', storage: localStorage }],
2803
2803
  },
2804
2804
  })
2805
- `}function Gp(e){return JSON.stringify({common:{welcome:"Welcome",home:"Home",about:"About",contact:"Contact"},messages:{loading:"Loading...",error:"An error occurred"}},null,2)}function Zp(){return`import { describe, expect, it } from 'bun:test'
2805
+ `}function Zp(e){return JSON.stringify({common:{welcome:"Welcome",home:"Home",about:"About",contact:"Contact"},messages:{loading:"Loading...",error:"An error occurred"}},null,2)}function Qp(){return`import { describe, expect, it } from 'bun:test'
2806
2806
 
2807
2807
  describe('Example', () => {
2808
2808
  it('should work', () => {
2809
2809
  expect(1 + 1).toBe(2)
2810
2810
  })
2811
2811
  })
2812
- `}function Qp(){return"<!-- Blog index -->"}function ef(){return"<!-- Blog post -->"}function tf(){return`<!DOCTYPE html>
2812
+ `}function ef(){return"<!-- Blog index -->"}function tf(){return"<!-- Blog post -->"}function rf(){return`<!DOCTYPE html>
2813
2813
  <html lang="en">
2814
2814
  <head>
2815
2815
  <meta charset="UTF-8">
@@ -2849,7 +2849,7 @@ describe('Example', () => {
2849
2849
  </footer>
2850
2850
  @yield('scripts')
2851
2851
  </body>
2852
- </html>`}function rf(){return"<!-- Post card -->"}function nf(){return"<!-- Dashboard index -->"}function of(){return"<!-- Settings -->"}function sf(){return`<!DOCTYPE html>
2852
+ </html>`}function nf(){return"<!-- Post card -->"}function of(){return"<!-- Dashboard index -->"}function sf(){return"<!-- Settings -->"}function af(){return`<!DOCTYPE html>
2853
2853
  <html lang="en">
2854
2854
  <head>
2855
2855
  <meta charset="UTF-8">
@@ -2885,7 +2885,7 @@ describe('Example', () => {
2885
2885
  </div>
2886
2886
  @yield('scripts')
2887
2887
  </body>
2888
- </html>`}function af(){return"<!-- Sidebar -->"}function cf(){return"<!-- Stats card -->"}function lf(){return"// Dashboard store"}function df(){return"<!-- Landing page -->"}function uf(){return`<!DOCTYPE html>
2888
+ </html>`}function cf(){return"<!-- Sidebar -->"}function lf(){return"<!-- Stats card -->"}function df(){return"// Dashboard store"}function uf(){return"<!-- Landing page -->"}function pf(){return`<!DOCTYPE html>
2889
2889
  <html lang="en">
2890
2890
  <head>
2891
2891
  <meta charset="UTF-8">
@@ -2920,31 +2920,31 @@ describe('Example', () => {
2920
2920
  </footer>
2921
2921
  @yield('scripts')
2922
2922
  </body>
2923
- </html>`}function pf(){return"<!-- Hero section -->"}function ff(){return"<!-- Features -->"}function mf(){return"<!-- Pricing -->"}function hf(){return"<!-- Button -->"}function Qt(e){if(!Zt(e))bo(e,{recursive:!0})}function gf(){if(Zt("bun.lockb"))return"bun";if(Zt("pnpm-lock.yaml"))return"pnpm";if(Zt("yarn.lock"))return"yarn";return"bun"}function wo(e){return e.replace(/[-_\s]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^./,(t)=>t.toUpperCase())}function yf(e){return e.replace(/[-_\s]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^./,(t)=>t.toLowerCase())}function ut(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}var{serve:xf}=globalThis.Bun;import er from"fs";import Ze from"path";function Zv(e,t=200,r={}){return new Response(e,{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...r}})}async function bf(e={}){let{port:t=3000,root:r=".",stxOptions:n={},watch:o=!0,onRequest:s,routes:i={},middleware:a=[],on404:c,onError:l}=e,d=Ze.resolve(r),u=new Map;async function p(b){let w=er.statSync(b),v=`${b}:${w.mtimeMs}`,S=u.get(v);if(S)return S.content;for(let _ of u.keys())if(_.startsWith(`${b}:`)&&_!==v)u.delete(_);let T=await Bun.file(b).text(),C=T,j=kt(T);if(j)C=j.content.trim();let k=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,L=[],X=[],K;while((K=k.exec(T))!==null){let _=K[1],E=K[2],A=K[0];if(_.includes("server"))X.push(E);else L.push(A)}let ne=T.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi)||[],ye=C.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),oe={__filename:b,__dirname:Ze.dirname(b)};for(let _ of X)await te(_,oe,b);let G=await se(ye,oe,b,n,new Set);if(ne.length>0){let _=ne.join(`
2924
- `);if(G.match(/(<\/head>)/i))G=G.replace(/(<\/head>)/i,`${_}
2925
- $1`)}if(L.length>0){let{interpolateScriptsInTemplate:_}=await import("./chunk-fjzye4qj.js"),E=_(L.join(`
2926
- `),oe);if(G.match(/(<\/body>)/i))G=G.replace(/(<\/body>)/i,`${E}
2927
- $1`);else G+=`
2928
- ${E}`}return u.set(v,{content:G,mtime:w.mtimeMs}),G}async function h(b){let w=er.statSync(b),v=`${b}:${w.mtimeMs}`,S=u.get(v);if(S)return S.content;let{content:T}=await $e(b,n);return u.set(v,{content:T,mtime:w.mtimeMs}),T}function f(b){let w=b.startsWith("/")?b.slice(1):b,v=[w,`${w}.stx`,`${w}.md`,`${w}.html`,Ze.join(w,"index.stx"),Ze.join(w,"index.md"),Ze.join(w,"index.html")];for(let S of v){let T=Ze.join(d,S);if(er.existsSync(T)&&er.statSync(T).isFile())return T}return null}async function g(b){let w=new URL(b.url),v=async()=>{if(i[w.pathname])return await i[w.pathname](b);if(s){let T=await s(b);if(T)return T}let S=f(w.pathname);if(!S){if(c)return await c(b);return new Response("Not Found",{status:404})}try{let T,C="text/html";if(S.endsWith(".stx"))T=await p(S);else if(S.endsWith(".md"))T=await h(S);else if(S.endsWith(".html"))T=await Bun.file(S).text();else if(S.endsWith(".css"))T=await Bun.file(S).text(),C="text/css";else if(S.endsWith(".js"))T=await Bun.file(S).text(),C="text/javascript";else if(S.endsWith(".json"))T=await Bun.file(S).text(),C="application/json";else return new Response(Bun.file(S));return new Response(T,{headers:{"Content-Type":C}})}catch(T){if(l)return await l(T,b);let C=T instanceof Error?T.message:String(T),j=n?.debug===!0?`<h1>Error</h1><pre>${C}
2929
- ${T instanceof Error?T.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An error occurred while processing your request.</p>";return new Response(j,{status:500,headers:{"Content-Type":"text/html"}})}};for(let S=a.length-1;S>=0;S--){let T=a[S],C=v;v=async()=>await T(b,C)}return await v()}let x=xf({port:t,fetch:async(b)=>wt(b,await g(b))}),y=null;if(o)y=er.watch(d,{recursive:!0},(b,w)=>{if(w&&(w.endsWith(".stx")||w.endsWith(".md")||w.endsWith(".html")))u.clear()});return{server:x,url:x.url.toString(),stop(){if(y)y.close();x.stop()}}}async function Qv(e,t={}){let r=Ze.resolve(e);if(!await Bun.file(r).exists())throw Error(`File not found: ${r}`);let n=r.endsWith(".md"),o=r.endsWith(".stx");if(!n&&!o)throw Error(`Unsupported file type: ${r}. Only .stx and .md files are supported.`);return await bf({...t,root:Ze.dirname(r),routes:{"/":async()=>{let s;if(n){let{content:i}=await $e(r,t.stxOptions);s=i}else{let i=await Bun.file(r).text(),a=[],c=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,l;while((l=c.exec(i))!==null)if(l[1].includes("server"))a.push(l[2]);let d=a.join(`
2930
- `),u=i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),p={};if(d.trim())await te(d,p,r);let h=new Set;s=await se(u,p,r,t.stxOptions||{},h)}return new Response(s,{headers:{"Content-Type":"text/html"}})},...t.routes}})}function Ti(e){return e}function Ci(e){return e}import{existsSync as wf,readFileSync as vf}from"fs";var $f={strict:!1,allowAny:!0,checkPropertyAccess:!0,checkFunctionCalls:!0,includeBuiltins:!0},Ei={console:{kind:"object",properties:{log:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},error:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},warn:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}}}},Math:{kind:"object",properties:{abs:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},floor:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},ceil:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},round:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},max:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},min:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},random:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},PI:{kind:"primitive",value:"number"},E:{kind:"primitive",value:"number"}}},JSON:{kind:"object",properties:{stringify:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},parse:{kind:"function",params:[{name:"text",type:{kind:"primitive",value:"string"}}],returnType:{kind:"primitive",value:"any"}}}},Date:{kind:"function",returnType:{kind:"object",properties:{getTime:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},toISOString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}},toLocaleDateString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}}}}},Array:{kind:"object",properties:{isArray:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},from:{kind:"function",params:[{name:"arrayLike",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},Object:{kind:"object",properties:{keys:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"string"}}},values:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}},entries:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},String:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},Number:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"number"}},Boolean:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},props:{kind:"object",properties:{}},slot:{kind:"primitive",value:"string"},loop:{kind:"object",properties:{index:{kind:"primitive",value:"number"},iteration:{kind:"primitive",value:"number"},first:{kind:"primitive",value:"boolean"},last:{kind:"primitive",value:"boolean"},even:{kind:"primitive",value:"boolean"},odd:{kind:"primitive",value:"boolean"},count:{kind:"primitive",value:"number"},remaining:{kind:"primitive",value:"number"},depth:{kind:"primitive",value:"number"},parent:{kind:"object",properties:{}}}}};class _i{options;variables=new Map;errors=[];warnings=[];currentFile="";constructor(e={}){if(this.options={...$f,...e},this.options.includeBuiltins)Object.entries(Ei).forEach(([t,r])=>{this.variables.set(t,r)});if(this.options.customTypes)Object.entries(this.options.customTypes).forEach(([t,r])=>{this.variables.set(t,r)})}checkFile(e){if(this.currentFile=e,this.errors=[],this.warnings=[],!wf(e))return this.errors.push({message:`File not found: ${e}`,file:e,line:0,column:0,expression:"",severity:"error"}),this.getResult();let t=vf(e,"utf-8");return this.checkTemplate(t,e)}checkTemplate(e,t="<inline>"){this.currentFile=t,this.errors=[],this.warnings=[];let r=e.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(r)this.analyzeScript(r[1],e.indexOf(r[0]));return this.checkDirectives(e),this.checkExpressions(e),this.getResult()}analyzeScript(e,t){let r=e.split(`
2923
+ </html>`}function ff(){return"<!-- Hero section -->"}function mf(){return"<!-- Features -->"}function hf(){return"<!-- Pricing -->"}function gf(){return"<!-- Button -->"}function er(e){if(!Qt(e))wo(e,{recursive:!0})}function yf(){if(Qt("bun.lockb"))return"bun";if(Qt("pnpm-lock.yaml"))return"pnpm";if(Qt("yarn.lock"))return"yarn";return"bun"}function vo(e){return e.replace(/[-_\s]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^./,(t)=>t.toUpperCase())}function xf(e){return e.replace(/[-_\s]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^./,(t)=>t.toLowerCase())}function pt(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase()}var{serve:bf}=globalThis.Bun;import tr from"fs";import Qe from"path";function Qv(e,t=200,r={}){return new Response(e,{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...r}})}async function wf(e={}){let{port:t=3000,root:r=".",stxOptions:n={},watch:o=!0,onRequest:s,routes:i={},middleware:a=[],on404:c,onError:l}=e,d=Qe.resolve(r),u=new Map;async function p(b){let w=tr.statSync(b),v=`${b}:${w.mtimeMs}`,k=u.get(v);if(k)return k.content;for(let A of u.keys())if(A.startsWith(`${b}:`)&&A!==v)u.delete(A);let C=await Bun.file(b).text(),E=C,R=Tt(C);if(R)E=R.content.trim();let T=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,F=[],J=[],G;while((G=T.exec(C))!==null){let A=G[1],_=G[2],j=G[0];if(A.includes("server"))J.push(_);else F.push(j)}let oe=C.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi)||[],xe=E.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),se={__filename:b,__dirname:Qe.dirname(b)};for(let A of J)await re(A,se,b);let Z=await ie(xe,se,b,n,new Set);if(oe.length>0){let A=oe.join(`
2924
+ `);if(Z.match(/(<\/head>)/i))Z=Z.replace(/(<\/head>)/i,`${A}
2925
+ $1`)}if(F.length>0){let{interpolateScriptsInTemplate:A}=await import("./chunk-2152npfd.js"),_=A(F.join(`
2926
+ `),se);if(Z.match(/(<\/body>)/i))Z=Z.replace(/(<\/body>)/i,`${_}
2927
+ $1`);else Z+=`
2928
+ ${_}`}return u.set(v,{content:Z,mtime:w.mtimeMs}),Z}async function h(b){let w=tr.statSync(b),v=`${b}:${w.mtimeMs}`,k=u.get(v);if(k)return k.content;let{content:C}=await Se(b,n);return u.set(v,{content:C,mtime:w.mtimeMs}),C}function f(b){let w=b.startsWith("/")?b.slice(1):b,v=[w,`${w}.stx`,`${w}.md`,`${w}.html`,Qe.join(w,"index.stx"),Qe.join(w,"index.md"),Qe.join(w,"index.html")];for(let k of v){let C=Qe.join(d,k);if(tr.existsSync(C)&&tr.statSync(C).isFile())return C}return null}async function g(b){let w=new URL(b.url),v=async()=>{if(i[w.pathname])return await i[w.pathname](b);if(s){let C=await s(b);if(C)return C}let k=f(w.pathname);if(!k){if(c)return await c(b);return new Response("Not Found",{status:404})}try{let C,E="text/html";if(k.endsWith(".stx"))C=await p(k);else if(k.endsWith(".md"))C=await h(k);else if(k.endsWith(".html"))C=await Bun.file(k).text();else if(k.endsWith(".css"))C=await Bun.file(k).text(),E="text/css";else if(k.endsWith(".js"))C=await Bun.file(k).text(),E="text/javascript";else if(k.endsWith(".json"))C=await Bun.file(k).text(),E="application/json";else return new Response(Bun.file(k));return new Response(C,{headers:{"Content-Type":E}})}catch(C){if(l)return await l(C,b);let E=C instanceof Error?C.message:String(C),R=n?.debug===!0?`<h1>Error</h1><pre>${E}
2929
+ ${C instanceof Error?C.stack:""}</pre>`:"<h1>Internal Server Error</h1><p>An error occurred while processing your request.</p>";return new Response(R,{status:500,headers:{"Content-Type":"text/html"}})}};for(let k=a.length-1;k>=0;k--){let C=a[k],E=v;v=async()=>await C(b,E)}return await v()}let x=bf({port:t,fetch:async(b)=>vt(b,await g(b))}),y=null;if(o)y=tr.watch(d,{recursive:!0},(b,w)=>{if(w&&(w.endsWith(".stx")||w.endsWith(".md")||w.endsWith(".html")))u.clear()});return{server:x,url:x.url.toString(),stop(){if(y)y.close();x.stop()}}}async function e0(e,t={}){let r=Qe.resolve(e);if(!await Bun.file(r).exists())throw Error(`File not found: ${r}`);let n=r.endsWith(".md"),o=r.endsWith(".stx");if(!n&&!o)throw Error(`Unsupported file type: ${r}. Only .stx and .md files are supported.`);return await wf({...t,root:Qe.dirname(r),routes:{"/":async()=>{let s;if(n){let{content:i}=await Se(r,t.stxOptions);s=i}else{let i=await Bun.file(r).text(),a=[],c=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,l;while((l=c.exec(i))!==null)if(l[1].includes("server"))a.push(l[2]);let d=a.join(`
2930
+ `),u=i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),p={};if(d.trim())await re(d,p,r);let h=new Set;s=await ie(u,p,r,t.stxOptions||{},h)}return new Response(s,{headers:{"Content-Type":"text/html"}})},...t.routes}})}function Ci(e){return e}function Ei(e){return e}import{existsSync as vf,readFileSync as $f}from"fs";var Sf={strict:!1,allowAny:!0,checkPropertyAccess:!0,checkFunctionCalls:!0,includeBuiltins:!0},_i={console:{kind:"object",properties:{log:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},error:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}},warn:{kind:"function",params:[{name:"message",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"void"}}}},Math:{kind:"object",properties:{abs:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},floor:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},ceil:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},round:{kind:"function",params:[{name:"x",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},max:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},min:{kind:"function",params:[{name:"values",type:{kind:"primitive",value:"number"}}],returnType:{kind:"primitive",value:"number"}},random:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},PI:{kind:"primitive",value:"number"},E:{kind:"primitive",value:"number"}}},JSON:{kind:"object",properties:{stringify:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},parse:{kind:"function",params:[{name:"text",type:{kind:"primitive",value:"string"}}],returnType:{kind:"primitive",value:"any"}}}},Date:{kind:"function",returnType:{kind:"object",properties:{getTime:{kind:"function",params:[],returnType:{kind:"primitive",value:"number"}},toISOString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}},toLocaleDateString:{kind:"function",params:[],returnType:{kind:"primitive",value:"string"}}}}},Array:{kind:"object",properties:{isArray:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},from:{kind:"function",params:[{name:"arrayLike",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},Object:{kind:"object",properties:{keys:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"string"}}},values:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}},entries:{kind:"function",params:[{name:"obj",type:{kind:"primitive",value:"any"}}],returnType:{kind:"array",elementType:{kind:"primitive",value:"any"}}}}},String:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"string"}},Number:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"number"}},Boolean:{kind:"function",params:[{name:"value",type:{kind:"primitive",value:"any"}}],returnType:{kind:"primitive",value:"boolean"}},props:{kind:"object",properties:{}},slot:{kind:"primitive",value:"string"},loop:{kind:"object",properties:{index:{kind:"primitive",value:"number"},iteration:{kind:"primitive",value:"number"},first:{kind:"primitive",value:"boolean"},last:{kind:"primitive",value:"boolean"},even:{kind:"primitive",value:"boolean"},odd:{kind:"primitive",value:"boolean"},count:{kind:"primitive",value:"number"},remaining:{kind:"primitive",value:"number"},depth:{kind:"primitive",value:"number"},parent:{kind:"object",properties:{}}}}};class Ai{options;variables=new Map;errors=[];warnings=[];currentFile="";constructor(e={}){if(this.options={...Sf,...e},this.options.includeBuiltins)Object.entries(_i).forEach(([t,r])=>{this.variables.set(t,r)});if(this.options.customTypes)Object.entries(this.options.customTypes).forEach(([t,r])=>{this.variables.set(t,r)})}checkFile(e){if(this.currentFile=e,this.errors=[],this.warnings=[],!vf(e))return this.errors.push({message:`File not found: ${e}`,file:e,line:0,column:0,expression:"",severity:"error"}),this.getResult();let t=$f(e,"utf-8");return this.checkTemplate(t,e)}checkTemplate(e,t="<inline>"){this.currentFile=t,this.errors=[],this.warnings=[];let r=e.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(r)this.analyzeScript(r[1],e.indexOf(r[0]));return this.checkDirectives(e),this.checkExpressions(e),this.getResult()}analyzeScript(e,t){let r=e.split(`
2931
2931
  `),n=this.getLineNumber(t);for(let o=0;o<r.length;o++){let s=r[o],i=n+o;this.extractTypedVariables(s,i),this.extractInterfaces(s,r,o,i),this.extractTypeAliases(s,i)}}extractTypedVariables(e,t){let r=e.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*:\s*([^=]+?)\s*=/);if(r){let[,s,i]=r,a=this.parseTypeAnnotation(i.trim());this.variables.set(s,a);return}let n=e.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(.+)/);if(n){let[,s,i]=n,a=this.inferType(i.trim());this.variables.set(s,a);return}let o=e.match(/(?:export\s+)?function\s+(\w+)\s*\(([^)]*)\)(?:\s*:\s*(\w+))?/);if(o){let[,s,i,a]=o,c=this.parseParams(i),l=a?this.parseTypeAnnotation(a):{kind:"primitive",value:"any"};this.variables.set(s,{kind:"function",params:c,returnType:l})}}extractInterfaces(e,t,r,n){let o=e.match(/(?:export\s+)?interface\s+(\w+)\s*\{/);if(o){let[,s]=o,i={},a=1,c=r+1;while(c<t.length&&a>0){let l=t[c].trim();if(l.includes("{"))a++;if(l.includes("}"))a--;let d=l.match(/(\w+)\??\s*:\s*([^;]+)/);if(d&&a>0){let[,u,p]=d;i[u]=this.parseTypeAnnotation(p.trim())}c++}this.variables.set(s,{kind:"object",name:s,properties:i})}}extractTypeAliases(e,t){let r=e.match(/(?:export\s+)?type\s+(\w+)\s*=\s*(.+)/);if(r){let[,n,o]=r,s=this.parseTypeAnnotation(o.trim());s.name=n,this.variables.set(n,s)}}parseTypeAnnotation(e){let t=e.trim();if(t.includes("|"))return{kind:"union",types:t.split("|").map((n)=>this.parseTypeAnnotation(n.trim()))};if(t.includes("&"))return{kind:"intersection",types:t.split("&").map((n)=>this.parseTypeAnnotation(n.trim()))};if(t.endsWith("[]"))return{kind:"array",elementType:this.parseTypeAnnotation(t.slice(0,-2))};let r=t.match(/^Array<(.+)>$/);if(r)return{kind:"array",elementType:this.parseTypeAnnotation(r[1])};if(t.startsWith("{")&&t.endsWith("}")){let n={},o=t.slice(1,-1).trim();if(o){let s=this.splitByComma(o);for(let i of s){let a=i.match(/(\w+)\??\s*:\s*(.+)/);if(a){let[,c,l]=a;n[c]=this.parseTypeAnnotation(l.trim())}}}return{kind:"object",properties:n}}if(t.startsWith('"')||t.startsWith("'"))return{kind:"literal",value:t.slice(1,-1)};if(/^\d+$/.test(t))return{kind:"literal",value:t};if(t==="true"||t==="false")return{kind:"literal",value:t};if(["string","number","boolean","null","undefined","any","unknown","void","never"].includes(t))return{kind:"primitive",value:t};if(this.variables.has(t))return this.variables.get(t);return{kind:"primitive",value:"any"}}inferType(e){let t=e.trim().replace(/;$/,"");if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")||t.startsWith("`")&&t.endsWith("`"))return{kind:"primitive",value:"string"};if(/^-?\d+(\.\d+)?$/.test(t))return{kind:"primitive",value:"number"};if(t==="true"||t==="false")return{kind:"primitive",value:"boolean"};if(t==="null")return{kind:"primitive",value:"null"};if(t==="undefined")return{kind:"primitive",value:"undefined"};if(t.startsWith("[")){let r=t.slice(1,-1).trim();if(r){let n=this.splitByComma(r)[0];if(n)return{kind:"array",elementType:this.inferType(n.trim())}}return{kind:"array",elementType:{kind:"primitive",value:"any"}}}if(t.startsWith("{")){let r={},n=this.extractObjectLiteral(t);for(let[o,s]of Object.entries(n))r[o]=this.inferType(s);return{kind:"object",properties:r}}if(t.includes("=>")){let r=t.match(/^\(([^)]*)\)\s*(?::\s*(\w+))?\s*=>/);if(r){let n=this.parseParams(r[1]),o=r[2]?this.parseTypeAnnotation(r[2]):{kind:"primitive",value:"any"};return{kind:"function",params:n,returnType:o}}}if(/^\w+$/.test(t)&&this.variables.has(t))return this.variables.get(t);if(t.includes("."))return this.resolvePropertyAccess(t);if(t.includes("(")){let r=t.split("(")[0],n=this.variables.get(r);if(n?.kind==="function"&&n.returnType)return n.returnType}return{kind:"primitive",value:"any"}}parseParams(e){if(!e.trim())return[];let t=[],r=this.splitByComma(e);for(let n of r){let o=n.trim(),s=o.includes("?"),i=o.match(/(\w+)\??\s*(?::\s*([^=]+))?(?:\s*=)?/);if(i){let[,a,c]=i,l=c?this.parseTypeAnnotation(c.trim()):{kind:"primitive",value:"any"};t.push({name:a,type:l,optional:s})}}return t}checkExpressions(e){let t=/\{\{([\s\S]*?)\}\}/g,r;while((r=t.exec(e))!==null){let o=r[1].trim(),s=r.index,i=this.getLineNumber(s,e),a=this.getColumn(s,e);if(!o)continue;if(o.startsWith("!")||o.endsWith("!"))continue;this.checkExpression(o,i,a)}let n=/\{!!([\s\S]*?)!!\}/g;while((r=n.exec(e))!==null){let o=r[1].trim(),s=r.index,i=this.getLineNumber(s,e),a=this.getColumn(s,e);if(!o)continue;this.checkExpression(o,i,a)}}checkExpression(e,t,r){if(e.includes("?")&&e.includes(":")){let s=e.split("?");this.checkExpression(s[0].trim(),t,r);let i=s.slice(1).join("?").split(":");if(i.length>=2)this.checkExpression(i[0].trim(),t,r),this.checkExpression(i.slice(1).join(":").trim(),t,r);return}for(let s of["&&","||","??"])if(e.includes(s)){e.split(s).forEach((i)=>this.checkExpression(i.trim(),t,r));return}for(let s of["===","!==","==","!=",">=","<=",">","<"])if(e.includes(s)){e.split(s).forEach((i)=>this.checkExpression(i.trim(),t,r));return}if(e.startsWith("!")){this.checkExpression(e.slice(1).trim(),t,r);return}if(this.isLiteral(e))return;let n=e.match(/^(\w+(?:\.\w+)*)\s*\(/);if(n){let s=n[1],i=this.resolvePropertyAccess(s);if(i.kind!=="function"&&i.value!=="any")this.addWarning(`'${s}' is not a function`,t,r,e);return}if(e.includes(".")){if(this.resolvePropertyAccess(e).value==="undefined"&&this.options.checkPropertyAccess)this.addWarning(`Property access '${e}' may be undefined`,t,r,e);return}let o=e.match(/^\w+/)?.[0];if(o&&!this.variables.has(o))this.addError(`Variable '${o}' is not defined`,t,r,e)}checkDirectives(e){let t=/@if\s*\(([^)]+)\)/g,r;while((r=t.exec(e))!==null){let i=r[1].trim(),a=r.index,c=this.getLineNumber(a,e),l=this.getColumn(a,e);this.checkExpression(i,c,l)}let n=/@foreach\s*\((\w+)\s+(?:as|in)\s+(\w+)(?:\s*,\s*(\w+))?\)/g;while((r=n.exec(e))!==null){let[,i,a,c]=r,l=r.index,d=this.getLineNumber(l,e),u=this.getColumn(l,e);if(!this.variables.has(i))this.addError(`Collection '${i}' is not defined`,d,u,r[0]);else{let p=this.variables.get(i);if(p.kind==="array"&&p.elementType)this.variables.set(a,p.elementType);else this.variables.set(a,{kind:"primitive",value:"any"});if(c)this.variables.set(c,{kind:"primitive",value:"number"})}}let o=/@unless\s*\(([^)]+)\)/g;while((r=o.exec(e))!==null){let i=r[1].trim(),a=r.index,c=this.getLineNumber(a,e),l=this.getColumn(a,e);this.checkExpression(i,c,l)}let s=/@switch\s*\(([^)]+)\)/g;while((r=s.exec(e))!==null){let i=r[1].trim(),a=r.index,c=this.getLineNumber(a,e),l=this.getColumn(a,e);this.checkExpression(i,c,l)}}resolvePropertyAccess(e){let t=e.split("."),r=this.variables.get(t[0])||{kind:"primitive",value:"any"};for(let n=1;n<t.length;n++){let o=t[n].replace(/\(\)$/,"");if(r.kind==="object"&&r.properties)if(r.properties[o])r=r.properties[o];else if(!this.options.allowAny)return{kind:"primitive",value:"undefined"};else r={kind:"primitive",value:"any"};else if(r.kind==="array"&&r.elementType)if(["length"].includes(o))r={kind:"primitive",value:"number"};else if(["map","filter","find","forEach","some","every","reduce"].includes(o))r={kind:"function",returnType:{kind:"primitive",value:"any"}};else if(["join"].includes(o))r={kind:"function",returnType:{kind:"primitive",value:"string"}};else r={kind:"primitive",value:"any"};else if(r.kind==="primitive"&&r.value==="string")if(["length"].includes(o))r={kind:"primitive",value:"number"};else if(["toUpperCase","toLowerCase","trim","slice","substring"].includes(o))r={kind:"function",returnType:{kind:"primitive",value:"string"}};else if(["split"].includes(o))r={kind:"function",returnType:{kind:"array",elementType:{kind:"primitive",value:"string"}}};else r={kind:"primitive",value:"any"};else r={kind:"primitive",value:"any"}}return r}isLiteral(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")||t.startsWith("`")&&t.endsWith("`"))return!0;if(/^-?\d+(\.\d+)?$/.test(t))return!0;if(t==="true"||t==="false")return!0;if(t==="null"||t==="undefined")return!0;return!1}extractObjectLiteral(e){let t={},r=e.slice(1,-1).trim();if(!r)return t;let n=this.splitByComma(r);for(let o of n){let s=o.indexOf(":");if(s>0){let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();t[i]=a}}return t}splitByComma(e){let t=[],r="",n=0,o=null;for(let s=0;s<e.length;s++){let i=e[s],a=s>0?e[s-1]:"";if((i==='"'||i==="'"||i==="`")&&a!=="\\"){if(o===i)o=null;else if(!o)o=i}if(!o){if(i==="{"||i==="["||i==="(")n++;if(i==="}"||i==="]"||i===")")n--;if(i===","&&n===0){t.push(r.trim()),r="";continue}}r+=i}if(r.trim())t.push(r.trim());return t}getLineNumber(e,t){return((t||"").slice(0,e).match(/\n/g)||[]).length+1}getColumn(e,t){let r=t.slice(0,e).lastIndexOf(`
2932
- `);return e-r}addError(e,t,r,n,o,s){this.errors.push({message:e,file:this.currentFile,line:t,column:r,expression:n,expected:o,received:s,severity:"error"})}addWarning(e,t,r,n,o,s){let i={message:e,file:this.currentFile,line:t,column:r,expression:n,expected:o,received:s,severity:"warning"};if(this.options.strict)this.errors.push(i);else this.warnings.push(i)}getResult(){return{valid:this.errors.length===0,errors:this.errors,warnings:this.warnings,variables:new Map(this.variables)}}addVariable(e,t){this.variables.set(e,t)}reset(){if(this.errors=[],this.warnings=[],this.variables.clear(),this.options.includeBuiltins)Object.entries(Ei).forEach(([e,t])=>{this.variables.set(e,t)})}}function Ai(e){return new _i(e)}function r0(e,t){return Ai(t).checkFile(e)}function n0(e,t){return Ai(t).checkTemplate(e)}function o0(e){let t=[];for(let r of e.errors){if(t.push(`\x1B[31merror\x1B[0m: ${r.message}`),t.push(` --> ${r.file}:${r.line}:${r.column}`),r.expression)t.push(" |"),t.push(` | ${r.expression}`),t.push(" |");if(r.expected&&r.received)t.push(` expected: ${r.expected}`),t.push(` received: ${r.received}`);t.push("")}for(let r of e.warnings){if(t.push(`\x1B[33mwarning\x1B[0m: ${r.message}`),t.push(` --> ${r.file}:${r.line}:${r.column}`),r.expression)t.push(" |"),t.push(` | ${r.expression}`),t.push(" |");t.push("")}if(e.valid)t.push("\x1B[32m\u2713 No type errors found\x1B[0m");else t.push(`\x1B[31m\u2717 Found ${e.errors.length} error(s) and ${e.warnings.length} warning(s)\x1B[0m`);return t.join(`
2933
- `)}import{existsSync as Ni,readFileSync as kf}from"fs";import ee from"path";function Tf(e,t=""){let r=e.startLine>1?`
2934
- `.repeat(e.startLine-1):"",n=Di(Mi(e.code)),o=e.kind==="client"||e.kind==="plain"?Oi(t):"";return`${r+n}
2932
+ `);return e-r}addError(e,t,r,n,o,s){this.errors.push({message:e,file:this.currentFile,line:t,column:r,expression:n,expected:o,received:s,severity:"error"})}addWarning(e,t,r,n,o,s){let i={message:e,file:this.currentFile,line:t,column:r,expression:n,expected:o,received:s,severity:"warning"};if(this.options.strict)this.errors.push(i);else this.warnings.push(i)}getResult(){return{valid:this.errors.length===0,errors:this.errors,warnings:this.warnings,variables:new Map(this.variables)}}addVariable(e,t){this.variables.set(e,t)}reset(){if(this.errors=[],this.warnings=[],this.variables.clear(),this.options.includeBuiltins)Object.entries(_i).forEach(([e,t])=>{this.variables.set(e,t)})}}function ji(e){return new Ai(e)}function n0(e,t){return ji(t).checkFile(e)}function o0(e,t){return ji(t).checkTemplate(e)}function s0(e){let t=[];for(let r of e.errors){if(t.push(`\x1B[31merror\x1B[0m: ${r.message}`),t.push(` --> ${r.file}:${r.line}:${r.column}`),r.expression)t.push(" |"),t.push(` | ${r.expression}`),t.push(" |");if(r.expected&&r.received)t.push(` expected: ${r.expected}`),t.push(` received: ${r.received}`);t.push("")}for(let r of e.warnings){if(t.push(`\x1B[33mwarning\x1B[0m: ${r.message}`),t.push(` --> ${r.file}:${r.line}:${r.column}`),r.expression)t.push(" |"),t.push(` | ${r.expression}`),t.push(" |");t.push("")}if(e.valid)t.push("\x1B[32m\u2713 No type errors found\x1B[0m");else t.push(`\x1B[31m\u2717 Found ${e.errors.length} error(s) and ${e.warnings.length} warning(s)\x1B[0m`);return t.join(`
2933
+ `)}import{existsSync as Bi,readFileSync as Tf}from"fs";import te from"path";function Cf(e,t=""){let r=e.startLine>1?`
2934
+ `.repeat(e.startLine-1):"",n=Pi(Di(e.code)),o=e.kind==="client"||e.kind==="plain"?Ii(t):"";return`${r+n}
2935
2935
  ${o}
2936
2936
  export {}
2937
- `}function Cf(e){let t=e.length>0?ee.dirname(ee.resolve(e[0])):process.cwd();try{Bun.resolveSync("@stacksjs/stx",t)}catch{return""}return["// Generated \u2014 `stx` is the virtual specifier client-script.ts strips.","declare module 'stx' {"," export * from '@stacksjs/stx'","}"].join(`
2938
- `)}function ji(e,t,r){return`${e}.__stx_${t}${r}.ts`}function u0(e){return e.replace(/\.__stx_(?:server|client|plain|template)\d+\.ts$/,"")}function Ef(){for(let e of[ee.resolve(import.meta.dir,"..","stx.d.ts"),ee.resolve(import.meta.dir,"..","..","stx.d.ts")])if(Ni(e))return e;return null}var _f=/^(.*?)\((\d+),(\d+)\):\s+(error|warning)\s+TS(\d+):\s+(.*)$/;function Af(e){return e>=1000&&e<2000}function jf(e){let t=ee.resolve(e),r;for(;;){let u=ee.join(t,"tsconfig.json");if(Ni(u)){r=u;break}let p=ee.dirname(t);if(p===t)break;t=p}if(!r)return{};let n=(u)=>{let p="",h=!1,f=!1;for(let g=0;g<u.length;g++){let x=u[g];if(h){if(p+=x,f)f=!1;else if(x==="\\")f=!0;else if(x==='"')h=!1;continue}if(x==='"'){h=!0,p+=x;continue}if(x==="/"&&u[g+1]==="/"){while(g<u.length&&u[g]!==`
2937
+ `}function Ef(e){let t=e.length>0?te.dirname(te.resolve(e[0])):process.cwd();try{Bun.resolveSync("@stacksjs/stx",t)}catch{return""}return["// Generated \u2014 `stx` is the virtual specifier client-script.ts strips.","declare module 'stx' {"," export * from '@stacksjs/stx'","}"].join(`
2938
+ `)}function Ri(e,t,r){return`${e}.__stx_${t}${r}.ts`}function p0(e){return e.replace(/\.__stx_(?:server|client|plain|template)\d+\.ts$/,"")}function _f(){for(let e of[te.resolve(import.meta.dir,"..","stx.d.ts"),te.resolve(import.meta.dir,"..","..","stx.d.ts")])if(Bi(e))return e;return null}var Af=/^(.*?)\((\d+),(\d+)\):\s+(error|warning)\s+TS(\d+):\s+(.*)$/;function jf(e){return e>=1000&&e<2000}function Rf(e){let t=te.resolve(e),r;for(;;){let u=te.join(t,"tsconfig.json");if(Bi(u)){r=u;break}let p=te.dirname(t);if(p===t)break;t=p}if(!r)return{};let n=(u)=>{let p="",h=!1,f=!1;for(let g=0;g<u.length;g++){let x=u[g];if(h){if(p+=x,f)f=!1;else if(x==="\\")f=!0;else if(x==='"')h=!1;continue}if(x==='"'){h=!0,p+=x;continue}if(x==="/"&&u[g+1]==="/"){while(g<u.length&&u[g]!==`
2939
2939
  `)g++;p+=`
2940
- `;continue}if(x==="/"&&u[g+1]==="*"){g+=2;while(g<u.length&&!(u[g]==="*"&&u[g+1]==="/"))g++;g++;continue}p+=x}return p.replace(/,(\s*[}\]])/g,"$1")},o=new Set,s=r,i,a,c=r;while(s&&!o.has(s)){o.add(s);let u;try{u=JSON.parse(n(kf(s,"utf8")))}catch{break}let p=u?.compilerOptions??{};if(!i&&p.paths&&typeof p.paths==="object")i=p.paths,c=s;if(!a&&typeof p.baseUrl==="string")a=ee.resolve(ee.dirname(s),p.baseUrl);if(i&&a)break;s=typeof u?.extends==="string"?ee.resolve(ee.dirname(s),u.extends.endsWith(".json")?u.extends:`${u.extends}.json`):void 0}if(!i)return{};let l=a??ee.dirname(c),d={};for(let[u,p]of Object.entries(i)){if(!Array.isArray(p))continue;d[u]=p.map((h)=>typeof h==="string"&&!ee.isAbsolute(h)?ee.resolve(l,h):h)}return{paths:d}}async function p0(e,t={}){let r=t.client!==!1,n=t.server!==!1,o=t.templates!==!1,s=new Map,i=new Map,a=[],c=0,l=0,d=Ef();for(let E of e){let A=await Bun.file(E).text(),R=qr(A).filter((z)=>{if(z.kind==="server")return n;return r}),M=qr(A).filter((z)=>z.kind==="server").map((z)=>z.code).join(`
2941
- `);if(r&&M){let z=R.filter((q)=>q.kind!=="server"),me=[...new Set(z.flatMap((q)=>Ii(M,q.code)))];if(me.length>0)i.set(E,{names:me,line:z[0].startLine,kind:z[0].kind})}let N=o?Li(A,{runtimeGlobals:!d}):null,Z=N?[...N.lineMap.values()].filter((z)=>z.expression).length:0;if(R.length===0&&Z===0)continue;if(a.push(E),c+=R.length,l+=Z,R.forEach((z,me)=>{s.set(ji(E,z.kind,me),{source:Tf(z,M),origin:E,kind:z.kind})}),N&&Z>0)s.set(ji(E,"template",0),{source:N.text,origin:E,kind:"template",virtual:N})}if(s.size===0)return{diagnostics:[],checkedFiles:a,blockCount:0,expressionCount:0};let u=(t.extraLibs??[]).map((E)=>ee.resolve(E));if(d)u.push(d);let p=`${ke()}/typecheck/__stx_globals.d.ts`,h=["// Generated \u2014 the context serve.ts injects into <script server> blocks.",Pi(),...d?[]:["declare const window: any",...Ri.map((E)=>`declare const ${E}: any`)],Cf(e)].filter(Boolean).join(`
2942
- `),f=`${ke()}/typecheck`;await Bun.$`rm -rf ${f}`.quiet().nothrow(),await Bun.$`mkdir -p ${f}`.quiet().nothrow(),await Bun.write(p,h);let g=new Map,x=0;for(let[E,A]of s){let R=`${x++}_${E.replace(/[^\w.-]+/g,"_")}`;await Bun.write(`${f}/${R}`,A.source),g.set(R,A)}let y={target:"ESNext",module:"ESNext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,allowJs:!0,esModuleInterop:!0,resolveJsonModule:!0,lib:["ESNext","DOM","DOM.Iterable"],types:[],...jf(e.length>0?ee.dirname(ee.resolve(e[0])):process.cwd()),...t.compilerOptions??{}},b=async(E,A)=>{let R=`${f}/tsconfig${A===1?"":`.${A}`}.json`;await Bun.write(R,JSON.stringify({compilerOptions:y,files:E.map((N)=>`${f}/${N}`).concat(p,...u)},null,2));let M=Bun.spawnSync(["bun","x","tsc","-p",R,"--pretty","false"],{stdout:"pipe",stderr:"pipe"});return{output:new TextDecoder().decode(M.stdout)+new TextDecoder().decode(M.stderr),exitCode:M.exitCode??0}},w=await b([...g.keys()],1),v=w.output,S=[],T=w.exitCode,C=0,j=new Set(u.map((E)=>E.split("/").pop())),k=0,L=new Set,X=(E)=>{for(let A of E.split(`
2943
- `)){let R=A.match(_f);if(!R)continue;if(C++,j.has(R[1].split("/").pop()))k++;let[,M,N,Z,z,me,q]=R,nt=M.split("/").pop(),Ce=g.get(nt);if(!Ce)continue;if(Af(Number(me)))L.add(nt);let D=Number(N),I=Number(Z),U;if(Ce.virtual){let F=Fi(Ce.virtual,D,I);if(!F?.expression)continue;if(Number(me)===2774)continue;D=F.line,I=F.column,U=F.expression.code.trim()}S.push({file:Ce.origin,line:D,column:I,code:Number(me),message:q,category:z==="error"?"error":"warning",blockKind:Ce.kind,expression:U})}};X(v);let K=C,ne=k;if(L.size>0&&L.size<g.size){let E=[...g.keys()].filter((A)=>!L.has(A));X((await b(E,2)).output)}if(r)for(let[E,A]of i){if(A.names.length===0)continue;S.push({file:E,line:A.line,column:1,code:0,message:`${A.names.length===1?"1 value reaches":`${A.names.length} values reach`} this block on the implicit bridge and ${A.names.length===1?"is":"are"} untyped: ${A.names.join(", ")}. Declare them with defineClientPayload({ ${A.names.join(", ")} }) in the server block to have them checked.`,category:"warning",blockKind:A.kind})}let ye=new Set,oe=S.filter((E)=>{let A=`${E.file}:${E.line}:${E.column}:${E.code}:${E.message}`;if(ye.has(A))return!1;return ye.add(A),!0});oe.sort((E,A)=>E.file.localeCompare(A.file)||E.line-A.line||E.column-A.column);let G=ne>0&&oe.length===0,_=G||T!==0&&K===0?`${G?"a file passed with --lib has errors of its own, so nothing in your code was checked":`tsc exited ${T} without reporting any diagnostic, so nothing was checked`}. `+"A syntax error in an ambient declaration file does this \u2014 skipLibCheck suppresses "+`SEMANTIC diagnostics only. tsc said:
2940
+ `;continue}if(x==="/"&&u[g+1]==="*"){g+=2;while(g<u.length&&!(u[g]==="*"&&u[g+1]==="/"))g++;g++;continue}p+=x}return p.replace(/,(\s*[}\]])/g,"$1")},o=new Set,s=r,i,a,c=r;while(s&&!o.has(s)){o.add(s);let u;try{u=JSON.parse(n(Tf(s,"utf8")))}catch{break}let p=u?.compilerOptions??{};if(!i&&p.paths&&typeof p.paths==="object")i=p.paths,c=s;if(!a&&typeof p.baseUrl==="string")a=te.resolve(te.dirname(s),p.baseUrl);if(i&&a)break;s=typeof u?.extends==="string"?te.resolve(te.dirname(s),u.extends.endsWith(".json")?u.extends:`${u.extends}.json`):void 0}if(!i)return{};let l=a??te.dirname(c),d={};for(let[u,p]of Object.entries(i)){if(!Array.isArray(p))continue;d[u]=p.map((h)=>typeof h==="string"&&!te.isAbsolute(h)?te.resolve(l,h):h)}return{paths:d}}async function f0(e,t={}){let r=t.client!==!1,n=t.server!==!1,o=t.templates!==!1,s=new Map,i=new Map,a=[],c=0,l=0,d=_f();for(let _ of e){let j=await Bun.file(_).text(),M=Xr(j).filter((U)=>{if(U.kind==="server")return n;return r}),D=Xr(j).filter((U)=>U.kind==="server").map((U)=>U.code).join(`
2941
+ `);if(r&&D){let U=M.filter((X)=>X.kind!=="server"),he=[...new Set(U.flatMap((X)=>Li(D,X.code)))];if(he.length>0)i.set(_,{names:he,line:U[0].startLine,kind:U[0].kind})}let B=o?Fi(j,{runtimeGlobals:!d}):null,Q=B?[...B.lineMap.values()].filter((U)=>U.expression).length:0;if(M.length===0&&Q===0)continue;if(a.push(_),c+=M.length,l+=Q,M.forEach((U,he)=>{s.set(Ri(_,U.kind,he),{source:Cf(U,D),origin:_,kind:U.kind})}),B&&Q>0)s.set(Ri(_,"template",0),{source:B.text,origin:_,kind:"template",virtual:B})}if(s.size===0)return{diagnostics:[],checkedFiles:a,blockCount:0,expressionCount:0};let u=(t.extraLibs??[]).map((_)=>te.resolve(_));if(d)u.push(d);let p=`${Te()}/typecheck/__stx_globals.d.ts`,h=["// Generated \u2014 the context serve.ts injects into <script server> blocks.",Oi(),...d?[]:["declare const window: any",...Mi.map((_)=>`declare const ${_}: any`)],Ef(e)].filter(Boolean).join(`
2942
+ `),f=`${Te()}/typecheck`;await Bun.$`rm -rf ${f}`.quiet().nothrow(),await Bun.$`mkdir -p ${f}`.quiet().nothrow(),await Bun.write(p,h);let g=new Map,x=0;for(let[_,j]of s){let M=`${x++}_${_.replace(/[^\w.-]+/g,"_")}`;await Bun.write(`${f}/${M}`,j.source),g.set(M,j)}let y={target:"ESNext",module:"ESNext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,allowJs:!0,esModuleInterop:!0,resolveJsonModule:!0,lib:["ESNext","DOM","DOM.Iterable"],types:[],...Rf(e.length>0?te.dirname(te.resolve(e[0])):process.cwd()),...t.compilerOptions??{}},b=async(_,j)=>{let M=`${f}/tsconfig${j===1?"":`.${j}`}.json`;await Bun.write(M,JSON.stringify({compilerOptions:y,files:_.map((B)=>`${f}/${B}`).concat(p,...u)},null,2));let D=Bun.spawnSync(["bun","x","tsc","-p",M,"--pretty","false"],{stdout:"pipe",stderr:"pipe"});return{output:new TextDecoder().decode(D.stdout)+new TextDecoder().decode(D.stderr),exitCode:D.exitCode??0}},w=await b([...g.keys()],1),v=w.output,k=[],C=w.exitCode,E=0,R=new Set(u.map((_)=>_.split("/").pop())),T=0,F=new Set,J=(_)=>{for(let j of _.split(`
2943
+ `)){let M=j.match(Af);if(!M)continue;if(E++,R.has(M[1].split("/").pop()))T++;let[,D,B,Q,U,he,X]=M,ot=D.split("/").pop(),Ee=g.get(ot);if(!Ee)continue;if(jf(Number(he)))F.add(ot);let P=Number(B),L=Number(Q),H;if(Ee.virtual){let N=Ni(Ee.virtual,P,L);if(!N?.expression)continue;if(Number(he)===2774)continue;P=N.line,L=N.column,H=N.expression.code.trim()}k.push({file:Ee.origin,line:P,column:L,code:Number(he),message:X,category:U==="error"?"error":"warning",blockKind:Ee.kind,expression:H})}};J(v);let G=E,oe=T;if(F.size>0&&F.size<g.size){let _=[...g.keys()].filter((j)=>!F.has(j));J((await b(_,2)).output)}if(r)for(let[_,j]of i){if(j.names.length===0)continue;k.push({file:_,line:j.line,column:1,code:0,message:`${j.names.length===1?"1 value reaches":`${j.names.length} values reach`} this block on the implicit bridge and ${j.names.length===1?"is":"are"} untyped: ${j.names.join(", ")}. Declare them with defineClientPayload({ ${j.names.join(", ")} }) in the server block to have them checked.`,category:"warning",blockKind:j.kind})}let xe=new Set,se=k.filter((_)=>{let j=`${_.file}:${_.line}:${_.column}:${_.code}:${_.message}`;if(xe.has(j))return!1;return xe.add(j),!0});se.sort((_,j)=>_.file.localeCompare(j.file)||_.line-j.line||_.column-j.column);let Z=oe>0&&se.length===0,A=Z||C!==0&&G===0?`${Z?"a file passed with --lib has errors of its own, so nothing in your code was checked":`tsc exited ${C} without reporting any diagnostic, so nothing was checked`}. `+"A syntax error in an ambient declaration file does this \u2014 skipLibCheck suppresses "+`SEMANTIC diagnostics only. tsc said:
2944
2944
  ${v.trim().split(`
2945
2945
  `).slice(0,12).join(`
2946
- `)||"(no output)"}`:void 0;return{diagnostics:oe,checkedFiles:a,blockCount:c,expressionCount:l,failure:_}}function f0(e){return e.map((t)=>{let r=t.blockKind==="template"?`[template: ${t.expression??""}]`:`[${t.blockKind==="plain"?"<script>":`<script ${t.blockKind}>`}]`;return`${t.file}:${t.line}:${t.column} ${t.category} TS${t.code} ${t.message} ${r}`}).join(`
2947
- `)}var $o=typeof window<"u"&&typeof document<"u";async function vo(e,t,r){if(!$o)return;try{let n=e.getAttribute("data-island-id"),o=document.querySelector(`script[data-island-props="${n}"]`),s=o?JSON.parse(o.textContent||"{}"):{},i=await r(),a=i.default||i.hydrate;if(typeof a!=="function"){console.error(`Island handler for "${t}" does not export a valid hydration function`);return}await a(e,s),e.setAttribute("data-hydrated","true")}catch(n){console.error(`Failed to hydrate island "${t}":`,n)}}function g0(e){if(!$o)return;let t=document.querySelectorAll("[data-island]"),r=[];if(t.forEach((n)=>{let o=n.getAttribute("data-island"),s=n.getAttribute("data-priority")||"lazy";if(!o||!e[o]||n.getAttribute("data-hydrated")==="true")return;if(s==="eager")vo(n,o,e[o]);else r.push([n,o])}),r.length>0&&"IntersectionObserver"in window){let n=new IntersectionObserver((o)=>{o.forEach((s)=>{if(s.isIntersecting){let i=s.target,a=i.getAttribute("data-island");if(a&&e[a]&&i.getAttribute("data-hydrated")!=="true")vo(i,a,e[a]),n.unobserve(i)}})},{rootMargin:"200px",threshold:0});r.forEach(([o])=>{n.observe(o)})}else setTimeout(()=>{r.forEach(([n,o])=>{if(n.getAttribute("data-hydrated")!=="true")vo(n,o,e[o])})},1000)}function y0(e){if(!$o)return;Object.entries(e).forEach(([t,r])=>{try{let n=r.toString().match(/import\(['"](.+)['"]\)/);if(n&&n[1]){let o=document.createElement("link");o.rel="modulepreload",o.href=n[1],o.setAttribute("data-island-module",t),document.head.appendChild(o)}}catch(n){console.warn(`Failed to preload island handler for "${t}":`,n)}})}var jt=typeof window<"u"&&typeof document<"u",ko={color:"#6366f1",initialColor:"",height:"3px",duration:2000,throttle:200,autoFinish:!0,zIndex:999999},ue=null,De=0,tr=!1,So=null,At=null,Ue=null;function Bi(e){if(!jt)return null;let t=document.getElementById("stx-loading-indicator");if(t)t.remove();let r=document.createElement("div");r.id="stx-loading-indicator";let n=e.initialColor?`linear-gradient(to right, ${e.initialColor}, ${e.color})`:e.color;r.style.cssText=`
2946
+ `)||"(no output)"}`:void 0;return{diagnostics:se,checkedFiles:a,blockCount:c,expressionCount:l,failure:A}}function m0(e){return e.map((t)=>{let r=t.blockKind==="template"?`[template: ${t.expression??""}]`:`[${t.blockKind==="plain"?"<script>":`<script ${t.blockKind}>`}]`;return`${t.file}:${t.line}:${t.column} ${t.category} TS${t.code} ${t.message} ${r}`}).join(`
2947
+ `)}var So=typeof window<"u"&&typeof document<"u";async function $o(e,t,r){if(!So)return;try{let n=e.getAttribute("data-island-id"),o=document.querySelector(`script[data-island-props="${n}"]`),s=o?JSON.parse(o.textContent||"{}"):{},i=await r(),a=i.default||i.hydrate;if(typeof a!=="function"){console.error(`Island handler for "${t}" does not export a valid hydration function`);return}await a(e,s),e.setAttribute("data-hydrated","true")}catch(n){console.error(`Failed to hydrate island "${t}":`,n)}}function y0(e){if(!So)return;let t=document.querySelectorAll("[data-island]"),r=[];if(t.forEach((n)=>{let o=n.getAttribute("data-island"),s=n.getAttribute("data-priority")||"lazy";if(!o||!e[o]||n.getAttribute("data-hydrated")==="true")return;if(s==="eager")$o(n,o,e[o]);else r.push([n,o])}),r.length>0&&"IntersectionObserver"in window){let n=new IntersectionObserver((o)=>{o.forEach((s)=>{if(s.isIntersecting){let i=s.target,a=i.getAttribute("data-island");if(a&&e[a]&&i.getAttribute("data-hydrated")!=="true")$o(i,a,e[a]),n.unobserve(i)}})},{rootMargin:"200px",threshold:0});r.forEach(([o])=>{n.observe(o)})}else setTimeout(()=>{r.forEach(([n,o])=>{if(n.getAttribute("data-hydrated")!=="true")$o(n,o,e[o])})},1000)}function x0(e){if(!So)return;Object.entries(e).forEach(([t,r])=>{try{let n=r.toString().match(/import\(['"](.+)['"]\)/);if(n&&n[1]){let o=document.createElement("link");o.rel="modulepreload",o.href=n[1],o.setAttribute("data-island-module",t),document.head.appendChild(o)}}catch(n){console.warn(`Failed to preload island handler for "${t}":`,n)}})}var Rt=typeof window<"u"&&typeof document<"u",To={color:"#6366f1",initialColor:"",height:"3px",duration:2000,throttle:200,autoFinish:!0,zIndex:999999},pe=null,Pe=0,rr=!1,ko=null,jt=null,He=null;function zi(e){if(!Rt)return null;let t=document.getElementById("stx-loading-indicator");if(t)t.remove();let r=document.createElement("div");r.id="stx-loading-indicator";let n=e.initialColor?`linear-gradient(to right, ${e.initialColor}, ${e.color})`:e.color;r.style.cssText=`
2948
2948
  position: fixed;
2949
2949
  top: 0;
2950
2950
  left: 0;
@@ -2975,7 +2975,7 @@ ${v.trim().split(`
2975
2975
  0% { transform: translateX(-100%); }
2976
2976
  100% { transform: translateX(100%); }
2977
2977
  }
2978
- `,document.head.appendChild(s)}return document.body.appendChild(r),r}function Xr(e,t){if(!jt||!ue)return;if(De=Math.min(Math.max(e,0),100),So)cancelAnimationFrame(So);So=requestAnimationFrame(()=>{if(!ue)return;ue.style.opacity=De>0?"1":"0",ue.style.transform=`scaleX(${De/100})`})}function Rf(e){if(!jt)return;if(tr=!0,De=0,!ue)ue=Bi(e);if(At)clearTimeout(At);if(Ue)clearInterval(Ue);Xr(10,e),Ue=setInterval(()=>{if(!tr)return;let t=90-De,r=Math.max(0.5,t*0.1);if(De<90)Xr(De+r,e)},e.throttle)}function Mf(e){if(!jt)return;if(tr=!1,Ue)clearInterval(Ue),Ue=null;Xr(100,e),At=setTimeout(()=>{if(ue)ue.style.opacity="0";setTimeout(()=>{if(De=0,ue)ue.style.transform="scaleX(0)"},300)},200)}function Df(){if(!jt)return;if(tr=!1,De=0,Ue)clearInterval(Ue),Ue=null;if(At)clearTimeout(At),At=null;if(ue)ue.style.opacity="0",ue.style.transform="scaleX(0)"}function Pf(e){let t={...ko,...e};return{start:()=>Rf(t),set:(r)=>Xr(r,t),finish:()=>Mf(t),clear:()=>Df(),get state(){return{isLoading:tr,progress:De,error:!1}}}}var pt=null;function b0(e){if(!jt)return;if(pt)pt(),pt=null;let t={...ko,...e},r=Pf(t);ue=Bi(t);let n=!1,o=(d)=>{let u=d.target.closest("a");if(!u)return;let p=u.getAttribute("href");if(!p)return;if(p.startsWith("http")||p.startsWith("#")||p.startsWith("mailto:")||p.startsWith("tel:")||u.target==="_blank"||u.hasAttribute("download"))return;n=!0,r.start()},s=()=>{if(!n)r.start(),n=!0},i=()=>{if(n||t.autoFinish)r.finish(),n=!1};document.addEventListener("click",o),window.addEventListener("popstate",s),window.addEventListener("load",i);let a=window.fetch,c=0,l=async function(...d){let u=typeof d[0]==="string"?d[0]:d[0].url,p=u.includes("/api/")||u.startsWith("/api");if(p){if(c++,c===1&&!n)r.start()}try{return await a.apply(this,d)}finally{if(p){if(c--,c===0&&!n)r.finish()}}};window.fetch=l,pt=()=>{if(document.removeEventListener("click",o),window.removeEventListener("popstate",s),window.removeEventListener("load",i),window.fetch===l)window.fetch=a}}function w0(){if(pt)pt(),pt=null}function v0(e){let t={...ko,...e},r=t.initialColor?`linear-gradient(to right, ${t.initialColor}, ${t.color})`:t.color;return`
2978
+ `,document.head.appendChild(s)}return document.body.appendChild(r),r}function Jr(e,t){if(!Rt||!pe)return;if(Pe=Math.min(Math.max(e,0),100),ko)cancelAnimationFrame(ko);ko=requestAnimationFrame(()=>{if(!pe)return;pe.style.opacity=Pe>0?"1":"0",pe.style.transform=`scaleX(${Pe/100})`})}function Mf(e){if(!Rt)return;if(rr=!0,Pe=0,!pe)pe=zi(e);if(jt)clearTimeout(jt);if(He)clearInterval(He);Jr(10,e),He=setInterval(()=>{if(!rr)return;let t=90-Pe,r=Math.max(0.5,t*0.1);if(Pe<90)Jr(Pe+r,e)},e.throttle)}function Df(e){if(!Rt)return;if(rr=!1,He)clearInterval(He),He=null;Jr(100,e),jt=setTimeout(()=>{if(pe)pe.style.opacity="0";setTimeout(()=>{if(Pe=0,pe)pe.style.transform="scaleX(0)"},300)},200)}function Pf(){if(!Rt)return;if(rr=!1,Pe=0,He)clearInterval(He),He=null;if(jt)clearTimeout(jt),jt=null;if(pe)pe.style.opacity="0",pe.style.transform="scaleX(0)"}function Of(e){let t={...To,...e};return{start:()=>Mf(t),set:(r)=>Jr(r,t),finish:()=>Df(t),clear:()=>Pf(),get state(){return{isLoading:rr,progress:Pe,error:!1}}}}var ft=null;function w0(e){if(!Rt)return;if(ft)ft(),ft=null;let t={...To,...e},r=Of(t);pe=zi(t);let n=!1,o=(d)=>{let u=d.target.closest("a");if(!u)return;let p=u.getAttribute("href");if(!p)return;if(p.startsWith("http")||p.startsWith("#")||p.startsWith("mailto:")||p.startsWith("tel:")||u.target==="_blank"||u.hasAttribute("download"))return;n=!0,r.start()},s=()=>{if(!n)r.start(),n=!0},i=()=>{if(n||t.autoFinish)r.finish(),n=!1};document.addEventListener("click",o),window.addEventListener("popstate",s),window.addEventListener("load",i);let a=window.fetch,c=0,l=async function(...d){let u=typeof d[0]==="string"?d[0]:d[0].url,p=u.includes("/api/")||u.startsWith("/api");if(p){if(c++,c===1&&!n)r.start()}try{return await a.apply(this,d)}finally{if(p){if(c--,c===0&&!n)r.finish()}}};window.fetch=l,ft=()=>{if(document.removeEventListener("click",o),window.removeEventListener("popstate",s),window.removeEventListener("load",i),window.fetch===l)window.fetch=a}}function v0(){if(ft)ft(),ft=null}function $0(e){let t={...To,...e},r=t.initialColor?`linear-gradient(to right, ${t.initialColor}, ${t.color})`:t.color;return`
2979
2979
  <div id="stx-loading-indicator" style="
2980
2980
  position: fixed;
2981
2981
  top: 0;
@@ -3069,11 +3069,11 @@ ${v.trim().split(`
3069
3069
  window.addEventListener('load', function() { window.stxLoading.finish(); });
3070
3070
  })();
3071
3071
  </script>
3072
- `}class zi{instances=new Map;componentsByFile=new Map;stateSnapshots=new Map;config;constructor(e={}){this.config={preserveState:e.preserveState??!0,maxStateAge:e.maxStateAge??30000,errorRecovery:e.errorRecovery??!0,verbose:e.verbose??!1,serializeState:e.serializeState??this.defaultSerializeState.bind(this),deserializeState:e.deserializeState??this.defaultDeserializeState.bind(this)}}register(e){if(this.instances.set(e.id,e),!this.componentsByFile.has(e.name))this.componentsByFile.set(e.name,new Set);if(this.componentsByFile.get(e.name).add(e.id),this.config.verbose)console.log(`[HMR] Registered component: ${e.name} (${e.id})`)}unregister(e){let t=this.instances.get(e);if(!t)return;if(this.componentsByFile.get(t.name)?.delete(e),this.componentsByFile.get(t.name)?.size===0)this.componentsByFile.delete(t.name);if(this.stateSnapshots.delete(e),t.cleanup?.(),this.instances.delete(e),this.config.verbose)console.log(`[HMR] Unregistered component: ${t.name} (${e})`)}getInstancesByFile(e){let t=this.componentsByFile.get(e)||new Set;return Array.from(t).map((r)=>this.instances.get(r)).filter(Boolean)}getInstance(e){return this.instances.get(e)}captureState(e){let t=this.instances.get(e);if(!t||!this.config.preserveState)return;let r=this.config.serializeState(t);if(this.stateSnapshots.set(e,r),this.config.verbose)console.log(`[HMR] Captured state for: ${t.name}`)}restoreState(e){let t=this.instances.get(e),r=this.stateSnapshots.get(e);if(!t||!r||!this.config.preserveState)return!1;if(Date.now()-r.timestamp>this.config.maxStateAge){if(this.stateSnapshots.delete(e),this.config.verbose)console.log(`[HMR] State expired for: ${t.name}`);return!1}try{if(this.config.deserializeState(r,t),this.config.verbose)console.log(`[HMR] Restored state for: ${t.name}`);return!0}catch(n){return console.error(`[HMR] Failed to restore state for ${t.name}:`,n),!1}}defaultSerializeState(e){let t={},r={};if(e.element)e.element.querySelectorAll("[data-stx-ref]").forEach((n)=>{let o=n.getAttribute("data-stx-ref"),s=n.getAttribute("data-stx-value");if(o&&s)try{t[o]=JSON.parse(s)}catch{t[o]=s}});return{refs:t,reactiveObjects:r,custom:e.state?.custom||{},timestamp:Date.now()}}defaultDeserializeState(e,t){if(t.element)Object.entries(e.refs).forEach(([r,n])=>{let o=t.element.querySelector(`[data-stx-ref="${r}"]`);if(o)o.setAttribute("data-stx-value",JSON.stringify(n)),o.dispatchEvent(new CustomEvent("stx:state-restored",{detail:{name:r,value:n},bubbles:!0}))});t.state={...e,timestamp:Date.now()}}getAllInstances(){return Array.from(this.instances.values())}clear(){for(let e of this.instances.values())e.cleanup?.();this.instances.clear(),this.componentsByFile.clear(),this.stateSnapshots.clear()}}class Ui{registry;config;pendingUpdates=new Map;updateQueue=Promise.resolve();constructor(e={}){this.config={preserveState:e.preserveState??!0,maxStateAge:e.maxStateAge??30000,errorRecovery:e.errorRecovery??!0,verbose:e.verbose??!1,serializeState:e.serializeState??(()=>({refs:{},reactiveObjects:{},custom:{},timestamp:Date.now()})),deserializeState:e.deserializeState??(()=>{})},this.registry=new zi(this.config)}register(e){this.registry.register(e)}unregister(e){this.registry.unregister(e)}async handleUpdate(e){return this.updateQueue=this.updateQueue.then(()=>this.processUpdate(e)),this.updateQueue}async processUpdate(e){let t=this.registry.getInstancesByFile(e.file);if(t.length===0){if(this.config.verbose)console.log(`[HMR] No instances found for: ${e.file}`);return}if(this.config.verbose)console.log(`[HMR] Updating ${t.length} instance(s) of: ${e.file}`);for(let r of t)await this.updateInstance(r,e);if(typeof window<"u"&&typeof window.dispatchEvent==="function")window.dispatchEvent(new CustomEvent("stx:hmr-update",{detail:{file:e.file,count:t.length}}))}async updateInstance(e,t){this.registry.captureState(e.id);let r=!1,n=e.element?.innerHTML||"";try{if(e.element?.dispatchEvent(new CustomEvent("stx:before-hmr-update",{bubbles:!0})),e.cleanup?.(),t.type==="style")await this.updateStyles(e,t);else await this.updateComponent(e,t);let o=this.registry.restoreState(e.id);if(!o&&e.setup)await e.setup();e.element?.dispatchEvent(new CustomEvent("stx:after-hmr-update",{detail:{stateRestored:o},bubbles:!0}))}catch(o){if(r=!0,console.error(`[HMR] Error updating component ${e.name}:`,o),this.config.errorRecovery){if(e.element&&n)e.element.innerHTML=n,console.log(`[HMR] Recovered previous state for: ${e.name}`);e.element?.dispatchEvent(new CustomEvent("stx:hmr-error",{detail:{error:o},bubbles:!0}))}}if(!r&&this.config.verbose)console.log(`[HMR] Successfully updated: ${e.name}`)}async updateComponent(e,t){if(!e.element)return;let{html:r,script:n}=this.parseComponentCode(t.code);if(r)e.element.innerHTML=r;if(n)await this.executeScript(n,e);if(e.render)e.element.innerHTML=e.render();this.reinitializeInteractivity(e)}async updateStyles(e,t){if(!e.element)return;let r=t.code.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(!r)return;let n=r[1],o=e.id,s=document.querySelector(`style[data-stx-component="${o}"]`);if(!s)s=document.createElement("style"),s.setAttribute("data-stx-component",o),document.head.appendChild(s);if(s.textContent=n,this.config.verbose)console.log(`[HMR] Updated styles for: ${e.name}`)}parseComponentCode(e){let t=e,r="",n="",o=e.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(o)r=o[1],t=t.replace(o[0],"");let s=e.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(s)n=s[1],t=t.replace(s[0],"");return{html:t.trim(),script:r.trim(),style:n.trim()}}async executeScript(e,t){try{let r={element:t.element,props:t.props,...typeof window<"u"?window.stx:{}},n=`
3072
+ `}class Ui{instances=new Map;componentsByFile=new Map;stateSnapshots=new Map;config;constructor(e={}){this.config={preserveState:e.preserveState??!0,maxStateAge:e.maxStateAge??30000,errorRecovery:e.errorRecovery??!0,verbose:e.verbose??!1,serializeState:e.serializeState??this.defaultSerializeState.bind(this),deserializeState:e.deserializeState??this.defaultDeserializeState.bind(this)}}register(e){if(this.instances.set(e.id,e),!this.componentsByFile.has(e.name))this.componentsByFile.set(e.name,new Set);if(this.componentsByFile.get(e.name).add(e.id),this.config.verbose)console.log(`[HMR] Registered component: ${e.name} (${e.id})`)}unregister(e){let t=this.instances.get(e);if(!t)return;if(this.componentsByFile.get(t.name)?.delete(e),this.componentsByFile.get(t.name)?.size===0)this.componentsByFile.delete(t.name);if(this.stateSnapshots.delete(e),t.cleanup?.(),this.instances.delete(e),this.config.verbose)console.log(`[HMR] Unregistered component: ${t.name} (${e})`)}getInstancesByFile(e){let t=this.componentsByFile.get(e)||new Set;return Array.from(t).map((r)=>this.instances.get(r)).filter(Boolean)}getInstance(e){return this.instances.get(e)}captureState(e){let t=this.instances.get(e);if(!t||!this.config.preserveState)return;let r=this.config.serializeState(t);if(this.stateSnapshots.set(e,r),this.config.verbose)console.log(`[HMR] Captured state for: ${t.name}`)}restoreState(e){let t=this.instances.get(e),r=this.stateSnapshots.get(e);if(!t||!r||!this.config.preserveState)return!1;if(Date.now()-r.timestamp>this.config.maxStateAge){if(this.stateSnapshots.delete(e),this.config.verbose)console.log(`[HMR] State expired for: ${t.name}`);return!1}try{if(this.config.deserializeState(r,t),this.config.verbose)console.log(`[HMR] Restored state for: ${t.name}`);return!0}catch(n){return console.error(`[HMR] Failed to restore state for ${t.name}:`,n),!1}}defaultSerializeState(e){let t={},r={};if(e.element)e.element.querySelectorAll("[data-stx-ref]").forEach((n)=>{let o=n.getAttribute("data-stx-ref"),s=n.getAttribute("data-stx-value");if(o&&s)try{t[o]=JSON.parse(s)}catch{t[o]=s}});return{refs:t,reactiveObjects:r,custom:e.state?.custom||{},timestamp:Date.now()}}defaultDeserializeState(e,t){if(t.element)Object.entries(e.refs).forEach(([r,n])=>{let o=t.element.querySelector(`[data-stx-ref="${r}"]`);if(o)o.setAttribute("data-stx-value",JSON.stringify(n)),o.dispatchEvent(new CustomEvent("stx:state-restored",{detail:{name:r,value:n},bubbles:!0}))});t.state={...e,timestamp:Date.now()}}getAllInstances(){return Array.from(this.instances.values())}clear(){for(let e of this.instances.values())e.cleanup?.();this.instances.clear(),this.componentsByFile.clear(),this.stateSnapshots.clear()}}class Hi{registry;config;pendingUpdates=new Map;updateQueue=Promise.resolve();constructor(e={}){this.config={preserveState:e.preserveState??!0,maxStateAge:e.maxStateAge??30000,errorRecovery:e.errorRecovery??!0,verbose:e.verbose??!1,serializeState:e.serializeState??(()=>({refs:{},reactiveObjects:{},custom:{},timestamp:Date.now()})),deserializeState:e.deserializeState??(()=>{})},this.registry=new Ui(this.config)}register(e){this.registry.register(e)}unregister(e){this.registry.unregister(e)}async handleUpdate(e){return this.updateQueue=this.updateQueue.then(()=>this.processUpdate(e)),this.updateQueue}async processUpdate(e){let t=this.registry.getInstancesByFile(e.file);if(t.length===0){if(this.config.verbose)console.log(`[HMR] No instances found for: ${e.file}`);return}if(this.config.verbose)console.log(`[HMR] Updating ${t.length} instance(s) of: ${e.file}`);for(let r of t)await this.updateInstance(r,e);if(typeof window<"u"&&typeof window.dispatchEvent==="function")window.dispatchEvent(new CustomEvent("stx:hmr-update",{detail:{file:e.file,count:t.length}}))}async updateInstance(e,t){this.registry.captureState(e.id);let r=!1,n=e.element?.innerHTML||"";try{if(e.element?.dispatchEvent(new CustomEvent("stx:before-hmr-update",{bubbles:!0})),e.cleanup?.(),t.type==="style")await this.updateStyles(e,t);else await this.updateComponent(e,t);let o=this.registry.restoreState(e.id);if(!o&&e.setup)await e.setup();e.element?.dispatchEvent(new CustomEvent("stx:after-hmr-update",{detail:{stateRestored:o},bubbles:!0}))}catch(o){if(r=!0,console.error(`[HMR] Error updating component ${e.name}:`,o),this.config.errorRecovery){if(e.element&&n)e.element.innerHTML=n,console.log(`[HMR] Recovered previous state for: ${e.name}`);e.element?.dispatchEvent(new CustomEvent("stx:hmr-error",{detail:{error:o},bubbles:!0}))}}if(!r&&this.config.verbose)console.log(`[HMR] Successfully updated: ${e.name}`)}async updateComponent(e,t){if(!e.element)return;let{html:r,script:n}=this.parseComponentCode(t.code);if(r)e.element.innerHTML=r;if(n)await this.executeScript(n,e);if(e.render)e.element.innerHTML=e.render();this.reinitializeInteractivity(e)}async updateStyles(e,t){if(!e.element)return;let r=t.code.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(!r)return;let n=r[1],o=e.id,s=document.querySelector(`style[data-stx-component="${o}"]`);if(!s)s=document.createElement("style"),s.setAttribute("data-stx-component",o),document.head.appendChild(s);if(s.textContent=n,this.config.verbose)console.log(`[HMR] Updated styles for: ${e.name}`)}parseComponentCode(e){let t=e,r="",n="",o=e.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(o)r=o[1],t=t.replace(o[0],"");let s=e.match(/<style\b[^>]*>([\s\S]*?)<\/style>/i);if(s)n=s[1],t=t.replace(s[0],"");return{html:t.trim(),script:r.trim(),style:n.trim()}}async executeScript(e,t){try{let r={element:t.element,props:t.props,...typeof window<"u"?window.stx:{}},n=`
3073
3073
  return (async function() {
3074
3074
  ${e}
3075
3075
  })()
3076
- `;await Function(...Object.keys(r),n)(...Object.values(r))}catch(r){throw console.error("[HMR] Script execution error:",r),r}}reinitializeInteractivity(e){if(!e.element)return;e.element.querySelectorAll("[data-stx-events]").forEach((t)=>{let r=t.getAttribute("data-stx-events");if(!r)return;try{let n=JSON.parse(r);for(let[o,s]of Object.entries(n))if(typeof window<"u"&&window.stx?.[s])t.addEventListener(o,window.stx[s])}catch{}}),e.element.dispatchEvent(new CustomEvent("stx:reinitialize",{bubbles:!0}))}getRegistry(){return this.registry}async refresh(e){let t=this.registry.getInstancesByFile(e);for(let r of t)if(r.render&&r.element)this.registry.captureState(r.id),r.element.innerHTML=r.render(),this.registry.restoreState(r.id),this.reinitializeInteractivity(r)}}function S0(e){return`
3076
+ `;await Function(...Object.keys(r),n)(...Object.values(r))}catch(r){throw console.error("[HMR] Script execution error:",r),r}}reinitializeInteractivity(e){if(!e.element)return;e.element.querySelectorAll("[data-stx-events]").forEach((t)=>{let r=t.getAttribute("data-stx-events");if(!r)return;try{let n=JSON.parse(r);for(let[o,s]of Object.entries(n))if(typeof window<"u"&&window.stx?.[s])t.addEventListener(o,window.stx[s])}catch{}}),e.element.dispatchEvent(new CustomEvent("stx:reinitialize",{bubbles:!0}))}getRegistry(){return this.registry}async refresh(e){let t=this.registry.getInstancesByFile(e);for(let r of t)if(r.render&&r.element)this.registry.captureState(r.id),r.element.innerHTML=r.render(),this.registry.restoreState(r.id),this.reinitializeInteractivity(r)}}function k0(e){return`
3077
3077
  <script data-stx-hmr-client>
3078
3078
  (function() {
3079
3079
  'use strict';
@@ -3300,7 +3300,7 @@ else {
3300
3300
  };
3301
3301
  })();
3302
3302
  </script>
3303
- `}function k0(e,t,r,n){return`
3303
+ `}function T0(e,t,r,n){return`
3304
3304
  <div data-stx-component="${e}" data-stx-name="${t}">
3305
3305
  ${r}
3306
3306
  </div>
@@ -3340,8 +3340,8 @@ else {
3340
3340
  observer.observe(document.body, { childList: true, subtree: true });
3341
3341
  })();
3342
3342
  </script>
3343
- `}var Rt=null;function T0(e){if(!Rt)Rt=new Ui(e);return Rt}function C0(){if(Rt)Rt.getRegistry().clear(),Rt=null}function Of(e){let t={refs:e.refs||{},reactive:e.reactive||{},props:e.props||{},routeParams:e.routeParams||{},stores:e.stores||{},meta:e.meta||{},timestamp:Date.now()};return t.checksum=Hi(t),JSON.stringify(t).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/'/g,"\\u0027")}function Hi(e){let t=JSON.stringify({refs:Object.keys(e.refs||{}),reactive:Object.keys(e.reactive||{}),props:Object.keys(e.props||{})}),r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);r=(r<<5)-r+o,r=r&r}return Math.abs(r).toString(36)}function If(e){return`<script id="__STX_STATE__" type="application/json">${Of(e)}</script>`}function _0(e){if(e.length===0)return"";return`data-stx-events='${JSON.stringify(e)}'`}function Lf(){if(typeof window>"u")return null;let e=document.getElementById("__STX_STATE__");if(!e)return null;try{let t=JSON.parse(e.textContent||"{}");if(t.checksum){if(Hi(t)!==t.checksum)console.warn("[Hydration] State checksum mismatch - state may be corrupted")}return t}catch(t){return console.error("[Hydration] Failed to parse state:",t),null}}class Wi{state=null;options;root=null;isHydrated=!1;pendingComponents=new Map;hydratedComponents=new Set;constructor(e={}){this.options={root:e.root||"#app",strict:e.strict??!1,onHydrating:e.onHydrating||(()=>{}),onHydrated:e.onHydrated||(()=>{}),onError:e.onError||console.error,performance:e.performance??!1,timeout:e.timeout??1e4}}async hydrate(){if(typeof window>"u")return;if(this.isHydrated)return;let e=this.options.performance?performance.now():0;try{this.root=typeof this.options.root==="string"?document.querySelector(this.options.root)||document.body:this.options.root,this.state=Lf(),this.options.onHydrating(),this.root.classList.add("stx-hydrating");let t=new Promise((r,n)=>{setTimeout(()=>n(Error("Hydration timeout")),this.options.timeout)});if(await Promise.race([this.runHydration(),t]),this.isHydrated=!0,this.root.classList.remove("stx-hydrating"),this.root.classList.add("stx-hydrated"),this.options.performance){let r=performance.now()-e;console.log(`[Hydration] Completed in ${r.toFixed(2)}ms`)}this.options.onHydrated(),window.dispatchEvent(new CustomEvent("stx:hydrated"))}catch(t){this.root?.classList.remove("stx-hydrating"),this.root?.classList.add("stx-hydration-error"),this.options.onError(t),window.dispatchEvent(new CustomEvent("stx:hydration-error",{detail:{error:t}}))}}async runHydration(){if(!this.root)return;this.restoreGlobalState(),await this.hydrateComponents(),this.bindEventHandlers(),this.initializeReactiveBindings(),this.setupRouterIntegration()}restoreGlobalState(){if(!this.state)return;let e=window.stx;if(!e)return;if(this.state.routeParams&&e.setRouteParams)e.setRouteParams(this.state.routeParams);if(this.state.stores&&e.registerStore)Object.entries(this.state.stores).forEach(([t,r])=>{e.registerStore(t,r)});window.dispatchEvent(new CustomEvent("stx:state-restored",{detail:this.state}))}async hydrateComponents(){if(!this.root)return;let e=this.root.querySelectorAll("[data-stx-component]");for(let t of Array.from(e)){let r=t.getAttribute("data-stx-component"),n=t.getAttribute("data-stx-name")||r,o=t.getAttribute("data-stx-hydrate")||"eager",s=t.getAttribute("data-stx-props");if(!r)continue;let i={id:r,name:n||r,strategy:o,props:s?JSON.parse(s):{},events:[]};switch(this.pendingComponents.set(r,i),i.strategy){case"eager":await this.hydrateComponent(t,i);break;case"lazy":case"visible":this.setupVisibleHydration(t,i);break;case"idle":this.setupIdleHydration(t,i);break;case"interaction":this.setupInteractionHydration(t,i);break}}}async hydrateComponent(e,t){if(this.hydratedComponents.has(t.id))return;try{let r=this.state?.refs[t.id]||this.state?.reactive[t.id]||{};this.restoreComponentState(e,r),this.bindComponentEvents(e),this.initializeComponentReactivity(e,t),this.hydratedComponents.add(t.id),e.classList.add("stx-hydrated"),e.setAttribute("data-hydrated","true"),e.dispatchEvent(new CustomEvent("stx:component-hydrated",{detail:{id:t.id,name:t.name},bubbles:!0}))}catch(r){if(console.error(`[Hydration] Failed to hydrate component ${t.id}:`,r),e.classList.add("stx-hydration-error"),this.options.strict)throw r}}restoreComponentState(e,t){if(!t||typeof t!=="object")return;e.querySelectorAll("[data-stx-bind]").forEach((r)=>{let n=r.getAttribute("data-stx-bind");if(!n||!t[n])return;let o=t[n];if(r instanceof HTMLInputElement)if(r.type==="checkbox"||r.type==="radio")r.checked=Boolean(o);else r.value=String(o);else if(r instanceof HTMLSelectElement)r.value=String(o);else if(r instanceof HTMLTextAreaElement)r.value=String(o);else r.textContent=String(o)})}setupVisibleHydration(e,t){if(!("IntersectionObserver"in window)){this.hydrateComponent(e,t);return}let r=new IntersectionObserver((n)=>{n.forEach((o)=>{if(o.isIntersecting)r.disconnect(),this.hydrateComponent(e,t)})},{rootMargin:"100px",threshold:0});r.observe(e)}setupIdleHydration(e,t){let r=()=>this.hydrateComponent(e,t);if("requestIdleCallback"in window)window.requestIdleCallback(r,{timeout:2000});else setTimeout(r,200)}setupInteractionHydration(e,t){let r=["mouseenter","touchstart","focusin"],n=()=>{r.forEach((o)=>e.removeEventListener(o,n)),this.hydrateComponent(e,t)};r.forEach((o)=>{e.addEventListener(o,n,{once:!0,passive:!0})})}bindEventHandlers(){if(!this.root)return;this.root.querySelectorAll("[data-stx-events]").forEach((e)=>this.bindElementEvents(e)),this.bindDirectiveEvents()}bindElementEvents(e){let t=e.getAttribute("data-stx-events");if(!t)return;try{JSON.parse(t).forEach((r)=>{this.bindSingleEvent(e,r)})}catch(r){console.error("[Hydration] Failed to parse events:",r)}}bindDirectiveEvents(){if(!this.root)return;["click","submit","input","change","focus","blur","keydown","keyup","keypress","mouseenter","mouseleave","touchstart","touchend","scroll","resize"].forEach((e)=>{let t=`data-stx-on-${e}`;this.root.querySelectorAll(`[${t}]`).forEach((r)=>{let n=r.getAttribute(t);if(!n)return;this.bindSingleEvent(r,{type:e,handler:n,modifiers:this.parseModifiers(r,e)})})})}parseModifiers(e,t){let r=[],n=e.getAttribute(`data-stx-${t}-modifiers`);if(n)r.push(...n.split(",").map((o)=>o.trim()));return r}bindSingleEvent(e,t){let r=this.resolveHandler(t.handler);if(!r){console.warn(`[Hydration] Handler not found: ${t.handler}`);return}let n=(s)=>{if(t.modifiers?.includes("prevent")||t.preventDefault)s.preventDefault();if(t.modifiers?.includes("stop")||t.stopPropagation)s.stopPropagation();try{r.call(e,s)}catch(i){console.error("[Hydration] Event handler error:",i)}},o={};if(t.modifiers?.includes("once"))o.once=!0;if(t.modifiers?.includes("passive"))o.passive=!0;if(t.modifiers?.includes("capture"))o.capture=!0;e.addEventListener(t.type,n,o)}resolveHandler(e){let t=window.stx;if(t&&t[e])return t[e];if(window[e])return window[e];try{if(e.match(/^\w+\+\+$/)||e.match(/^\w+--$/)){let o=e.replace(/[+-]+$/,"");return()=>{if(t&&t[o]){if(typeof t[o].value<"u")if(e.includes("++"))t[o].value++;else t[o].value--}}}let r=e.match(/^(\w+)\s*=\s*(.+)$/);if(r){let[,o,s]=r;return()=>{if(t&&t[o]){let i=Function(`return ${s}`)();if(typeof t[o].value<"u")t[o].value=i}}}let n=e.match(/^(\w+)\((.*)\)$/);if(n){let[,o,s]=n;return(i)=>{let a=t?.[o]||window[o];if(a){let c=s?Function("$event",`return [${s}]`)(i):[];a(...c)}}}return(o)=>{Function("$event","stx",e)(o,t)}}catch{return null}}bindComponentEvents(e){e.querySelectorAll("[data-stx-events]").forEach((t)=>{this.bindElementEvents(t)})}initializeComponentReactivity(e,t){if(!window.stx)return;e.querySelectorAll("[data-stx-reactive]").forEach((r)=>{let n=r.getAttribute("data-stx-reactive");if(!n)return;this.setupReactiveBinding(r,n)})}initializeReactiveBindings(){if(!this.root)return;this.getTextNodesWithExpressions(this.root).forEach(({node:e,expressions:t})=>{t.forEach((r)=>{this.setupTextNodeBinding(e,r)})}),this.root.querySelectorAll("[data-stx-bind-attrs]").forEach((e)=>{let t=e.getAttribute("data-stx-bind-attrs");if(!t)return;try{let r=JSON.parse(t);Object.entries(r).forEach(([n,o])=>{this.setupAttributeBinding(e,n,o)})}catch{}})}getTextNodesWithExpressions(e){let t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n;while(n=r.nextNode()){let o=(n.textContent||"").match(/\{\{\s*([^}]+)\s*\}\}/g);if(o)t.push({node:n,expressions:o.map((s)=>s.replace(/\{\{\s*|\s*\}\}/g,""))})}return t}setupTextNodeBinding(e,t){let r=window.stx;if(!r)return;let n=e.textContent||"",o=()=>{try{let i=Function("stx",`with(stx) { return ${t} }`)(r);e.textContent=n.replace(new RegExp(`\\{\\{\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\}\\}`),String(i))}catch{}};o();let s=t.match(/^(\w+)(\.value)?$/);if(s&&r[s[1]]?.subscribe)r[s[1]].subscribe(o)}setupAttributeBinding(e,t,r){let n=window.stx;if(!n)return;let o=()=>{try{let i=Function("stx",`with(stx) { return ${r} }`)(n);if(typeof i==="boolean")if(i)e.setAttribute(t,"");else e.removeAttribute(t);else e.setAttribute(t,String(i))}catch{}};o();let s=r.match(/^(\w+)(\.value)?$/);if(s&&n[s[1]]?.subscribe)n[s[1]].subscribe(o)}setupReactiveBinding(e,t){let r=window.stx;if(!r)return;let n=()=>{try{let s=Function("stx",`with(stx) { return ${t} }`)(r);e.textContent=String(s)}catch{}};n();let o=t.match(/^(\w+)(\.value)?$/);if(o&&r[o[1]]?.subscribe)r[o[1]].subscribe(n)}setupRouterIntegration(){window.addEventListener("stx:navigate",(e)=>{let{url:t}=e.detail||{};if(t){if(window.stx?.setRouteParams){let r=new URL(t,window.location.origin)}}}),window.addEventListener("stx:load",()=>{this.hydrateComponents(),this.bindEventHandlers()})}get hydrated(){return this.isHydrated}getState(){return this.state}async hydrateById(e){let t=this.pendingComponents.get(e),r=document.querySelector(`[data-stx-component="${e}"]`);if(t&&r)await this.hydrateComponent(r,t)}}function A0(e){return`
3344
- ${e?If(e):""}
3343
+ `}var Mt=null;function C0(e){if(!Mt)Mt=new Hi(e);return Mt}function E0(){if(Mt)Mt.getRegistry().clear(),Mt=null}function If(e){let t={refs:e.refs||{},reactive:e.reactive||{},props:e.props||{},routeParams:e.routeParams||{},stores:e.stores||{},meta:e.meta||{},timestamp:Date.now()};return t.checksum=Wi(t),JSON.stringify(t).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/'/g,"\\u0027")}function Wi(e){let t=JSON.stringify({refs:Object.keys(e.refs||{}),reactive:Object.keys(e.reactive||{}),props:Object.keys(e.props||{})}),r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);r=(r<<5)-r+o,r=r&r}return Math.abs(r).toString(36)}function Lf(e){return`<script id="__STX_STATE__" type="application/json">${If(e)}</script>`}function A0(e){if(e.length===0)return"";return`data-stx-events='${JSON.stringify(e)}'`}function Ff(){if(typeof window>"u")return null;let e=document.getElementById("__STX_STATE__");if(!e)return null;try{let t=JSON.parse(e.textContent||"{}");if(t.checksum){if(Wi(t)!==t.checksum)console.warn("[Hydration] State checksum mismatch - state may be corrupted")}return t}catch(t){return console.error("[Hydration] Failed to parse state:",t),null}}class Vi{state=null;options;root=null;isHydrated=!1;pendingComponents=new Map;hydratedComponents=new Set;constructor(e={}){this.options={root:e.root||"#app",strict:e.strict??!1,onHydrating:e.onHydrating||(()=>{}),onHydrated:e.onHydrated||(()=>{}),onError:e.onError||console.error,performance:e.performance??!1,timeout:e.timeout??1e4}}async hydrate(){if(typeof window>"u")return;if(this.isHydrated)return;let e=this.options.performance?performance.now():0;try{this.root=typeof this.options.root==="string"?document.querySelector(this.options.root)||document.body:this.options.root,this.state=Ff(),this.options.onHydrating(),this.root.classList.add("stx-hydrating");let t=new Promise((r,n)=>{setTimeout(()=>n(Error("Hydration timeout")),this.options.timeout)});if(await Promise.race([this.runHydration(),t]),this.isHydrated=!0,this.root.classList.remove("stx-hydrating"),this.root.classList.add("stx-hydrated"),this.options.performance){let r=performance.now()-e;console.log(`[Hydration] Completed in ${r.toFixed(2)}ms`)}this.options.onHydrated(),window.dispatchEvent(new CustomEvent("stx:hydrated"))}catch(t){this.root?.classList.remove("stx-hydrating"),this.root?.classList.add("stx-hydration-error"),this.options.onError(t),window.dispatchEvent(new CustomEvent("stx:hydration-error",{detail:{error:t}}))}}async runHydration(){if(!this.root)return;this.restoreGlobalState(),await this.hydrateComponents(),this.bindEventHandlers(),this.initializeReactiveBindings(),this.setupRouterIntegration()}restoreGlobalState(){if(!this.state)return;let e=window.stx;if(!e)return;if(this.state.routeParams&&e.setRouteParams)e.setRouteParams(this.state.routeParams);if(this.state.stores&&e.registerStore)Object.entries(this.state.stores).forEach(([t,r])=>{e.registerStore(t,r)});window.dispatchEvent(new CustomEvent("stx:state-restored",{detail:this.state}))}async hydrateComponents(){if(!this.root)return;let e=this.root.querySelectorAll("[data-stx-component]");for(let t of Array.from(e)){let r=t.getAttribute("data-stx-component"),n=t.getAttribute("data-stx-name")||r,o=t.getAttribute("data-stx-hydrate")||"eager",s=t.getAttribute("data-stx-props");if(!r)continue;let i={id:r,name:n||r,strategy:o,props:s?JSON.parse(s):{},events:[]};switch(this.pendingComponents.set(r,i),i.strategy){case"eager":await this.hydrateComponent(t,i);break;case"lazy":case"visible":this.setupVisibleHydration(t,i);break;case"idle":this.setupIdleHydration(t,i);break;case"interaction":this.setupInteractionHydration(t,i);break}}}async hydrateComponent(e,t){if(this.hydratedComponents.has(t.id))return;try{let r=this.state?.refs[t.id]||this.state?.reactive[t.id]||{};this.restoreComponentState(e,r),this.bindComponentEvents(e),this.initializeComponentReactivity(e,t),this.hydratedComponents.add(t.id),e.classList.add("stx-hydrated"),e.setAttribute("data-hydrated","true"),e.dispatchEvent(new CustomEvent("stx:component-hydrated",{detail:{id:t.id,name:t.name},bubbles:!0}))}catch(r){if(console.error(`[Hydration] Failed to hydrate component ${t.id}:`,r),e.classList.add("stx-hydration-error"),this.options.strict)throw r}}restoreComponentState(e,t){if(!t||typeof t!=="object")return;e.querySelectorAll("[data-stx-bind]").forEach((r)=>{let n=r.getAttribute("data-stx-bind");if(!n||!t[n])return;let o=t[n];if(r instanceof HTMLInputElement)if(r.type==="checkbox"||r.type==="radio")r.checked=Boolean(o);else r.value=String(o);else if(r instanceof HTMLSelectElement)r.value=String(o);else if(r instanceof HTMLTextAreaElement)r.value=String(o);else r.textContent=String(o)})}setupVisibleHydration(e,t){if(!("IntersectionObserver"in window)){this.hydrateComponent(e,t);return}let r=new IntersectionObserver((n)=>{n.forEach((o)=>{if(o.isIntersecting)r.disconnect(),this.hydrateComponent(e,t)})},{rootMargin:"100px",threshold:0});r.observe(e)}setupIdleHydration(e,t){let r=()=>this.hydrateComponent(e,t);if("requestIdleCallback"in window)window.requestIdleCallback(r,{timeout:2000});else setTimeout(r,200)}setupInteractionHydration(e,t){let r=["mouseenter","touchstart","focusin"],n=()=>{r.forEach((o)=>e.removeEventListener(o,n)),this.hydrateComponent(e,t)};r.forEach((o)=>{e.addEventListener(o,n,{once:!0,passive:!0})})}bindEventHandlers(){if(!this.root)return;this.root.querySelectorAll("[data-stx-events]").forEach((e)=>this.bindElementEvents(e)),this.bindDirectiveEvents()}bindElementEvents(e){let t=e.getAttribute("data-stx-events");if(!t)return;try{JSON.parse(t).forEach((r)=>{this.bindSingleEvent(e,r)})}catch(r){console.error("[Hydration] Failed to parse events:",r)}}bindDirectiveEvents(){if(!this.root)return;["click","submit","input","change","focus","blur","keydown","keyup","keypress","mouseenter","mouseleave","touchstart","touchend","scroll","resize"].forEach((e)=>{let t=`data-stx-on-${e}`;this.root.querySelectorAll(`[${t}]`).forEach((r)=>{let n=r.getAttribute(t);if(!n)return;this.bindSingleEvent(r,{type:e,handler:n,modifiers:this.parseModifiers(r,e)})})})}parseModifiers(e,t){let r=[],n=e.getAttribute(`data-stx-${t}-modifiers`);if(n)r.push(...n.split(",").map((o)=>o.trim()));return r}bindSingleEvent(e,t){let r=this.resolveHandler(t.handler);if(!r){console.warn(`[Hydration] Handler not found: ${t.handler}`);return}let n=(s)=>{if(t.modifiers?.includes("prevent")||t.preventDefault)s.preventDefault();if(t.modifiers?.includes("stop")||t.stopPropagation)s.stopPropagation();try{r.call(e,s)}catch(i){console.error("[Hydration] Event handler error:",i)}},o={};if(t.modifiers?.includes("once"))o.once=!0;if(t.modifiers?.includes("passive"))o.passive=!0;if(t.modifiers?.includes("capture"))o.capture=!0;e.addEventListener(t.type,n,o)}resolveHandler(e){let t=window.stx;if(t&&t[e])return t[e];if(window[e])return window[e];try{if(e.match(/^\w+\+\+$/)||e.match(/^\w+--$/)){let o=e.replace(/[+-]+$/,"");return()=>{if(t&&t[o]){if(typeof t[o].value<"u")if(e.includes("++"))t[o].value++;else t[o].value--}}}let r=e.match(/^(\w+)\s*=\s*(.+)$/);if(r){let[,o,s]=r;return()=>{if(t&&t[o]){let i=Function(`return ${s}`)();if(typeof t[o].value<"u")t[o].value=i}}}let n=e.match(/^(\w+)\((.*)\)$/);if(n){let[,o,s]=n;return(i)=>{let a=t?.[o]||window[o];if(a){let c=s?Function("$event",`return [${s}]`)(i):[];a(...c)}}}return(o)=>{Function("$event","stx",e)(o,t)}}catch{return null}}bindComponentEvents(e){e.querySelectorAll("[data-stx-events]").forEach((t)=>{this.bindElementEvents(t)})}initializeComponentReactivity(e,t){if(!window.stx)return;e.querySelectorAll("[data-stx-reactive]").forEach((r)=>{let n=r.getAttribute("data-stx-reactive");if(!n)return;this.setupReactiveBinding(r,n)})}initializeReactiveBindings(){if(!this.root)return;this.getTextNodesWithExpressions(this.root).forEach(({node:e,expressions:t})=>{t.forEach((r)=>{this.setupTextNodeBinding(e,r)})}),this.root.querySelectorAll("[data-stx-bind-attrs]").forEach((e)=>{let t=e.getAttribute("data-stx-bind-attrs");if(!t)return;try{let r=JSON.parse(t);Object.entries(r).forEach(([n,o])=>{this.setupAttributeBinding(e,n,o)})}catch{}})}getTextNodesWithExpressions(e){let t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n;while(n=r.nextNode()){let o=(n.textContent||"").match(/\{\{\s*([^}]+)\s*\}\}/g);if(o)t.push({node:n,expressions:o.map((s)=>s.replace(/\{\{\s*|\s*\}\}/g,""))})}return t}setupTextNodeBinding(e,t){let r=window.stx;if(!r)return;let n=e.textContent||"",o=()=>{try{let i=Function("stx",`with(stx) { return ${t} }`)(r);e.textContent=n.replace(new RegExp(`\\{\\{\\s*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\}\\}`),String(i))}catch{}};o();let s=t.match(/^(\w+)(\.value)?$/);if(s&&r[s[1]]?.subscribe)r[s[1]].subscribe(o)}setupAttributeBinding(e,t,r){let n=window.stx;if(!n)return;let o=()=>{try{let i=Function("stx",`with(stx) { return ${r} }`)(n);if(typeof i==="boolean")if(i)e.setAttribute(t,"");else e.removeAttribute(t);else e.setAttribute(t,String(i))}catch{}};o();let s=r.match(/^(\w+)(\.value)?$/);if(s&&n[s[1]]?.subscribe)n[s[1]].subscribe(o)}setupReactiveBinding(e,t){let r=window.stx;if(!r)return;let n=()=>{try{let s=Function("stx",`with(stx) { return ${t} }`)(r);e.textContent=String(s)}catch{}};n();let o=t.match(/^(\w+)(\.value)?$/);if(o&&r[o[1]]?.subscribe)r[o[1]].subscribe(n)}setupRouterIntegration(){window.addEventListener("stx:navigate",(e)=>{let{url:t}=e.detail||{};if(t){if(window.stx?.setRouteParams){let r=new URL(t,window.location.origin)}}}),window.addEventListener("stx:load",()=>{this.hydrateComponents(),this.bindEventHandlers()})}get hydrated(){return this.isHydrated}getState(){return this.state}async hydrateById(e){let t=this.pendingComponents.get(e),r=document.querySelector(`[data-stx-component="${e}"]`);if(t&&r)await this.hydrateComponent(r,t)}}function j0(e){return`
3344
+ ${e?Lf(e):""}
3345
3345
  <script data-stx-hydration-runtime>
3346
3346
  (function() {
3347
3347
  'use strict';
@@ -3438,7 +3438,7 @@ else {
3438
3438
  }
3439
3439
  })();
3440
3440
  </script>
3441
- `}var To=null;function Ff(e){if(!To)To=new Wi(e);return To}async function j0(e){await Ff(e).hydrate()}function R0(){return`
3441
+ `}var Co=null;function Nf(e){if(!Co)Co=new Vi(e);return Co}async function R0(e){await Nf(e).hydrate()}function M0(){return`
3442
3442
  <style data-stx-hydration-styles>
3443
3443
  /* Pre-hydration state */
3444
3444
  [data-stx-component]:not(.stx-hydrated) {
@@ -3471,9 +3471,9 @@ else {
3471
3471
  }
3472
3472
  }
3473
3473
  </style>
3474
- `}import Vi from"path";class Nf{store=new Map;async get(e){let t=this.store.get(e);if(!t||t.expires<=Date.now()){if(t)this.store.delete(e);return null}return{...t.data}}async set(e,t,r){this.store.set(e,{data:{...t},expires:Date.now()+r*1000})}async delete(e){this.store.delete(e)}}async function F0(e,t={},r={}){let n=r.viewsDir||"./views",o=r.layoutsDir||"./layouts",s=!e.includes("<")&&!e.includes("@"),i,a;if(s){if(a=Vi.resolve(n,e),!a.endsWith(".stx"))a+=".stx";if(!await Bun.file(a).exists())return new Response(`Template not found: ${e}`,{status:500});i=await Bun.file(a).text()}else i=e,a="inline-template.stx";let c={...t,props:t,__filename:a,__dirname:Vi.dirname(a)};if(r.ctx)c.csrf_token=r.ctx.csrfToken,c.csrf_field=`<input type="hidden" name="_token" value="${r.ctx.csrfToken}">`,c.old=r.ctx.old,c.errors=r.ctx.errors,c.session=r.ctx.session,c.user=r.ctx.user(),c.isAuthenticated=r.ctx.isAuthenticated();let l=i.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(l){let h=l[1];i=i.replace(/<script\s+server\b[^>]*>[\s\S]*?<\/script>/gi,""),await te(h,c,a)}let d={layoutsDir:o,...r.stxOptions},u=await se(i,c,a,d,new Set),p=new Headers({"Content-Type":"text/html; charset=utf-8"});if(r.ctx)r.ctx.responseHeaders.forEach((h,f)=>{p.set(f,h)});return new Response(u,{headers:p})}var rr={stores:new Map,subscriptions:new Map};function Bf(e,t){rr.stores.set(e,t)}function Xi(e){return rr.stores.get(e)}function zf(e){return rr.stores.has(e)}function Uf(){return Array.from(rr.stores.keys())}var Mt=new Map;function qi(e){if(e==="memory")return{getItem:(t)=>Mt.get(t)??null,setItem:(t,r)=>Mt.set(t,r),removeItem:(t)=>Mt.delete(t)};if(typeof window>"u")return{getItem:(t)=>Mt.get(t)??null,setItem:(t,r)=>Mt.set(t,r),removeItem:(t)=>Mt.delete(t)};return e==="local"?window.localStorage:window.sessionStorage}function Hf(e,t){let r={};for(let n of t){let o=n.split("."),s=e,i=r,a=!0;for(let c=0;c<o.length-1;c++){let l=o[c];if(s&&typeof s==="object"&&l in s){if(s=s[l],!(l in i))i[l]={};i=i[l]}else{a=!1;break}}if(a&&s&&typeof s==="object"){let c=o[o.length-1];if(c in s)i[c]=s[c]}}return r}function Ji(e,t={}){let{name:r,persist:n,devtools:o=!1,middleware:s=[],equals:i=(x,y)=>x===y}=t,a=e,c=new Set,l=null;if(n){let x=qi(n.storage||"local"),y=n.key||`stx-store:${r||"unnamed"}`,b=n.deserialize||JSON.parse;try{let w=x.getItem(y);if(w){let v=b(w);if(n.paths&&typeof v==="object"&&v!==null)a={...e,...v};else a=v}}catch{}}let d=(x)=>{if(!n)return;let y=qi(n.storage||"local"),b=n.key||`stx-store:${r||"unnamed"}`,w=n.serialize||JSON.stringify,v=n.paths&&typeof x==="object"&&x!==null?Hf(x,n.paths):x;if(n.debounce){if(l)clearTimeout(l);l=setTimeout(()=>{y.setItem(b,w(v))},n.debounce)}else y.setItem(b,w(v))},u=(x,y)=>{for(let b of c)try{b(x,y)}catch(w){console.error("[stx-store] Subscriber error:",w)}},p=o?(x,y)=>{if(Ys(r||"unnamed",x,a,y),typeof window<"u")window.__STX_DEVTOOLS__?.onStoreChange?.(r||"unnamed",x,y)}:()=>{},h=(x)=>{let y=a;if(!i(x,y))a=x,d(x),u(x,y),p("set",x)},f=h,g={get:()=>a,set:(x)=>{if(typeof x==="function")f(x(a));else f(x)},subscribe:(x)=>{return c.add(x),()=>{c.delete(x)}},update:(x)=>{if(typeof a!=="object"||a===null)throw Error("update() can only be used with object stores");let y=typeof x==="function"?x(a):x;g.set({...a,...y})},reset:()=>{g.set(e),p("reset",e)},name:r,destroy:()=>{if(c.clear(),l)clearTimeout(l);if(r)rr.stores.delete(r)}};for(let x of s.reverse())f=x(h,()=>a,g)(f);if(r){if(Bf(r,g),o)Js(r,a??{},{},[])}return g}function Wf(e){let t=typeof e==="string"?Xi(e):e;if(!t)throw Error(`Store "${e}" not found`);return t.get()}function Vf(e,t,r){if(typeof t==="function"){if(typeof window<"u"&&window.stx?.defineStore)return window.stx.defineStore(e,t,r);return t()}let n=t,{state:o,getters:s={},actions:i={},persist:a,devtools:c=!0}=n,l=typeof o==="function"?o():o,d=a===!0?{storage:"local",key:`stx-store:${e}`}:a||void 0,u=Ji(l,{name:e,persist:d,devtools:c}),p=new Proxy({},{get(h,f){let g=String(f);if(g==="$state")return u.get();if(g==="$subscribe")return u.subscribe;if(g==="$reset")return u.reset;if(g==="$patch")return(y)=>{if(typeof y==="function"){let b={...u.get()};y(b),u.set(b)}else u.update(y)};if(g==="_store")return u;if(g==="$id")return e;if(g in s)return s[g](u.get());if(g in i)return(...y)=>{return i[g].apply(p,y)};let x=u.get();if(x&&typeof x==="object"&&g in x)return x[g];return},set(h,f,g){let x=String(f);if(x.startsWith("$")||x==="_store")return!1;let y=u.get();if(y&&typeof y==="object")return u.set({...y,[x]:g}),!0;return!1},has(h,f){let g=String(f),x=u.get();return g.startsWith("$")||g==="_store"||g in s||g in i||x&&typeof x==="object"&&g in x},ownKeys(){let h=u.get();return[...h&&typeof h==="object"?Object.keys(h):[],...Object.keys(s),...Object.keys(i),"$state","$subscribe","$reset","$patch","$id"]},getOwnPropertyDescriptor(h,f){return{enumerable:!0,configurable:!0,get:()=>this.get(h,f,p)}}});return qf.set(e,p),p}var qf=new Map;function Xf(e){if(typeof window>"u")return;let t=window;t.__STX_STORES__=t.__STX_STORES__||{};for(let[r,n]of Object.entries(e))t.__STX_STORES__[r]=n;window.dispatchEvent(new CustomEvent("stx:stores-ready",{detail:Object.keys(e)}))}function W(e,t={}){let r=[];for(let[o,s]of Object.entries(t)){if(s===void 0||s===null)continue;if(Array.isArray(s))r.push(`${o}=${encodeURIComponent(s.join(","))}`);else if(typeof s==="boolean"){if(s)r.push(`${o}=true`)}else r.push(`${o}=${encodeURIComponent(String(s))}`)}if(r.length===0)return e;let n=e.includes("?")?"&":"?";return`${e}${n}${r.join("&")}`}function Yi(e){let t=e.indexOf("?");if(t===-1)return{src:e,params:{}};let r=e.slice(0,t),n=e.slice(t+1),o={};for(let s of n.split("&")){let[i,a]=s.split("="),c=a?decodeURIComponent(a):"";if(c==="true")o[i]=!0;else if(c==="false")o[i]=!1;else if(/^-?\d+$/.test(c))o[i]=Number.parseInt(c,10);else if(/^-?\d+\.\d+$/.test(c))o[i]=Number.parseFloat(c);else if(c.includes(","))o[i]=c.split(",");else o[i]=c}return{src:r,params:o}}function Co(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Ki(e,t,r,n){let o={w:t};if(r)o.h=r;if(n)o.fit=n;return W(e,o)}function Gi(e,t,r,n="center"){return W(e,{w:t,h:r,fit:"crop",crop:n})}function Zi(e,t,r="center"){return W(e,{w:t,h:t,fit:"crop",crop:r})}function Qi(e,t,r){return W(e,{w:t,h:r,fit:"max"})}function ea(e,t,r){return W(e,{w:t,h:r,fit:"crop"})}function ta(e,t){return W(e,{blur:Math.min(2000,Math.max(0,t))})}function ra(e,t){return W(e,{sharp:Math.min(100,Math.max(0,t))})}function na(e){return W(e,{sat:-100})}function oa(e,t=100){return W(e,{sepia:Math.min(100,Math.max(0,t))})}function sa(e){return W(e,{invert:!0})}function ia(e,t){return W(e,{bri:Math.min(100,Math.max(-100,t))})}function aa(e,t){return W(e,{con:Math.min(100,Math.max(-100,t))})}function ca(e,t){return W(e,{sat:Math.min(100,Math.max(-100,t))})}function la(e,t){return W(e,{rot:(t%360+360)%360})}function da(e){return W(e,{flip:"h"})}function ua(e){return W(e,{flip:"v"})}function pa(e,t,r){let n={fm:t};if(r!==void 0)n.q=r;return W(e,n)}function fa(e,t){return W(e,{q:Math.min(100,Math.max(1,t))})}function ma(e,t=["format","compress"]){return W(e,{auto:t})}function ha(e,t,r={}){return W(e,{mark:t,markx:r.x,marky:r.y,markalpha:r.alpha,markscale:r.scale,markalign:r.align})}var Eo={web:{fm:"webp",q:80,auto:["format","compress"]},highQuality:{q:95},thumb:{w:150,h:150,fit:"crop",crop:"center"},avatar:{w:200,h:200,fit:"crop",crop:"faces"},social:{w:1200,h:630,fit:"crop"},preview:{w:400,q:70},placeholder:{w:20,blur:200,q:20}};function ga(e,t,r){return W(e,Co(Eo[t],r))}function ya(e,t,r){return t.map((n)=>W(e,{...r,w:n}))}function xa(e,t,r=[1,2,3],n){return r.map((o)=>W(e,{...n,w:Math.round(t*o),dpr:o}))}function ba(e){let t=[];if(e.w!==void 0&&(e.w<1||e.w>16383))t.push("Width must be between 1 and 16383");if(e.h!==void 0&&(e.h<1||e.h>16383))t.push("Height must be between 1 and 16383");if(e.q!==void 0&&(e.q<1||e.q>100))t.push("Quality must be between 1 and 100");if(e.blur!==void 0&&(e.blur<0||e.blur>2000))t.push("Blur must be between 0 and 2000");if(e.rot!==void 0&&(e.rot<0||e.rot>359))t.push("Rotation must be between 0 and 359");if(e.dpr!==void 0&&(e.dpr<1||e.dpr>5))t.push("DPR must be between 1 and 5");return{valid:t.length===0,errors:t}}function wa(e){let t={...e};if(t.w!==void 0)t.w=Math.min(16383,Math.max(1,t.w));if(t.h!==void 0)t.h=Math.min(16383,Math.max(1,t.h));if(t.q!==void 0)t.q=Math.min(100,Math.max(1,t.q));if(t.blur!==void 0)t.blur=Math.min(2000,Math.max(0,t.blur));if(t.rot!==void 0)t.rot=(t.rot%360+360)%360;if(t.dpr!==void 0)t.dpr=Math.min(5,Math.max(1,t.dpr));return t}function sc(e){let{endpoint:t,accept:r,maxSize:n,maxFiles:o=1,fieldName:s="file",preview:i=!1,dropzone:a=!0,multiple:c=!1,autoUpload:l=!0,showProgress:d=!0,disabled:u=!1,placeholder:p="Drop files here or click to select",label:h}=e,f=e.class||"",g=e.style||"",x=e.id||`stx-upload-${Math.random().toString(36).slice(2,8)}`,y=Array.isArray(r)?r.join(","):r,b=`
3474
+ `}import qi from"path";class Bf{store=new Map;async get(e){let t=this.store.get(e);if(!t||t.expires<=Date.now()){if(t)this.store.delete(e);return null}return{...t.data}}async set(e,t,r){this.store.set(e,{data:{...t},expires:Date.now()+r*1000})}async delete(e){this.store.delete(e)}}async function N0(e,t={},r={}){let n=r.viewsDir||"./views",o=r.layoutsDir||"./layouts",s=!e.includes("<")&&!e.includes("@"),i,a;if(s){if(a=qi.resolve(n,e),!a.endsWith(".stx"))a+=".stx";if(!await Bun.file(a).exists())return new Response(`Template not found: ${e}`,{status:500});i=await Bun.file(a).text()}else i=e,a="inline-template.stx";let c={...t,props:t,__filename:a,__dirname:qi.dirname(a)};if(r.ctx)c.csrf_token=r.ctx.csrfToken,c.csrf_field=`<input type="hidden" name="_token" value="${r.ctx.csrfToken}">`,c.old=r.ctx.old,c.errors=r.ctx.errors,c.session=r.ctx.session,c.user=r.ctx.user(),c.isAuthenticated=r.ctx.isAuthenticated();let l=i.match(/<script\s+server\b[^>]*>([\s\S]*?)<\/script>/i);if(l){let h=l[1];i=i.replace(/<script\s+server\b[^>]*>[\s\S]*?<\/script>/gi,""),await re(h,c,a)}let d={layoutsDir:o,...r.stxOptions},u=await ie(i,c,a,d,new Set),p=new Headers({"Content-Type":"text/html; charset=utf-8"});if(r.ctx)r.ctx.responseHeaders.forEach((h,f)=>{p.set(f,h)});return new Response(u,{headers:p})}var nr={stores:new Map,subscriptions:new Map};function zf(e,t){nr.stores.set(e,t)}function Ji(e){return nr.stores.get(e)}function Uf(e){return nr.stores.has(e)}function Hf(){return Array.from(nr.stores.keys())}var Dt=new Map;function Xi(e){if(e==="memory")return{getItem:(t)=>Dt.get(t)??null,setItem:(t,r)=>Dt.set(t,r),removeItem:(t)=>Dt.delete(t)};if(typeof window>"u")return{getItem:(t)=>Dt.get(t)??null,setItem:(t,r)=>Dt.set(t,r),removeItem:(t)=>Dt.delete(t)};return e==="local"?window.localStorage:window.sessionStorage}function Wf(e,t){let r={};for(let n of t){let o=n.split("."),s=e,i=r,a=!0;for(let c=0;c<o.length-1;c++){let l=o[c];if(s&&typeof s==="object"&&l in s){if(s=s[l],!(l in i))i[l]={};i=i[l]}else{a=!1;break}}if(a&&s&&typeof s==="object"){let c=o[o.length-1];if(c in s)i[c]=s[c]}}return r}function Yi(e,t={}){let{name:r,persist:n,devtools:o=!1,middleware:s=[],equals:i=(x,y)=>x===y}=t,a=e,c=new Set,l=null;if(n){let x=Xi(n.storage||"local"),y=n.key||`stx-store:${r||"unnamed"}`,b=n.deserialize||JSON.parse;try{let w=x.getItem(y);if(w){let v=b(w);if(n.paths&&typeof v==="object"&&v!==null)a={...e,...v};else a=v}}catch{}}let d=(x)=>{if(!n)return;let y=Xi(n.storage||"local"),b=n.key||`stx-store:${r||"unnamed"}`,w=n.serialize||JSON.stringify,v=n.paths&&typeof x==="object"&&x!==null?Wf(x,n.paths):x;if(n.debounce){if(l)clearTimeout(l);l=setTimeout(()=>{y.setItem(b,w(v))},n.debounce)}else y.setItem(b,w(v))},u=(x,y)=>{for(let b of c)try{b(x,y)}catch(w){console.error("[stx-store] Subscriber error:",w)}},p=o?(x,y)=>{if(Ks(r||"unnamed",x,a,y),typeof window<"u")window.__STX_DEVTOOLS__?.onStoreChange?.(r||"unnamed",x,y)}:()=>{},h=(x)=>{let y=a;if(!i(x,y))a=x,d(x),u(x,y),p("set",x)},f=h,g={get:()=>a,set:(x)=>{if(typeof x==="function")f(x(a));else f(x)},subscribe:(x)=>(c.add(x),()=>{c.delete(x)}),update:(x)=>{if(typeof a!=="object"||a===null)throw Error("update() can only be used with object stores");let y=typeof x==="function"?x(a):x;g.set({...a,...y})},reset:()=>{g.set(e),p("reset",e)},name:r,destroy:()=>{if(c.clear(),l)clearTimeout(l);if(r)nr.stores.delete(r)}};for(let x of s.reverse())f=x(h,()=>a,g)(f);if(r){if(zf(r,g),o)Ys(r,a??{},{},[])}return g}function Vf(e){let t=typeof e==="string"?Ji(e):e;if(!t)throw Error(`Store "${e}" not found`);return t.get()}function qf(e,t,r){if(typeof t==="function"){if(typeof window<"u"&&window.stx?.defineStore)return window.stx.defineStore(e,t,r);return t()}let n=t,{state:o,getters:s={},actions:i={},persist:a,devtools:c=!0}=n,l=typeof o==="function"?o():o,d=a===!0?{storage:"local",key:`stx-store:${e}`}:a||void 0,u=Yi(l,{name:e,persist:d,devtools:c}),p=new Proxy({},{get(h,f){let g=String(f);if(g==="$state")return u.get();if(g==="$subscribe")return u.subscribe;if(g==="$reset")return u.reset;if(g==="$patch")return(y)=>{if(typeof y==="function"){let b={...u.get()};y(b),u.set(b)}else u.update(y)};if(g==="_store")return u;if(g==="$id")return e;if(g in s)return s[g](u.get());if(g in i)return(...y)=>i[g].apply(p,y);let x=u.get();if(x&&typeof x==="object"&&g in x)return x[g];return},set(h,f,g){let x=String(f);if(x.startsWith("$")||x==="_store")return!1;let y=u.get();if(y&&typeof y==="object")return u.set({...y,[x]:g}),!0;return!1},has(h,f){let g=String(f),x=u.get();return g.startsWith("$")||g==="_store"||g in s||g in i||x&&typeof x==="object"&&g in x},ownKeys(){let h=u.get();return[...h&&typeof h==="object"?Object.keys(h):[],...Object.keys(s),...Object.keys(i),"$state","$subscribe","$reset","$patch","$id"]},getOwnPropertyDescriptor(h,f){return{enumerable:!0,configurable:!0,get:()=>this.get(h,f,p)}}});return Xf.set(e,p),p}var Xf=new Map;function Jf(e){if(typeof window>"u")return;let t=window;t.__STX_STORES__=t.__STX_STORES__||{};for(let[r,n]of Object.entries(e))t.__STX_STORES__[r]=n;window.dispatchEvent(new CustomEvent("stx:stores-ready",{detail:Object.keys(e)}))}function V(e,t={}){let r=[];for(let[o,s]of Object.entries(t)){if(s===void 0||s===null)continue;if(Array.isArray(s))r.push(`${o}=${encodeURIComponent(s.join(","))}`);else if(typeof s==="boolean"){if(s)r.push(`${o}=true`)}else r.push(`${o}=${encodeURIComponent(String(s))}`)}if(r.length===0)return e;let n=e.includes("?")?"&":"?";return`${e}${n}${r.join("&")}`}function Ki(e){let t=e.indexOf("?");if(t===-1)return{src:e,params:{}};let r=e.slice(0,t),n=e.slice(t+1),o={};for(let s of n.split("&")){let[i,a]=s.split("="),c=a?decodeURIComponent(a):"";if(c==="true")o[i]=!0;else if(c==="false")o[i]=!1;else if(/^-?\d+$/.test(c))o[i]=Number.parseInt(c,10);else if(/^-?\d+\.\d+$/.test(c))o[i]=Number.parseFloat(c);else if(c.includes(","))o[i]=c.split(",");else o[i]=c}return{src:r,params:o}}function Eo(...e){let t={};for(let r of e)if(r)Object.assign(t,r);return t}function Gi(e,t,r,n){let o={w:t};if(r)o.h=r;if(n)o.fit=n;return V(e,o)}function Zi(e,t,r,n="center"){return V(e,{w:t,h:r,fit:"crop",crop:n})}function Qi(e,t,r="center"){return V(e,{w:t,h:t,fit:"crop",crop:r})}function ea(e,t,r){return V(e,{w:t,h:r,fit:"max"})}function ta(e,t,r){return V(e,{w:t,h:r,fit:"crop"})}function ra(e,t){return V(e,{blur:Math.min(2000,Math.max(0,t))})}function na(e,t){return V(e,{sharp:Math.min(100,Math.max(0,t))})}function oa(e){return V(e,{sat:-100})}function sa(e,t=100){return V(e,{sepia:Math.min(100,Math.max(0,t))})}function ia(e){return V(e,{invert:!0})}function aa(e,t){return V(e,{bri:Math.min(100,Math.max(-100,t))})}function ca(e,t){return V(e,{con:Math.min(100,Math.max(-100,t))})}function la(e,t){return V(e,{sat:Math.min(100,Math.max(-100,t))})}function da(e,t){return V(e,{rot:(t%360+360)%360})}function ua(e){return V(e,{flip:"h"})}function pa(e){return V(e,{flip:"v"})}function fa(e,t,r){let n={fm:t};if(r!==void 0)n.q=r;return V(e,n)}function ma(e,t){return V(e,{q:Math.min(100,Math.max(1,t))})}function ha(e,t=["format","compress"]){return V(e,{auto:t})}function ga(e,t,r={}){return V(e,{mark:t,markx:r.x,marky:r.y,markalpha:r.alpha,markscale:r.scale,markalign:r.align})}var _o={web:{fm:"webp",q:80,auto:["format","compress"]},highQuality:{q:95},thumb:{w:150,h:150,fit:"crop",crop:"center"},avatar:{w:200,h:200,fit:"crop",crop:"faces"},social:{w:1200,h:630,fit:"crop"},preview:{w:400,q:70},placeholder:{w:20,blur:200,q:20}};function ya(e,t,r){return V(e,Eo(_o[t],r))}function xa(e,t,r){return t.map((n)=>V(e,{...r,w:n}))}function ba(e,t,r=[1,2,3],n){return r.map((o)=>V(e,{...n,w:Math.round(t*o),dpr:o}))}function wa(e){let t=[];if(e.w!==void 0&&(e.w<1||e.w>16383))t.push("Width must be between 1 and 16383");if(e.h!==void 0&&(e.h<1||e.h>16383))t.push("Height must be between 1 and 16383");if(e.q!==void 0&&(e.q<1||e.q>100))t.push("Quality must be between 1 and 100");if(e.blur!==void 0&&(e.blur<0||e.blur>2000))t.push("Blur must be between 0 and 2000");if(e.rot!==void 0&&(e.rot<0||e.rot>359))t.push("Rotation must be between 0 and 359");if(e.dpr!==void 0&&(e.dpr<1||e.dpr>5))t.push("DPR must be between 1 and 5");return{valid:t.length===0,errors:t}}function va(e){let t={...e};if(t.w!==void 0)t.w=Math.min(16383,Math.max(1,t.w));if(t.h!==void 0)t.h=Math.min(16383,Math.max(1,t.h));if(t.q!==void 0)t.q=Math.min(100,Math.max(1,t.q));if(t.blur!==void 0)t.blur=Math.min(2000,Math.max(0,t.blur));if(t.rot!==void 0)t.rot=(t.rot%360+360)%360;if(t.dpr!==void 0)t.dpr=Math.min(5,Math.max(1,t.dpr));return t}function ic(e){let{endpoint:t,accept:r,maxSize:n,maxFiles:o=1,fieldName:s="file",preview:i=!1,dropzone:a=!0,multiple:c=!1,autoUpload:l=!0,showProgress:d=!0,disabled:u=!1,placeholder:p="Drop files here or click to select",label:h}=e,f=e.class||"",g=e.style||"",x=e.id||`stx-upload-${Math.random().toString(36).slice(2,8)}`,y=Array.isArray(r)?r.join(","):r,b=`
3475
3475
  <div id="${x}" class="stx-upload${a?" stx-upload-dropzone":""}${u?" stx-upload-disabled":""}${f?" "+f:""}"${g?` style="${g}"`:""}>
3476
- ${h?`<label class="stx-upload-label">${oc(h)}</label>`:""}
3476
+ ${h?`<label class="stx-upload-label">${sc(h)}</label>`:""}
3477
3477
  <div class="stx-upload-area" data-stx-upload-area>
3478
3478
  <input
3479
3479
  type="file"
@@ -3488,8 +3488,8 @@ else {
3488
3488
  <svg class="stx-upload-icon" viewBox="0 0 24 24" width="48" height="48">
3489
3489
  <path fill="currentColor" d="M9 16h6v-6h4l-7-7-7 7h4v6zm-4 2h14v2H5v-2z"/>
3490
3490
  </svg>
3491
- <span class="stx-upload-text">${oc(p)}</span>
3492
- ${n?`<span class="stx-upload-hint">Max size: ${Zf(n)}</span>`:""}
3491
+ <span class="stx-upload-text">${sc(p)}</span>
3492
+ ${n?`<span class="stx-upload-hint">Max size: ${Qf(n)}</span>`:""}
3493
3493
  </div>
3494
3494
  </div>
3495
3495
  ${i?'<div class="stx-upload-previews" data-stx-upload-previews></div>':""}
@@ -3508,7 +3508,7 @@ else {
3508
3508
  var progressText = progress ? progress.querySelector('.stx-upload-progress-text') : null;
3509
3509
 
3510
3510
  var config = {
3511
- endpoint: '${Gf(t)}',
3511
+ endpoint: '${Zf(t)}',
3512
3512
  fieldName: '${s}',
3513
3513
  maxSize: ${n||"null"},
3514
3514
  maxFiles: ${o},
@@ -3760,7 +3760,7 @@ else {
3760
3760
  opacity: 0.5;
3761
3761
  pointer-events: none;
3762
3762
  }
3763
- `.trim();return{html:b,script:w,css:v}}function oc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Gf(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Zf(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}async function Jr(e,t){let{endpoint:r,method:n="POST",headers:o={},expirationSeconds:s=3600,oneTimeUse:i=!1,params:a={}}=t,c=JSON.stringify({url:e,expirationSeconds:s,oneTimeUse:i,...a}),l=await fetch(r,{method:n,headers:{"Content-Type":"application/json",...o},body:n!=="GET"?c:void 0});if(!l.ok)throw Error(`Failed to sign URL: ${l.status} ${l.statusText}`);let d=await l.json();return{url:d.url||d.signedUrl,signature:d.signature,expires:d.expires||Date.now()+s*1000,oneTimeUse:d.oneTimeUse||i}}async function Yr(e,t){let{endpoint:r,method:n="POST",headers:o={},expirationSeconds:s=3600,oneTimeUse:i=!1,params:a={}}=t,c=JSON.stringify({urls:e,expirationSeconds:s,oneTimeUse:i,...a}),l=await fetch(r,{method:n,headers:{"Content-Type":"application/json",...o},body:n!=="GET"?c:void 0});if(!l.ok)throw Error(`Failed to batch sign URLs: ${l.status} ${l.statusText}`);let d=await l.json(),u=new Map,p=new Map;if(Array.isArray(d.results))for(let h of d.results)if(h.error)p.set(h.url,h.error);else u.set(h.url||h.originalUrl,{url:h.signedUrl||h.url,signature:h.signature,expires:h.expires||Date.now()+s*1000,oneTimeUse:h.oneTimeUse||i});else if(typeof d.signatures==="object"){for(let[h,f]of Object.entries(d.signatures)){let g=f;u.set(h,{url:g.signedUrl||g.url||h,signature:g.signature,expires:g.expires||Date.now()+s*1000,oneTimeUse:i})}if(d.errors)for(let[h,f]of Object.entries(d.errors))p.set(h,f)}return{signatures:u,errors:p}}async function ic(e,t,r=10){let n=new Map,o=new Map,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let i=await Promise.all(s.map((a)=>Yr(a,t)));for(let a of i){for(let[c,l]of a.signatures)n.set(c,l);for(let[c,l]of a.errors)o.set(c,l)}return{signatures:n,errors:o}}function _o(e){return e.expires>Date.now()}function Ao(e){return Math.max(0,e.expires-Date.now())}function jo(e,t=300000){return Ao(e)<t}async function or(e){if(e.check)return await e.check();return!0}function Kr(e){let t={};if(e.role)t.role=e.role;if(e.permission)t.permission=e.permission;if(e.userId)t.userId=e.userId;return t}var nr=new Map;async function ac(e,t){let r=`${e}:${t.endpoint}`,n=nr.get(r);if(n&&_o(n)&&!jo(n))return n;let o=await Jr(e,t);return nr.set(r,o),o}function cc(){nr.clear()}function lc(){let e=0,t=Date.now();for(let[r,n]of nr)if(n.expires<=t)nr.delete(r),e++;return e}function Gr(){return`
3763
+ `.trim();return{html:b,script:w,css:v}}function sc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Zf(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Qf(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(1)} MB`}async function Yr(e,t){let{endpoint:r,method:n="POST",headers:o={},expirationSeconds:s=3600,oneTimeUse:i=!1,params:a={}}=t,c=JSON.stringify({url:e,expirationSeconds:s,oneTimeUse:i,...a}),l=await fetch(r,{method:n,headers:{"Content-Type":"application/json",...o},body:n!=="GET"?c:void 0});if(!l.ok)throw Error(`Failed to sign URL: ${l.status} ${l.statusText}`);let d=await l.json();return{url:d.url||d.signedUrl,signature:d.signature,expires:d.expires||Date.now()+s*1000,oneTimeUse:d.oneTimeUse||i}}async function Kr(e,t){let{endpoint:r,method:n="POST",headers:o={},expirationSeconds:s=3600,oneTimeUse:i=!1,params:a={}}=t,c=JSON.stringify({urls:e,expirationSeconds:s,oneTimeUse:i,...a}),l=await fetch(r,{method:n,headers:{"Content-Type":"application/json",...o},body:n!=="GET"?c:void 0});if(!l.ok)throw Error(`Failed to batch sign URLs: ${l.status} ${l.statusText}`);let d=await l.json(),u=new Map,p=new Map;if(Array.isArray(d.results))for(let h of d.results)if(h.error)p.set(h.url,h.error);else u.set(h.url||h.originalUrl,{url:h.signedUrl||h.url,signature:h.signature,expires:h.expires||Date.now()+s*1000,oneTimeUse:h.oneTimeUse||i});else if(typeof d.signatures==="object"){for(let[h,f]of Object.entries(d.signatures)){let g=f;u.set(h,{url:g.signedUrl||g.url||h,signature:g.signature,expires:g.expires||Date.now()+s*1000,oneTimeUse:i})}if(d.errors)for(let[h,f]of Object.entries(d.errors))p.set(h,f)}return{signatures:u,errors:p}}async function ac(e,t,r=10){let n=new Map,o=new Map,s=[];for(let a=0;a<e.length;a+=r)s.push(e.slice(a,a+r));let i=await Promise.all(s.map((a)=>Kr(a,t)));for(let a of i){for(let[c,l]of a.signatures)n.set(c,l);for(let[c,l]of a.errors)o.set(c,l)}return{signatures:n,errors:o}}function Ao(e){return e.expires>Date.now()}function jo(e){return Math.max(0,e.expires-Date.now())}function Ro(e,t=300000){return jo(e)<t}async function sr(e){if(e.check)return await e.check();return!0}function Gr(e){let t={};if(e.role)t.role=e.role;if(e.permission)t.permission=e.permission;if(e.userId)t.userId=e.userId;return t}var or=new Map;async function cc(e,t){let r=`${e}:${t.endpoint}`,n=or.get(r);if(n&&Ao(n)&&!Ro(n))return n;let o=await Yr(e,t);return or.set(r,o),o}function lc(){or.clear()}function dc(){let e=0,t=Date.now();for(let[r,n]of or)if(n.expires<=t)or.delete(r),e++;return e}function Zr(){return`
3764
3764
  (function() {
3765
3765
  'use strict';
3766
3766
 
@@ -3834,34 +3834,34 @@ catch (error) {
3834
3834
  }
3835
3835
  };
3836
3836
  })();
3837
- `.trim()}async function uc(e){let{src:t,alt:r="",signatureEndpoint:n="/api/sign",signatureConfig:o={},auth:s,fallback:i,oneTimeUse:a=!0}=e,c=e.class,l=e.style;if(s){if(!await or(s)){if(i)return{html:`<img src="${Y(i)}" alt="${Y(r)}"${c?` class="${Y(c)}"`:""}${l?` style="${Y(l)}"`:""} />`};return{html:"<!-- Protected content: access denied -->"}}}let d={endpoint:n,oneTimeUse:a,...o,params:s?Kr(s):o.params},u=`stx-protected-${Math.random().toString(36).slice(2,8)}`,p=[`id="${u}"`,`data-protected-src="${Y(t)}"`,`data-signature-endpoint="${Y(n)}"`,`alt="${Y(r)}"`];if(i)p.push(`data-fallback="${Y(i)}"`),p.push(`src="${Y(i)}"`);else p.push('src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"');if(c)p.push(`class="${Y(c)}"`);if(l)p.push(`style="${Y(l)}"`);let h=`
3837
+ `.trim()}async function pc(e){let{src:t,alt:r="",signatureEndpoint:n="/api/sign",signatureConfig:o={},auth:s,fallback:i,oneTimeUse:a=!0}=e,c=e.class,l=e.style;if(s){if(!await sr(s)){if(i)return{html:`<img src="${K(i)}" alt="${K(r)}"${c?` class="${K(c)}"`:""}${l?` style="${K(l)}"`:""} />`};return{html:"<!-- Protected content: access denied -->"}}}let d={endpoint:n,oneTimeUse:a,...o,params:s?Gr(s):o.params},u=`stx-protected-${Math.random().toString(36).slice(2,8)}`,p=[`id="${u}"`,`data-protected-src="${K(t)}"`,`data-signature-endpoint="${K(n)}"`,`alt="${K(r)}"`];if(i)p.push(`data-fallback="${K(i)}"`),p.push(`src="${K(i)}"`);else p.push('src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"');if(c)p.push(`class="${K(c)}"`);if(l)p.push(`style="${K(l)}"`);let h=`
3838
3838
  (function() {
3839
3839
  var el = document.getElementById('${u}');
3840
3840
  if (!el) return;
3841
3841
 
3842
3842
  STX.loadProtectedMedia(el, {
3843
- endpoint: '${Y(n)}',
3843
+ endpoint: '${K(n)}',
3844
3844
  oneTimeUse: ${a},
3845
3845
  expirationSeconds: ${o.expirationSeconds||3600}
3846
3846
  });
3847
3847
  })();
3848
- `.trim();return{html:`<img ${p.join(" ")} />`,script:h}}async function pc(e){let{src:t,signatureEndpoint:r="/api/sign",signatureConfig:n={},auth:o,fallback:s,oneTimeUse:i=!0,poster:a,controls:c=!0,autoplay:l=!1,muted:d=!1,loop:u=!1}=e,p=e.class,h=e.style,f=e.alt;if(o){if(!await or(o))return{html:"<!-- Protected video: access denied -->"}}let g=`stx-protected-video-${Math.random().toString(36).slice(2,8)}`,x=[`id="${g}"`,`data-protected-src="${Y(t)}"`,`data-signature-endpoint="${Y(r)}"`];if(a)x.push(`poster="${Y(a)}"`);if(c)x.push("controls");if(l)x.push("autoplay");if(d)x.push("muted");if(u)x.push("loop");if(p)x.push(`class="${Y(p)}"`);if(h)x.push(`style="${Y(h)}"`);if(s)x.push(`data-fallback="${Y(s)}"`);let y=`
3848
+ `.trim();return{html:`<img ${p.join(" ")} />`,script:h}}async function fc(e){let{src:t,signatureEndpoint:r="/api/sign",signatureConfig:n={},auth:o,fallback:s,oneTimeUse:i=!0,poster:a,controls:c=!0,autoplay:l=!1,muted:d=!1,loop:u=!1}=e,p=e.class,h=e.style,f=e.alt;if(o){if(!await sr(o))return{html:"<!-- Protected video: access denied -->"}}let g=`stx-protected-video-${Math.random().toString(36).slice(2,8)}`,x=[`id="${g}"`,`data-protected-src="${K(t)}"`,`data-signature-endpoint="${K(r)}"`];if(a)x.push(`poster="${K(a)}"`);if(c)x.push("controls");if(l)x.push("autoplay");if(d)x.push("muted");if(u)x.push("loop");if(p)x.push(`class="${K(p)}"`);if(h)x.push(`style="${K(h)}"`);if(s)x.push(`data-fallback="${K(s)}"`);let y=`
3849
3849
  (function() {
3850
3850
  var el = document.getElementById('${g}');
3851
3851
  if (!el) return;
3852
3852
 
3853
3853
  STX.loadProtectedMedia(el, {
3854
- endpoint: '${Y(r)}',
3854
+ endpoint: '${K(r)}',
3855
3855
  oneTimeUse: ${i},
3856
3856
  expirationSeconds: ${n.expirationSeconds||3600}
3857
3857
  });
3858
3858
  })();
3859
- `.trim();return{html:`<video ${x.join(" ")}></video>`,script:y}}async function fc(e,t){let r=/data-protected-src="([^"]+)"/g,n=[],o;while((o=r.exec(e))!==null)n.push(o[1]);if(n.length===0)return{html:e,script:""};let s=Gr()+`
3859
+ `.trim();return{html:`<video ${x.join(" ")}></video>`,script:y}}async function mc(e,t){let r=/data-protected-src="([^"]+)"/g,n=[],o;while((o=r.exec(e))!==null)n.push(o[1]);if(n.length===0)return{html:e,script:""};let s=Zr()+`
3860
3860
 
3861
3861
  `;return s+=`
3862
3862
  (function() {
3863
3863
  var sources = ${JSON.stringify(n)};
3864
- var endpoint = '${Y(t)}';
3864
+ var endpoint = '${K(t)}';
3865
3865
 
3866
3866
  // Batch sign all URLs
3867
3867
  STX.batchSignUrls(sources, { endpoint: endpoint })
@@ -3888,12 +3888,12 @@ else if (el.dataset.fallback) {
3888
3888
  });
3889
3889
  });
3890
3890
  })();
3891
- `.trim(),{html:e,script:s}}function mc(e,t,r){if(t.src)return{src:String(t.src),alt:String(t.alt||""),signatureEndpoint:String(t.signatureEndpoint||"/api/sign"),auth:t.auth,fallback:t.fallback?String(t.fallback):void 0,oneTimeUse:t.oneTimeUse!==!1};let n=e.trim();if(n.startsWith("@protected(")||n.startsWith("("))n=n.replace(/^@protected\(/,"").replace(/^\(/,"").replace(/\)$/,"");let o=Qf(n);return{src:dc(o[0],r)||"",alt:dc(o[1],r)||"",...typeof o[2]==="object"?o[2]:{}}}function Qf(e){let t=[],r="",n=!1,o="",s=0;for(let i=0;i<e.length;i++){let a=e[i],c=i>0?e[i-1]:"";if((a==='"'||a==="'")&&c!=="\\"){if(!n)n=!0,o=a;else if(a===o)n=!1;else r+=a;continue}if(!n){if(a==="{")s++;if(a==="}")s--;if(a===","&&s===0){t.push(r.trim()),r="";continue}}r+=a}if(r.trim())t.push(r.trim());return t}function dc(e,t){if(typeof e!=="string")return e;let r=e.trim();if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);if(t[r]!==void 0)return t[r];if(r.startsWith("{"))try{return JSON.parse(r)}catch{}return r}function Y(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function em(e){let{src:t,apiKey:r,bucket:n,allowedTypes:o,maxFileSize:s,multiple:i=!1,customStyles:a={},callbacks:c={}}=e,l=`stx-media-manager-${Math.random().toString(36).slice(2,8)}`,d={container:`#${l}`};if(r)d.apiKey=r;if(n)d.bucket=n;if(o)d.allowedTypes=o;if(s)d.maxFileSize=s;if(i)d.multiple=i;if(Object.keys(a).length>0)d.styles=a;let u=`<div id="${l}" class="stx-media-manager"></div>`,p=Object.entries(c).filter(([,f])=>f).map(([f,g])=>{return`manager.on('${f.replace(/^on/,"").toLowerCase()}', ${g});`}).join(`
3891
+ `.trim(),{html:e,script:s}}function hc(e,t,r){if(t.src)return{src:String(t.src),alt:String(t.alt||""),signatureEndpoint:String(t.signatureEndpoint||"/api/sign"),auth:t.auth,fallback:t.fallback?String(t.fallback):void 0,oneTimeUse:t.oneTimeUse!==!1};let n=e.trim();if(n.startsWith("@protected(")||n.startsWith("("))n=n.replace(/^@protected\(/,"").replace(/^\(/,"").replace(/\)$/,"");let o=em(n);return{src:uc(o[0],r)||"",alt:uc(o[1],r)||"",...typeof o[2]==="object"?o[2]:{}}}function em(e){let t=[],r="",n=!1,o="",s=0;for(let i=0;i<e.length;i++){let a=e[i],c=i>0?e[i-1]:"";if((a==='"'||a==="'")&&c!=="\\"){if(!n)n=!0,o=a;else if(a===o)n=!1;else r+=a;continue}if(!n){if(a==="{")s++;if(a==="}")s--;if(a===","&&s===0){t.push(r.trim()),r="";continue}}r+=a}if(r.trim())t.push(r.trim());return t}function uc(e,t){if(typeof e!=="string")return e;let r=e.trim();if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);if(t[r]!==void 0)return t[r];if(r.startsWith("{"))try{return JSON.parse(r)}catch{}return r}function K(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function tm(e){let{src:t,apiKey:r,bucket:n,allowedTypes:o,maxFileSize:s,multiple:i=!1,customStyles:a={},callbacks:c={}}=e,l=`stx-media-manager-${Math.random().toString(36).slice(2,8)}`,d={container:`#${l}`};if(r)d.apiKey=r;if(n)d.bucket=n;if(o)d.allowedTypes=o;if(s)d.maxFileSize=s;if(i)d.multiple=i;if(Object.keys(a).length>0)d.styles=a;let u=`<div id="${l}" class="stx-media-manager"></div>`,p=Object.entries(c).filter(([,f])=>f).map(([f,g])=>`manager.on('${f.replace(/^on/,"").toLowerCase()}', ${g});`).join(`
3892
3892
  `),h=`
3893
3893
  (function() {
3894
3894
  // Load media manager script
3895
3895
  var script = document.createElement('script');
3896
- script.src = '${hc(t)}';
3896
+ script.src = '${gc(t)}';
3897
3897
  script.async = true;
3898
3898
 
3899
3899
  script.onload = function() {
@@ -3910,12 +3910,12 @@ else if (el.dataset.fallback) {
3910
3910
  };
3911
3911
 
3912
3912
  script.onerror = function() {
3913
- console.error('[stx] Failed to load media manager from:', '${hc(t)}');
3913
+ console.error('[stx] Failed to load media manager from:', '${gc(t)}');
3914
3914
  };
3915
3915
 
3916
3916
  document.head.appendChild(script);
3917
3917
  })();
3918
- `.trim();return{html:u,script:h}}function tm(e){let{accept:t="image/*",multiple:r=!1,onSelect:n="handleMediaSelect"}=e,o=`stx-picker-${Math.random().toString(36).slice(2,8)}`,s=`
3918
+ `.trim();return{html:u,script:h}}function rm(e){let{accept:t="image/*",multiple:r=!1,onSelect:n="handleMediaSelect"}=e,o=`stx-picker-${Math.random().toString(36).slice(2,8)}`,s=`
3919
3919
  <div id="${o}" class="stx-media-picker" style="display:none;">
3920
3920
  <div class="stx-media-picker-backdrop"></div>
3921
3921
  <div class="stx-media-picker-modal">
@@ -4104,7 +4104,7 @@ else {
4104
4104
  border: none;
4105
4105
  color: white;
4106
4106
  }
4107
- `.trim();return{html:s,script:i,css:a}}function hc(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var xc={root:null,rootMargin:"50px 0px",threshold:0,useNative:!0,selector:"[data-stx-lazy]"};function Ro(){return"loading"in HTMLImageElement.prototype}function Mo(){return"IntersectionObserver"in window}function bc(e={}){let t={...xc,...e},r=document.querySelectorAll(t.selector);if(r.length===0)return()=>{};if(t.useNative&&Ro())return r.forEach((o)=>{if(o.tagName==="IMG"||o.tagName==="IFRAME")Qe(o,t)}),()=>{};if(!Mo())return r.forEach((o)=>Qe(o,t)),()=>{};let n=new IntersectionObserver((o)=>{o.forEach((s)=>{if(s.isIntersecting){let i=s.target;Qe(i,t),n.unobserve(i)}})},{root:t.root,rootMargin:t.rootMargin,threshold:t.threshold});return r.forEach((o)=>n.observe(o)),()=>{n.disconnect()}}function Qe(e,t={}){let{onLoad:r,onLoaded:n,onError:o}=t;if(r)r(e);let s=e.tagName==="IMG",i=e.tagName==="VIDEO",a=e.tagName==="IFRAME";if(s)gc(e,n,o);else if(i)yc(e,n,o);else if(a)rm(e,n,o);else{let c=e.querySelector("img[data-src], img[data-srcset]"),l=e.querySelector("video[data-src]");if(c)gc(c,()=>{if(n)n(e)},(d)=>{if(o)o(e,d)});else if(l)yc(l,()=>{if(n)n(e)},(d)=>{if(o)o(e,d)});e.querySelectorAll("source[data-srcset]").forEach((d)=>{let u=d;if(u.dataset.srcset)u.srcset=u.dataset.srcset,delete u.dataset.srcset;if(u.dataset.sizes)u.sizes=u.dataset.sizes,delete u.dataset.sizes})}}function gc(e,t,r){let n=()=>{e.classList.add("stx-img-loaded"),e.style.opacity="1";let s=e.closest(".stx-img-placeholder");if(s)s.classList.add("stx-img-loaded");if(t)t(e)},o=()=>{if(e.classList.add("stx-img-error"),r)r(e,Error(`Failed to load image: ${e.src}`))};if(e.addEventListener("load",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.dataset.srcset)e.srcset=e.dataset.srcset,delete e.dataset.srcset;if(e.dataset.src)e.src=e.dataset.src,delete e.dataset.src;if(e.dataset.sizes)e.sizes=e.dataset.sizes,delete e.dataset.sizes}function yc(e,t,r){let n=()=>{if(e.classList.add("stx-video-loaded"),t)t(e)},o=()=>{if(e.classList.add("stx-video-error"),r)r(e,Error(`Failed to load video: ${e.src}`))};if(e.addEventListener("loadeddata",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.querySelectorAll("source[data-src]").forEach((s)=>{let i=s;if(i.dataset.src)i.src=i.dataset.src,delete i.dataset.src}),e.dataset.src)e.src=e.dataset.src,delete e.dataset.src;if(e.dataset.poster)e.poster=e.dataset.poster,delete e.dataset.poster;e.load()}function rm(e,t,r){let n=()=>{if(e.classList.add("stx-iframe-loaded"),t)t(e)},o=()=>{if(e.classList.add("stx-iframe-error"),r)r(e,Error(`Failed to load iframe: ${e.src}`))};if(e.addEventListener("load",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.dataset.src)e.src=e.dataset.src,delete e.dataset.src}function wc(e){Qe(e,{})}function vc(e="[data-stx-lazy]"){document.querySelectorAll(e).forEach((t)=>Qe(t,{}))}function $c(e={}){let t={...xc,...e};return new IntersectionObserver((r,n)=>{r.forEach((o)=>{if(o.isIntersecting)Qe(o.target,t),n.unobserve(o.target)})},{root:t.root,rootMargin:t.rootMargin,threshold:t.threshold})}function Sc(e,t){e.observe(t)}function kc(e){e.disconnect()}function Zr(){return`
4107
+ `.trim();return{html:s,script:i,css:a}}function gc(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var bc={root:null,rootMargin:"50px 0px",threshold:0,useNative:!0,selector:"[data-stx-lazy]"};function Mo(){return"loading"in HTMLImageElement.prototype}function Do(){return"IntersectionObserver"in window}function wc(e={}){let t={...bc,...e},r=document.querySelectorAll(t.selector);if(r.length===0)return()=>{};if(t.useNative&&Mo())return r.forEach((o)=>{if(o.tagName==="IMG"||o.tagName==="IFRAME")et(o,t)}),()=>{};if(!Do())return r.forEach((o)=>et(o,t)),()=>{};let n=new IntersectionObserver((o)=>{o.forEach((s)=>{if(s.isIntersecting){let i=s.target;et(i,t),n.unobserve(i)}})},{root:t.root,rootMargin:t.rootMargin,threshold:t.threshold});return r.forEach((o)=>n.observe(o)),()=>{n.disconnect()}}function et(e,t={}){let{onLoad:r,onLoaded:n,onError:o}=t;if(r)r(e);let s=e.tagName==="IMG",i=e.tagName==="VIDEO",a=e.tagName==="IFRAME";if(s)yc(e,n,o);else if(i)xc(e,n,o);else if(a)nm(e,n,o);else{let c=e.querySelector("img[data-src], img[data-srcset]"),l=e.querySelector("video[data-src]");if(c)yc(c,()=>{if(n)n(e)},(d)=>{if(o)o(e,d)});else if(l)xc(l,()=>{if(n)n(e)},(d)=>{if(o)o(e,d)});e.querySelectorAll("source[data-srcset]").forEach((d)=>{let u=d;if(u.dataset.srcset)u.srcset=u.dataset.srcset,delete u.dataset.srcset;if(u.dataset.sizes)u.sizes=u.dataset.sizes,delete u.dataset.sizes})}}function yc(e,t,r){let n=()=>{e.classList.add("stx-img-loaded"),e.style.opacity="1";let s=e.closest(".stx-img-placeholder");if(s)s.classList.add("stx-img-loaded");if(t)t(e)},o=()=>{if(e.classList.add("stx-img-error"),r)r(e,Error(`Failed to load image: ${e.src}`))};if(e.addEventListener("load",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.dataset.srcset)e.srcset=e.dataset.srcset,delete e.dataset.srcset;if(e.dataset.src)e.src=e.dataset.src,delete e.dataset.src;if(e.dataset.sizes)e.sizes=e.dataset.sizes,delete e.dataset.sizes}function xc(e,t,r){let n=()=>{if(e.classList.add("stx-video-loaded"),t)t(e)},o=()=>{if(e.classList.add("stx-video-error"),r)r(e,Error(`Failed to load video: ${e.src}`))};if(e.addEventListener("loadeddata",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.querySelectorAll("source[data-src]").forEach((s)=>{let i=s;if(i.dataset.src)i.src=i.dataset.src,delete i.dataset.src}),e.dataset.src)e.src=e.dataset.src,delete e.dataset.src;if(e.dataset.poster)e.poster=e.dataset.poster,delete e.dataset.poster;e.load()}function nm(e,t,r){let n=()=>{if(e.classList.add("stx-iframe-loaded"),t)t(e)},o=()=>{if(e.classList.add("stx-iframe-error"),r)r(e,Error(`Failed to load iframe: ${e.src}`))};if(e.addEventListener("load",n,{once:!0}),e.addEventListener("error",o,{once:!0}),e.dataset.src)e.src=e.dataset.src,delete e.dataset.src}function vc(e){et(e,{})}function $c(e="[data-stx-lazy]"){document.querySelectorAll(e).forEach((t)=>et(t,{}))}function Sc(e={}){let t={...bc,...e};return new IntersectionObserver((r,n)=>{r.forEach((o)=>{if(o.isIntersecting)et(o.target,t),n.unobserve(o.target)})},{root:t.root,rootMargin:t.rootMargin,threshold:t.threshold})}function kc(e,t){e.observe(t)}function Tc(e){e.disconnect()}function Qr(){return`
4108
4108
  (function() {
4109
4109
  'use strict';
4110
4110
 
@@ -4194,7 +4194,7 @@ else {
4194
4194
  window.STX.lazyLoad = loadElement;
4195
4195
  window.STX.initLazyLoading = init;
4196
4196
  })();
4197
- `.trim()}var nm={duration:300,easing:"ease-out",removePlaceholder:!1,loadedClass:"stx-img-loaded",loadingClass:"stx-img-loading"};function Do(e,t={}){let r={...nm,...t},n=e.closest(".stx-img-placeholder");if(!n){om(e,r);return}if(n.style.setProperty("--stx-img-transition-duration",`${r.duration}ms`),n.style.setProperty("--stx-img-transition-easing",r.easing),r.loadingClass)n.classList.add(r.loadingClass);if(e.complete&&e.naturalWidth>0)Tc(e,n,r);else e.addEventListener("load",()=>Tc(e,n,r),{once:!0}),e.addEventListener("error",()=>sm(e,n,r),{once:!0})}function om(e,t){let r=()=>{e.style.transition=`opacity ${t.duration}ms ${t.easing}`,e.style.opacity="1",e.classList.remove(t.loadingClass),e.classList.add(t.loadedClass)};if(e.complete&&e.naturalWidth>0)r();else e.style.opacity="0",e.classList.add(t.loadingClass),e.addEventListener("load",r,{once:!0})}function Tc(e,t,r){if(r.loadingClass)t.classList.remove(r.loadingClass);if(r.loadedClass)t.classList.add(r.loadedClass);if(e.style.opacity="1",r.removePlaceholder)setTimeout(()=>{t.style.backgroundImage="none"},r.duration)}function sm(e,t,r){if(r.loadingClass)t.classList.remove(r.loadingClass);t.classList.add("stx-img-error"),e.classList.add("stx-img-error")}function Cc(e,t){let r=Qr(e),n=t.getContext("2d");if(!n)return;t.width=r.w,t.height=r.h;let o=n.createImageData(r.w,r.h);o.data.set(r.rgba),n.putImageData(o,0,0)}function Qr(e){let t=e[0]|e[1]<<8|e[2]<<16,r=(t&63)/63,n=(t>>6&63)/31.5-1,o=(t>>12&63)/31.5-1,s=(t>>18&31)/31,i=t>>23!==0,a=e[3]|e[4]<<8,c=(a>>3&63)/63,l=(a>>9&63)/63,d=a>>15!==0,u=Math.max(3,d?i?5:7:i?5:5),p=Math.max(3,d?i?5:5:i?5:7),g=new Uint8ClampedArray(4096);for(let x=0;x<32;x++)for(let y=0;y<32;y++){let b=(x*32+y)*4,w=y/31,v=x/31,S=r+(w-0.5)*s*0.5+(v-0.5)*s*0.5,T=n*(1-w*0.3),C=o*(1-v*0.3),j=S-0.6666666666666666*T,k=(3*S-j+C)/2,L=k-C;g[b]=Math.max(0,Math.min(255,Math.round(k*255))),g[b+1]=Math.max(0,Math.min(255,Math.round(L*255))),g[b+2]=Math.max(0,Math.min(255,Math.round(j*255))),g[b+3]=255}return{w:32,h:32,rgba:g}}function Ec(e){let t=Qr(e),r=document.createElement("canvas");r.width=t.w,r.height=t.h;let n=r.getContext("2d");if(!n)return"";let o=n.createImageData(t.w,t.h);return o.data.set(t.rgba),n.putImageData(o,0,0),r.toDataURL("image/png")}function _c(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Ac(e,t,r=300){return new Promise((n)=>{e.style.transition=`opacity ${r}ms ease-out`,t.style.transition=`opacity ${r}ms ease-out`,t.style.opacity="0",t.offsetWidth,e.style.opacity="0",t.style.opacity="1",setTimeout(n,r)})}function jc(e={}){document.querySelectorAll("[data-stx-blur-up], .stx-img-placeholder img").forEach((t)=>{Do(t,e)})}function en(){return`
4197
+ `.trim()}var om={duration:300,easing:"ease-out",removePlaceholder:!1,loadedClass:"stx-img-loaded",loadingClass:"stx-img-loading"};function Po(e,t={}){let r={...om,...t},n=e.closest(".stx-img-placeholder");if(!n){sm(e,r);return}if(n.style.setProperty("--stx-img-transition-duration",`${r.duration}ms`),n.style.setProperty("--stx-img-transition-easing",r.easing),r.loadingClass)n.classList.add(r.loadingClass);if(e.complete&&e.naturalWidth>0)Cc(e,n,r);else e.addEventListener("load",()=>Cc(e,n,r),{once:!0}),e.addEventListener("error",()=>im(e,n,r),{once:!0})}function sm(e,t){let r=()=>{e.style.transition=`opacity ${t.duration}ms ${t.easing}`,e.style.opacity="1",e.classList.remove(t.loadingClass),e.classList.add(t.loadedClass)};if(e.complete&&e.naturalWidth>0)r();else e.style.opacity="0",e.classList.add(t.loadingClass),e.addEventListener("load",r,{once:!0})}function Cc(e,t,r){if(r.loadingClass)t.classList.remove(r.loadingClass);if(r.loadedClass)t.classList.add(r.loadedClass);if(e.style.opacity="1",r.removePlaceholder)setTimeout(()=>{t.style.backgroundImage="none"},r.duration)}function im(e,t,r){if(r.loadingClass)t.classList.remove(r.loadingClass);t.classList.add("stx-img-error"),e.classList.add("stx-img-error")}function Ec(e,t){let r=en(e),n=t.getContext("2d");if(!n)return;t.width=r.w,t.height=r.h;let o=n.createImageData(r.w,r.h);o.data.set(r.rgba),n.putImageData(o,0,0)}function en(e){let t=e[0]|e[1]<<8|e[2]<<16,r=(t&63)/63,n=(t>>6&63)/31.5-1,o=(t>>12&63)/31.5-1,s=(t>>18&31)/31,i=t>>23!==0,a=e[3]|e[4]<<8,c=(a>>3&63)/63,l=(a>>9&63)/63,d=a>>15!==0,u=Math.max(3,d?i?5:7:i?5:5),p=Math.max(3,d?i?5:5:i?5:7),g=new Uint8ClampedArray(4096);for(let x=0;x<32;x++)for(let y=0;y<32;y++){let b=(x*32+y)*4,w=y/31,v=x/31,k=r+(w-0.5)*s*0.5+(v-0.5)*s*0.5,C=n*(1-w*0.3),E=o*(1-v*0.3),R=k-0.6666666666666666*C,T=(3*k-R+E)/2,F=T-E;g[b]=Math.max(0,Math.min(255,Math.round(T*255))),g[b+1]=Math.max(0,Math.min(255,Math.round(F*255))),g[b+2]=Math.max(0,Math.min(255,Math.round(R*255))),g[b+3]=255}return{w:32,h:32,rgba:g}}function _c(e){let t=en(e),r=document.createElement("canvas");r.width=t.w,r.height=t.h;let n=r.getContext("2d");if(!n)return"";let o=n.createImageData(t.w,t.h);return o.data.set(t.rgba),n.putImageData(o,0,0),r.toDataURL("image/png")}function Ac(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function jc(e,t,r=300){return new Promise((n)=>{e.style.transition=`opacity ${r}ms ease-out`,t.style.transition=`opacity ${r}ms ease-out`,t.style.opacity="0",t.offsetWidth,e.style.opacity="0",t.style.opacity="1",setTimeout(n,r)})}function Rc(e={}){document.querySelectorAll("[data-stx-blur-up], .stx-img-placeholder img").forEach((t)=>{Po(t,e)})}function tn(){return`
4198
4198
  (function() {
4199
4199
  'use strict';
4200
4200
 
@@ -4256,7 +4256,7 @@ else {
4256
4256
  window.STX.initBlurUp = initBlurUp;
4257
4257
  window.STX.initAllBlurUp = init;
4258
4258
  })();
4259
- `.trim()}function tn(){return`
4259
+ `.trim()}function rn(){return`
4260
4260
  .stx-img-placeholder {
4261
4261
  position: relative;
4262
4262
  overflow: hidden;
@@ -4293,7 +4293,7 @@ else {
4293
4293
  .stx-img-error {
4294
4294
  opacity: 0.5;
4295
4295
  }
4296
- `.trim()}var im={method:"POST",fieldName:"file",timeout:60000,withCredentials:!1};function Po(e,t={}){if(t.maxSize&&e.size>t.maxSize)return{valid:!1,error:`File size (${Rc(e.size)}) exceeds maximum (${Rc(t.maxSize)})`,code:"FILE_TOO_LARGE"};if(t.accept&&t.accept.length>0){if(!t.accept.some((r)=>{if(r.endsWith("/*")){let n=r.slice(0,-1);return e.type.startsWith(n)}return e.type===r}))return{valid:!1,error:`File type "${e.type}" is not allowed`,code:"INVALID_TYPE"}}return{valid:!0}}function Rc(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(2)} MB`}async function Oo(e,t,r){let n={...im,...t},o=Po(e,n);if(!o.valid)return{success:!1,error:o.error,name:e.name,size:e.size,type:e.type};if(n.chunkSize&&e.size>n.chunkSize)return cm(e,n,r);return am(e,n,r)}async function am(e,t,r){return new Promise((n)=>{let o=new XMLHttpRequest,s=Date.now(),i=0,a=s;o.upload.addEventListener("progress",(l)=>{if(l.lengthComputable&&r){let d=Date.now(),u=(d-a)/1000,p=l.loaded-i,h=u>0?p/u:0,f=l.total-l.loaded,g=h>0?f/h*1000:void 0;i=l.loaded,a=d,r({file:e,loaded:l.loaded,total:l.total,percent:Math.round(l.loaded/l.total*100),speed:h,timeRemaining:g})}}),o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{let l=JSON.parse(o.responseText);n({success:!0,url:l.url,id:l.id,name:e.name,size:e.size,type:e.type,data:l})}catch{n({success:!0,name:e.name,size:e.size,type:e.type})}else n({success:!1,error:`Upload failed with status ${o.status}`,name:e.name,size:e.size,type:e.type})}),o.addEventListener("error",()=>{n({success:!1,error:"Network error during upload",name:e.name,size:e.size,type:e.type})}),o.addEventListener("timeout",()=>{n({success:!1,error:"Upload timed out",name:e.name,size:e.size,type:e.type})});let c=new FormData;if(c.append(t.fieldName||"file",e),t.formData)for(let[l,d]of Object.entries(t.formData))c.append(l,d);if(o.open(t.method||"POST",t.endpoint),o.timeout=t.timeout||60000,o.withCredentials=t.withCredentials||!1,t.headers)for(let[l,d]of Object.entries(t.headers))o.setRequestHeader(l,d);o.send(c)})}async function cm(e,t,r){let n=t.chunkSize,o=Math.ceil(e.size/n),s=0,i;for(let a=0;a<o;a++){let c=a*n,l=Math.min(c+n,e.size),d=e.slice(c,l),u=new FormData;if(u.append(t.fieldName||"file",d,e.name),u.append("chunk",String(a)),u.append("totalChunks",String(o)),u.append("fileName",e.name),u.append("fileSize",String(e.size)),u.append("fileType",e.type),i)u.append("uploadId",i);if(t.formData)for(let[p,h]of Object.entries(t.formData))u.append(p,h);try{let p=await fetch(t.endpoint,{method:t.method||"POST",headers:t.headers,credentials:t.withCredentials?"include":"same-origin",body:u});if(!p.ok)return{success:!1,error:`Chunk ${a+1}/${o} failed with status ${p.status}`,name:e.name,size:e.size,type:e.type};let h=await p.json();if(!i&&h.uploadId)i=h.uploadId;if(s=l,r)r({file:e,loaded:s,total:e.size,percent:Math.round(s/e.size*100),chunk:a+1,totalChunks:o});if(a===o-1)return{success:!0,url:h.url,id:h.id||i,name:e.name,size:e.size,type:e.type,data:h}}catch(p){return{success:!1,error:`Chunk upload failed: ${p}`,name:e.name,size:e.size,type:e.type}}}return{success:!1,error:"Unknown error during chunked upload",name:e.name,size:e.size,type:e.type}}async function Mc(e,t,r,n){let o=[];for(let s of e){let i=await Oo(s,t,(a)=>{if(r)r(s,a)});if(o.push(i),n)n(s,i)}return o}function Dc(e,t=200){return new Promise((r,n)=>{if(!e.type.startsWith("image/")){n(Error("File is not an image"));return}let o=new FileReader;o.onload=(s)=>{let i=new Image;i.onload=()=>{let a=document.createElement("canvas"),{width:c,height:l}=i;if(c>t||l>t)if(c>l)l=Math.round(l*t/c),c=t;else c=Math.round(c*t/l),l=t;a.width=c,a.height=l;let d=a.getContext("2d");if(d)d.drawImage(i,0,0,c,l),r(a.toDataURL("image/jpeg",0.7));else n(Error("Could not get canvas context"))},i.onerror=()=>n(Error("Could not load image")),i.src=s.target?.result},o.onerror=()=>n(Error("Could not read file")),o.readAsDataURL(e)})}function Pc(e){return new Promise((t,r)=>{if(!e.type.startsWith("video/")){r(Error("File is not a video"));return}let n=document.createElement("video"),o=document.createElement("canvas");n.preload="metadata",n.muted=!0,n.playsInline=!0,n.onloadeddata=()=>{n.currentTime=0.1},n.onseeked=()=>{o.width=n.videoWidth,o.height=n.videoHeight;let s=o.getContext("2d");if(s)s.drawImage(n,0,0),t(o.toDataURL("image/jpeg",0.7));else r(Error("Could not get canvas context"));URL.revokeObjectURL(n.src)},n.onerror=()=>{URL.revokeObjectURL(n.src),r(Error("Could not load video"))},n.src=URL.createObjectURL(e)})}function rn(){return`
4296
+ `.trim()}var am={method:"POST",fieldName:"file",timeout:60000,withCredentials:!1};function Oo(e,t={}){if(t.maxSize&&e.size>t.maxSize)return{valid:!1,error:`File size (${Mc(e.size)}) exceeds maximum (${Mc(t.maxSize)})`,code:"FILE_TOO_LARGE"};if(t.accept&&t.accept.length>0){if(!t.accept.some((r)=>{if(r.endsWith("/*")){let n=r.slice(0,-1);return e.type.startsWith(n)}return e.type===r}))return{valid:!1,error:`File type "${e.type}" is not allowed`,code:"INVALID_TYPE"}}return{valid:!0}}function Mc(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;return`${(e/1048576).toFixed(2)} MB`}async function Io(e,t,r){let n={...am,...t},o=Oo(e,n);if(!o.valid)return{success:!1,error:o.error,name:e.name,size:e.size,type:e.type};if(n.chunkSize&&e.size>n.chunkSize)return lm(e,n,r);return cm(e,n,r)}async function cm(e,t,r){return new Promise((n)=>{let o=new XMLHttpRequest,s=Date.now(),i=0,a=s;o.upload.addEventListener("progress",(l)=>{if(l.lengthComputable&&r){let d=Date.now(),u=(d-a)/1000,p=l.loaded-i,h=u>0?p/u:0,f=l.total-l.loaded,g=h>0?f/h*1000:void 0;i=l.loaded,a=d,r({file:e,loaded:l.loaded,total:l.total,percent:Math.round(l.loaded/l.total*100),speed:h,timeRemaining:g})}}),o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{let l=JSON.parse(o.responseText);n({success:!0,url:l.url,id:l.id,name:e.name,size:e.size,type:e.type,data:l})}catch{n({success:!0,name:e.name,size:e.size,type:e.type})}else n({success:!1,error:`Upload failed with status ${o.status}`,name:e.name,size:e.size,type:e.type})}),o.addEventListener("error",()=>{n({success:!1,error:"Network error during upload",name:e.name,size:e.size,type:e.type})}),o.addEventListener("timeout",()=>{n({success:!1,error:"Upload timed out",name:e.name,size:e.size,type:e.type})});let c=new FormData;if(c.append(t.fieldName||"file",e),t.formData)for(let[l,d]of Object.entries(t.formData))c.append(l,d);if(o.open(t.method||"POST",t.endpoint),o.timeout=t.timeout||60000,o.withCredentials=t.withCredentials||!1,t.headers)for(let[l,d]of Object.entries(t.headers))o.setRequestHeader(l,d);o.send(c)})}async function lm(e,t,r){let n=t.chunkSize,o=Math.ceil(e.size/n),s=0,i;for(let a=0;a<o;a++){let c=a*n,l=Math.min(c+n,e.size),d=e.slice(c,l),u=new FormData;if(u.append(t.fieldName||"file",d,e.name),u.append("chunk",String(a)),u.append("totalChunks",String(o)),u.append("fileName",e.name),u.append("fileSize",String(e.size)),u.append("fileType",e.type),i)u.append("uploadId",i);if(t.formData)for(let[p,h]of Object.entries(t.formData))u.append(p,h);try{let p=await fetch(t.endpoint,{method:t.method||"POST",headers:t.headers,credentials:t.withCredentials?"include":"same-origin",body:u});if(!p.ok)return{success:!1,error:`Chunk ${a+1}/${o} failed with status ${p.status}`,name:e.name,size:e.size,type:e.type};let h=await p.json();if(!i&&h.uploadId)i=h.uploadId;if(s=l,r)r({file:e,loaded:s,total:e.size,percent:Math.round(s/e.size*100),chunk:a+1,totalChunks:o});if(a===o-1)return{success:!0,url:h.url,id:h.id||i,name:e.name,size:e.size,type:e.type,data:h}}catch(p){return{success:!1,error:`Chunk upload failed: ${p}`,name:e.name,size:e.size,type:e.type}}}return{success:!1,error:"Unknown error during chunked upload",name:e.name,size:e.size,type:e.type}}async function Dc(e,t,r,n){let o=[];for(let s of e){let i=await Io(s,t,(a)=>{if(r)r(s,a)});if(o.push(i),n)n(s,i)}return o}function Pc(e,t=200){return new Promise((r,n)=>{if(!e.type.startsWith("image/")){n(Error("File is not an image"));return}let o=new FileReader;o.onload=(s)=>{let i=new Image;i.onload=()=>{let a=document.createElement("canvas"),{width:c,height:l}=i;if(c>t||l>t)if(c>l)l=Math.round(l*t/c),c=t;else c=Math.round(c*t/l),l=t;a.width=c,a.height=l;let d=a.getContext("2d");if(d)d.drawImage(i,0,0,c,l),r(a.toDataURL("image/jpeg",0.7));else n(Error("Could not get canvas context"))},i.onerror=()=>n(Error("Could not load image")),i.src=s.target?.result},o.onerror=()=>n(Error("Could not read file")),o.readAsDataURL(e)})}function Oc(e){return new Promise((t,r)=>{if(!e.type.startsWith("video/")){r(Error("File is not a video"));return}let n=document.createElement("video"),o=document.createElement("canvas");n.preload="metadata",n.muted=!0,n.playsInline=!0,n.onloadeddata=()=>{n.currentTime=0.1},n.onseeked=()=>{o.width=n.videoWidth,o.height=n.videoHeight;let s=o.getContext("2d");if(s)s.drawImage(n,0,0),t(o.toDataURL("image/jpeg",0.7));else r(Error("Could not get canvas context"));URL.revokeObjectURL(n.src)},n.onerror=()=>{URL.revokeObjectURL(n.src),r(Error("Could not load video"))},n.src=URL.createObjectURL(e)})}function nn(){return`
4297
4297
  (function() {
4298
4298
  'use strict';
4299
4299
 
@@ -4361,18 +4361,18 @@ else {
4361
4361
  return { valid: true };
4362
4362
  };
4363
4363
  })();
4364
- `.trim()}function Oc(){return{script:[Zr(),en(),rn()].join(`
4364
+ `.trim()}function Ic(){return{script:[Qr(),tn(),nn()].join(`
4365
4365
 
4366
- `),css:tn()}}function lm(){let{script:e,css:t}=Oc(),r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim(),n=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim();return{script:r,css:n}}var S$={enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3]},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}};import Io from"fs";import ft from"path";async function Ic(e,t={},r={}){let n=await Bun.file(e).text(),o=n.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),s=o?o[1]:"",i=o?n.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):n;i=i.replace(/<script\s+client\s*>/gi,"<script>");let a={__filename:e,__dirname:ft.dirname(e),props:t,...t};if(s)await te(s,a,e);let c={...Dt,...r};return await se(i,a,e,c,new Set)}async function zm(e){let t=performance.now(),r={success:!0,views:[],errors:[],duration:0},{viewsDir:n,outputDir:o,componentsDir:s=ft.join(n,"components"),layoutsDir:i=ft.join(n,"layouts"),partialsDir:a=ft.join(n,"partials"),globalProps:c={},placeholders:l={},views:d,debug:u=!1,generateManifest:p=!0}=e;if(u)console.log("Building STX views..."),console.log(` Source: ${n}`),console.log(` Output: ${o}`);Io.mkdirSync(o,{recursive:!0});let h={componentsDir:s,layoutsDir:i,partialsDir:a,debug:u},f;if(d&&d.length>0)f=d;else f=Io.readdirSync(n).filter((g)=>g.endsWith(".stx")).map((g)=>({input:g}));for(let g of f){let x=ft.join(n,g.input),y=g.output||g.input.replace(/\.stx$/,".html"),b=ft.join(o,y);if(u)console.log(` Building ${g.input}...`);try{let w={...c,...g.props,...l},v=await Ic(x,w,h);await Bun.write(b,v),r.views.push(y)}catch(w){let v=w instanceof Error?w.message:String(w);if(r.errors.push({file:g.input,error:v}),r.success=!1,u)console.error(` Error: ${v}`)}}if(p){let g={buildTime:new Date().toISOString(),views:r.views,placeholders:l,errors:r.errors.length>0?r.errors:void 0};await Bun.write(ft.join(o,"manifest.json"),JSON.stringify(g,null,2))}if(r.duration=performance.now()-t,u)if(r.success)console.log(`
4366
+ `),css:rn()}}function dm(){let{script:e,css:t}=Ic(),r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim(),n=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{};,:])\s*/g,"$1").trim();return{script:r,css:n}}var k$={enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3]},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}};import Lo from"fs";import mt from"path";async function Lc(e,t={},r={}){let n=await Bun.file(e).text(),o=n.match(/<script\s+server\s*>([\s\S]*?)<\/script>/i),s=o?o[1]:"",i=o?n.replace(/<script\s+server\s*>[\s\S]*?<\/script>/i,""):n;i=i.replace(/<script\s+client\s*>/gi,"<script>");let a={__filename:e,__dirname:mt.dirname(e),props:t,...t};if(s)await re(s,a,e);let c={...Pt,...r};return await ie(i,a,e,c,new Set)}async function Um(e){let t=performance.now(),r={success:!0,views:[],errors:[],duration:0},{viewsDir:n,outputDir:o,componentsDir:s=mt.join(n,"components"),layoutsDir:i=mt.join(n,"layouts"),partialsDir:a=mt.join(n,"partials"),globalProps:c={},placeholders:l={},views:d,debug:u=!1,generateManifest:p=!0}=e;if(u)console.log("Building STX views..."),console.log(` Source: ${n}`),console.log(` Output: ${o}`);Lo.mkdirSync(o,{recursive:!0});let h={componentsDir:s,layoutsDir:i,partialsDir:a,debug:u},f;if(d&&d.length>0)f=d;else f=Lo.readdirSync(n).filter((g)=>g.endsWith(".stx")).map((g)=>({input:g}));for(let g of f){let x=mt.join(n,g.input),y=g.output||g.input.replace(/\.stx$/,".html"),b=mt.join(o,y);if(u)console.log(` Building ${g.input}...`);try{let w={...c,...g.props,...l},v=await Lc(x,w,h);await Bun.write(b,v),r.views.push(y)}catch(w){let v=w instanceof Error?w.message:String(w);if(r.errors.push({file:g.input,error:v}),r.success=!1,u)console.error(` Error: ${v}`)}}if(p){let g={buildTime:new Date().toISOString(),views:r.views,placeholders:l,errors:r.errors.length>0?r.errors:void 0};await Bun.write(mt.join(o,"manifest.json"),JSON.stringify(g,null,2))}if(r.duration=performance.now()-t,u)if(r.success)console.log(`
4367
4367
  \u2705 Built ${r.views.length} views in ${r.duration.toFixed(0)}ms`);else console.log(`
4368
- \u26A0\uFE0F Built ${r.views.length} views with ${r.errors.length} errors`);return r}function N$(e,t){let r=Io.watch(e.viewsDir,{recursive:!0},async(n,o)=>{if(!o)return;if(o.endsWith(".stx")||o.endsWith(".ts")||o.endsWith(".js")){if(e.debug)console.log(`
4369
- File changed: ${o}, rebuilding...`);let s=await zm(e);t?.(s)}});return{close:()=>r.close()}}async function B$(e,t={},r={}){let n={...r,skipDefaultSeoTags:!0,skipSignalsRuntime:!0},o=await Ic(e,t,n);o=await Um(o),o=o.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),o=o.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),o=o.replace(/<!--\s*stx SEO Tags\s*-->/gi,""),o=o.replace(/\n\s*\n\s*\n/g,`
4368
+ \u26A0\uFE0F Built ${r.views.length} views with ${r.errors.length} errors`);return r}function B$(e,t){let r=Lo.watch(e.viewsDir,{recursive:!0},async(n,o)=>{if(!o)return;if(o.endsWith(".stx")||o.endsWith(".ts")||o.endsWith(".js")){if(e.debug)console.log(`
4369
+ File changed: ${o}, rebuilding...`);let s=await Um(e);t?.(s)}});return{close:()=>r.close()}}async function z$(e,t={},r={}){let n={...r,skipDefaultSeoTags:!0,skipSignalsRuntime:!0},o=await Lc(e,t,n);o=await Hm(o),o=o.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),o=o.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,""),o=o.replace(/<!--\s*stx SEO Tags\s*-->/gi,""),o=o.replace(/\n\s*\n\s*\n/g,`
4370
4370
 
4371
- `).trim();let s=Wm(o);return{html:o,text:s}}async function Um(e){try{let{generateCrosswindCSS:t,extractClassNames:r}=await import("./chunk-fjf53b44.js");if(r(e).size===0)return e;let n=await t(e);if(!n)return e;let o=Hm(n);if(o.size===0)return e;return e.replace(/(<[a-z][a-z0-9]*)((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s+)class\s*=\s*"([^"]*)"((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s*)(\/?>)/gi,(s,i,a,c,l,d)=>{let u=c.split(/\s+/).filter(Boolean),p=[];for(let g of u){let x=o.get(g);if(x)p.push(x)}if(p.length===0)return`${i}${a}class="${c}"${l}${d}`;let h=p.join("; "),f=`${a}${l}`.match(/style\s*=\s*"([^"]*)"/);if(f){let g=`${h}; ${f[1]}`,x=a.replace(/style\s*=\s*"[^"]*"/,`style="${g}"`),y=l.replace(/style\s*=\s*"[^"]*"/,`style="${g}"`);return`${i}${x}class="${c}"${y}${d}`}return`${i}${a}class="${c}" style="${h}"${l}${d}`})}catch{return e}}function Hm(e){let t=new Map,r=/\.([a-zA-Z0-9_-]+(?:\\:[a-zA-Z0-9_-]+)*)\s*\{([^}]+)\}/g,n=r.exec(e);while(n!==null){let o=n[1].replace(/\\/g,""),s=n[2].split(";").map((i)=>i.trim()).filter(Boolean).join("; ");if(s)t.set(o,s);n=r.exec(e)}return t}function Wm(e){return e.replace(/<br\s*\/?>/gi,`
4371
+ `).trim();let s=Vm(o);return{html:o,text:s}}async function Hm(e){try{let{generateCrosswindCSS:t,extractClassNames:r}=await import("./chunk-fqhckdt8.js");if(r(e).size===0)return e;let n=await t(e);if(!n)return e;let o=Wm(n);if(o.size===0)return e;return e.replace(/(<[a-z][a-z0-9]*)((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s+)class\s*=\s*"([^"]*)"((?:\s+[a-z][a-z0-9-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*))?)*\s*)(\/?>)/gi,(s,i,a,c,l,d)=>{let u=c.split(/\s+/).filter(Boolean),p=[];for(let g of u){let x=o.get(g);if(x)p.push(x)}if(p.length===0)return`${i}${a}class="${c}"${l}${d}`;let h=p.join("; "),f=`${a}${l}`.match(/style\s*=\s*"([^"]*)"/);if(f){let g=`${h}; ${f[1]}`,x=a.replace(/style\s*=\s*"[^"]*"/,`style="${g}"`),y=l.replace(/style\s*=\s*"[^"]*"/,`style="${g}"`);return`${i}${x}class="${c}"${y}${d}`}return`${i}${a}class="${c}" style="${h}"${l}${d}`})}catch{return e}}function Wm(e){let t=new Map,r=/\.([a-zA-Z0-9_-]+(?:\\:[a-zA-Z0-9_-]+)*)\s*\{([^}]+)\}/g,n=r.exec(e);while(n!==null){let o=n[1].replace(/\\/g,""),s=n[2].split(";").map((i)=>i.trim()).filter(Boolean).join("; ");if(s)t.set(o,s);n=r.exec(e)}return t}function Vm(e){return e.replace(/<br\s*\/?>/gi,`
4372
4372
  `).replace(/<\/(p|div|h[1-6]|li|tr)>/gi,`
4373
4373
  `).replace(/<\/td>/gi,"\t").replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&copy;/g,"(c)").replace(/&middot;/g,"-").replace(/\n\s*\n\s*\n/g,`
4374
4374
 
4375
- `).trim()}function Vm(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function qm(e){let t={};for(let r of Object.keys(e))if(!r.startsWith("__"))t[r]=e[r];return t}function U$(e){let{template:t,context:r={},title:n="stx App"}=e,o=qm(r),s=Vm(JSON.stringify(o));return`<!DOCTYPE html>
4375
+ `).trim()}function qm(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Xm(e){let t={};for(let r of Object.keys(e))if(!r.startsWith("__"))t[r]=e[r];return t}function H$(e){let{template:t,context:r={},title:n="stx App"}=e,o=Xm(r),s=qm(JSON.stringify(o));return`<!DOCTYPE html>
4376
4376
  <html lang="en">
4377
4377
  <head>
4378
4378
  <meta charset="UTF-8">
@@ -4392,7 +4392,7 @@ File changed: ${o}, rebuilding...`);let s=await zm(e);t?.(s)}});return{close:()=
4392
4392
  }
4393
4393
  </script>
4394
4394
  </body>
4395
- </html>`}var Te=null;function Xm(e,t){if(Te)Te.provides.set(e,t);else nn.set(e,t)}function Jm(e,t){let r=Te;while(r){if(r.provides.has(e))return r.provides.get(e);r=r.parent}if(nn.has(e))return nn.get(e);return t}var nn=new Map;function Lo(e,t){nn.set(e,t)}function Ym(e){let t=Te,r=t?.el,n=Array.isArray(e)?e:e&&typeof e==="object"?Object.keys(e):[];if(r&&n.length>0){let s=r.__stx_component_emits||=Object.create(null);for(let i of n)s[i]=!0}let o=(s,...i)=>{if(typeof document>"u")return;if(r){let a=r.__stx_component_emits||=Object.create(null);a[s]=!0,r.dispatchEvent(new CustomEvent(s,{detail:i.length===1?i[0]:i,bubbles:!0,cancelable:!0}))}};if(t)t.emit=o;return o}function Km(e){if(Te)Te.exposed=e}function Gm(e){let t=Promise.resolve();return e?t.then(e):t}function Zm(e){if(Te)Te.errorCapturedHooks.push(e)}function Qm(e,t,r){let n=t?.parent;while(n){for(let o of n.errorCapturedHooks)if(o(e,t,r)===!1)return;n=n.parent}}function eh(){return Te?.slots??{}}function th(){return Te?.slots??{}}function rh(){return Te?.attrs??{}}function nh(e){let t=e.__provides?new Map(Object.entries(e.__provides)):new Map;return{...e,__provides:t,__provide(r,n){t.set(r,n)},__inject(r,n){if(t.has(r))return t.get(r);if(e.__provides){let o=e.__provides instanceof Map?e.__provides:new Map(Object.entries(e.__provides));if(o.has(r))return o.get(r)}return n}}}function oh(){return`
4395
+ </html>`}var Ce=null;function Jm(e,t){if(Ce)Ce.provides.set(e,t);else on.set(e,t)}function Ym(e,t){let r=Ce;while(r){if(r.provides.has(e))return r.provides.get(e);r=r.parent}if(on.has(e))return on.get(e);return t}var on=new Map;function Fo(e,t){on.set(e,t)}function Km(e){let t=Ce,r=t?.el,n=Array.isArray(e)?e:e&&typeof e==="object"?Object.keys(e):[];if(r&&n.length>0){let s=r.__stx_component_emits||=Object.create(null);for(let i of n)s[i]=!0}let o=(s,...i)=>{if(typeof document>"u")return;if(r){let a=r.__stx_component_emits||=Object.create(null);a[s]=!0,r.dispatchEvent(new CustomEvent(s,{detail:i.length===1?i[0]:i,bubbles:!0,cancelable:!0}))}};if(t)t.emit=o;return o}function Gm(e){if(Ce)Ce.exposed=e}function Zm(e){let t=Promise.resolve();return e?t.then(e):t}function Qm(e){if(Ce)Ce.errorCapturedHooks.push(e)}function eh(e,t,r){let n=t?.parent;while(n){for(let o of n.errorCapturedHooks)if(o(e,t,r)===!1)return;n=n.parent}}function th(){return Ce?.slots??{}}function rh(){return Ce?.slots??{}}function nh(){return Ce?.attrs??{}}function oh(e){let t=e.__provides?new Map(Object.entries(e.__provides)):new Map;return{...e,__provides:t,__provide(r,n){t.set(r,n)},__inject(r,n){if(t.has(r))return t.get(r);if(e.__provides){let o=e.__provides instanceof Map?e.__provides:new Map(Object.entries(e.__provides));if(o.has(r))return o.get(r)}return n}}}function sh(){return`
4396
4396
  // STX Composition API Runtime
4397
4397
  (function() {
4398
4398
  const _provides = new Map();
@@ -4457,7 +4457,7 @@ File changed: ${o}, rebuilding...`);let s=await zm(e);t?.(s)}});return{close:()=
4457
4457
  return refs;
4458
4458
  };
4459
4459
  })();
4460
- `}var Ot=Symbol.for("stx.Fragment"),sh=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Fc=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),Nc={className:"class",htmlFor:"for",tabIndex:"tabindex",autoFocus:"autofocus",autoPlay:"autoplay",crossOrigin:"crossorigin",dateTime:"datetime",encType:"enctype",formAction:"formaction",formEncType:"formenctype",formMethod:"formmethod",formNoValidate:"formnovalidate",formTarget:"formtarget",frameBorder:"frameborder",hrefLang:"hreflang",httpEquiv:"http-equiv",inputMode:"inputmode",maxLength:"maxlength",mediaGroup:"mediagroup",minLength:"minlength",noModule:"nomodule",noValidate:"novalidate",playsInline:"playsinline",readOnly:"readonly",rowSpan:"rowspan",colSpan:"colspan",srcDoc:"srcdoc",srcLang:"srclang",srcSet:"srcset",useMap:"usemap"};function ih(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Fo(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function Bc(e){if(e==null||typeof e==="boolean")return[];if(!Array.isArray(e))return[Lc(e)];return e.flat(1/0).map(Lc).filter((t)=>t!=="")}function Lc(e){if(e==null||typeof e==="boolean")return"";if(typeof e==="string")return e;if(typeof e==="number")return String(e);return e}function It(e,t,r){let{children:n,ref:o,key:s,...i}=t||{};return{type:e,props:Object.keys(i).length>0?i:null,children:Bc(n),key:r??s??void 0,ref:o??void 0}}var ah=It,ch=It;function zc(e){return Object.entries(e).filter(([,t])=>t!=null&&t!==!1).map(([t,r])=>{let n=t.replace(/[A-Z]/g,(s)=>`-${s.toLowerCase()}`),o=typeof r==="number"&&!n.startsWith("--")&&n!=="opacity"&&n!=="z-index"&&n!=="flex-grow"&&n!=="flex-shrink"&&n!=="order"&&n!=="font-weight"&&n!=="line-height"?`${r}px`:String(r);return`${n}: ${o}`}).join("; ")}function No(e){if(typeof e==="string")return e;if(Array.isArray(e))return e.filter(Boolean).map(No).join(" ");if(typeof e==="object"&&e!==null)return Object.entries(e).filter(([,t])=>t).map(([t])=>t).join(" ");return""}function lh(e){if(!e)return"";let t=[];for(let[r,n]of Object.entries(e)){if(r==="key"||r==="ref"||r==="children"||r==="innerHTML"||r==="dangerouslySetInnerHTML")continue;if(r.startsWith("on")&&typeof n==="function")continue;let o=Nc[r]||r;if(o==="class"||o==="className"){let s=No(n);if(s)t.push(` class="${Fo(s)}"`);continue}if(o==="style"){let s=typeof n==="string"?n:zc(n);if(s)t.push(` style="${Fo(s)}"`);continue}if(Fc.has(o)){if(n)t.push(` ${o}`);continue}if(n!=null&&n!==!1)t.push(` ${o}="${Fo(String(n))}"`)}return t.join("")}function Pt(e){if(e==null||typeof e==="boolean")return"";if(typeof e==="string")return ih(e);if(typeof e==="number")return String(e);if(Array.isArray(e))return e.map(Pt).join("");if(e.type===Ot)return e.children.map(Pt).join("");if(typeof e.type==="function"){let s=e.type({...e.props,children:e.children.length===1?e.children[0]:e.children.length>0?e.children:void 0});return Pt(s)}let t=e.type,r=lh(e.props),n=e.props?.innerHTML??e.props?.dangerouslySetInnerHTML?.__html;if(n!=null)return`<${t}${r}>${n}</${t}>`;if(sh.has(t))return`<${t}${r}>`;let o=e.children.map(Pt).join("");return`<${t}${r}>${o}</${t}>`}function dh(e){return new ReadableStream({start(t){t.enqueue(Pt(e)),t.close()}})}function uh(e,t){if(!t)return;for(let[r,n]of Object.entries(t)){if(r==="key"||r==="ref"||r==="children"||r==="innerHTML"||r==="dangerouslySetInnerHTML")continue;let o=Nc[r]||r;if(r.startsWith("on")&&typeof n==="function"){let s=r.slice(2).toLowerCase();e.addEventListener(s,n);continue}if(o==="class"||o==="className"){let s=No(n);if(s)e.setAttribute("class",s);continue}if(o==="style"){let s=typeof n==="string"?n:zc(n);if(s)e.setAttribute("style",s);continue}if(Fc.has(o)){if(n)e.setAttribute(o,"");continue}if(n!=null&&n!==!1)e.setAttribute(o,String(n))}}function sr(e,t){if(e==null||typeof e==="boolean")return;if(typeof e==="string"){t.appendChild(document.createTextNode(e));return}if(typeof e==="number"){t.appendChild(document.createTextNode(String(e)));return}if(Array.isArray(e)){for(let o of e)sr(o,t);return}if(e.type===Ot){for(let o of e.children)sr(o,t);return}if(typeof e.type==="function"){let o=e.type({...e.props,children:e.children.length===1?e.children[0]:e.children.length>0?e.children:void 0});sr(o,t);return}let r=document.createElement(e.type);uh(r,e.props);let n=e.props?.innerHTML??e.props?.dangerouslySetInnerHTML?.__html;if(n!=null)r.innerHTML=n;else for(let o of e.children)sr(o,r);if(e.ref){if(typeof e.ref==="function")e.ref(r)}t.appendChild(r)}function ph(e){if(e.when)return It(Ot,{children:e.children});return e.fallback??null}function fh(e){let t=e.each;if(!t||t.length===0)return e.fallback??null;let r=Array.isArray(e.children)?e.children[0]:e.children,n=t.map((o,s)=>r(o,s));return It(Ot,{children:n})}function mh(e){return It(Ot,{children:e.children})}function hh(e,t,...r){let{key:n,ref:o,...s}=t||{};return{type:e,props:Object.keys(s).length>0?s:{},children:Bc(r.length===1?r[0]:r),key:n??void 0,ref:o??void 0}}function Uc(e,t){let r=new Set,n=new Map,o=new Map,s={globalProperties:{},performance:!1,compilerOptions:{}},i={config:s,_components:n,_directives:o,_installedPlugins:r,use(a,...c){if(r.has(a))return i;if(r.add(a),typeof a==="function")a(i,...c);else if(typeof a.install==="function")a.install(i,...c);return i},provide(a,c){return Lo(a,c),i},component(a,c){if(!c)return n.get(a);return n.set(a,c),i},directive(a,c){if(!c)return o.get(a);return o.set(a,c),i},mount(a){if(typeof document<"u"){let c=globalThis.__stx_globals||(globalThis.__stx_globals={});Object.assign(c,s.globalProperties),document.querySelectorAll("[v-cloak]").forEach((l)=>{l.removeAttribute("v-cloak")})}return i},unmount(){n.clear(),o.clear(),r.clear()}};return i}function gh(e){return class extends HTMLElement{_component;_shadow;constructor(){super();this._shadow=this.attachShadow({mode:"open"}),this._component=e}connectedCallback(){if(this._component?.render){let t=this._component.render();if(typeof t==="string")this._shadow.innerHTML=t}else if(this._component?.template)this._shadow.innerHTML=this._component.template;else if(typeof this._component==="string")this._shadow.innerHTML=this._component}disconnectedCallback(){this._shadow.innerHTML=""}}}import{dirname as yh,resolve as qc}from"path";function Bo(e){return e.endsWith(".md")||e.endsWith(".markdown")}function Vc(e){let t=[];n(/<pre\b[^>]*>[\s\S]*?<\/pre>/gi);let r=[...t];n(/<code\b[^>]*>[\s\S]*?<\/code>/gi,r);function n(i,a){let c;while((c=i.exec(e))!==null){let l=c.index,d=l+c[0].length;if(a?.some((u)=>l>=u.start&&d<=u.end))continue;t.push({start:l,end:d})}}if(t.length===0)return e;t.sort((i,a)=>i.start-a.start);let o="",s=0;for(let i of t){if(i.start<s)continue;o+=e.slice(s,i.start),o+=`@raw${e.slice(i.start,i.end)}@endraw`,s=i.end}return o+=e.slice(s),o}async function zo(e,t={}){let{data:r,content:n}=Hc(e),o=await(t.renderer??((s)=>Wc(s)))(n);return{html:Vc(o),frontmatter:r??{}}}function xh(e){let t=e,r=kt(e);if(r)t=r.content.trim();let n=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,o=[],s=[],i=[],a=(d)=>/\b(?:state|derived|effect|batch)\s*(?:<[^<>()]*>)?\s*\(/.test(d),c;while((c=n.exec(e))!==null){let d=c[1],u=c[2],p=c[0],h=d.includes("server");if(a(u))i.push(p);else if(h)s.push(u);else o.push(p)}let l=t;{let d=/<script\b(?![^>]*\b(?:client|type\s*=\s*["']module["']|src\s*=))[^>]*>/gi,u,p=[];while((u=d.exec(l))!==null){let h=u.index+u[0].length,f=l.indexOf("</script>",h);if(f===-1)continue;p.push({start:u.index,end:f+9}),d.lastIndex=f+9}for(let h=p.length-1;h>=0;h--)l=l.substring(0,p[h].start)+l.substring(p[h].end)}for(let d of o)l=l.replace(d,"");return{templateContent:l,serverScripts:s,clientScripts:o,signalsScripts:i}}function bh(e,t){return`<!DOCTYPE html>
4460
+ `}var It=Symbol.for("stx.Fragment"),ih=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Nc=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),Bc={className:"class",htmlFor:"for",tabIndex:"tabindex",autoFocus:"autofocus",autoPlay:"autoplay",crossOrigin:"crossorigin",dateTime:"datetime",encType:"enctype",formAction:"formaction",formEncType:"formenctype",formMethod:"formmethod",formNoValidate:"formnovalidate",formTarget:"formtarget",frameBorder:"frameborder",hrefLang:"hreflang",httpEquiv:"http-equiv",inputMode:"inputmode",maxLength:"maxlength",mediaGroup:"mediagroup",minLength:"minlength",noModule:"nomodule",noValidate:"novalidate",playsInline:"playsinline",readOnly:"readonly",rowSpan:"rowspan",colSpan:"colspan",srcDoc:"srcdoc",srcLang:"srclang",srcSet:"srcset",useMap:"usemap"};function ah(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function No(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function zc(e){if(e==null||typeof e==="boolean")return[];if(!Array.isArray(e))return[Fc(e)];return e.flat(1/0).map(Fc).filter((t)=>t!=="")}function Fc(e){if(e==null||typeof e==="boolean")return"";if(typeof e==="string")return e;if(typeof e==="number")return String(e);return e}function Lt(e,t,r){let{children:n,ref:o,key:s,...i}=t||{};return{type:e,props:Object.keys(i).length>0?i:null,children:zc(n),key:r??s??void 0,ref:o??void 0}}var ch=Lt,lh=Lt;function Uc(e){return Object.entries(e).filter(([,t])=>t!=null&&t!==!1).map(([t,r])=>{let n=t.replace(/[A-Z]/g,(s)=>`-${s.toLowerCase()}`),o=typeof r==="number"&&!n.startsWith("--")&&n!=="opacity"&&n!=="z-index"&&n!=="flex-grow"&&n!=="flex-shrink"&&n!=="order"&&n!=="font-weight"&&n!=="line-height"?`${r}px`:String(r);return`${n}: ${o}`}).join("; ")}function Bo(e){if(typeof e==="string")return e;if(Array.isArray(e))return e.filter(Boolean).map(Bo).join(" ");if(typeof e==="object"&&e!==null)return Object.entries(e).filter(([,t])=>t).map(([t])=>t).join(" ");return""}function dh(e){if(!e)return"";let t=[];for(let[r,n]of Object.entries(e)){if(r==="key"||r==="ref"||r==="children"||r==="innerHTML"||r==="dangerouslySetInnerHTML")continue;if(r.startsWith("on")&&typeof n==="function")continue;let o=Bc[r]||r;if(o==="class"||o==="className"){let s=Bo(n);if(s)t.push(` class="${No(s)}"`);continue}if(o==="style"){let s=typeof n==="string"?n:Uc(n);if(s)t.push(` style="${No(s)}"`);continue}if(Nc.has(o)){if(n)t.push(` ${o}`);continue}if(n!=null&&n!==!1)t.push(` ${o}="${No(String(n))}"`)}return t.join("")}function Ot(e){if(e==null||typeof e==="boolean")return"";if(typeof e==="string")return ah(e);if(typeof e==="number")return String(e);if(Array.isArray(e))return e.map(Ot).join("");if(e.type===It)return e.children.map(Ot).join("");if(typeof e.type==="function"){let s=e.type({...e.props,children:e.children.length===1?e.children[0]:e.children.length>0?e.children:void 0});return Ot(s)}let t=e.type,r=dh(e.props),n=e.props?.innerHTML??e.props?.dangerouslySetInnerHTML?.__html;if(n!=null)return`<${t}${r}>${n}</${t}>`;if(ih.has(t))return`<${t}${r}>`;let o=e.children.map(Ot).join("");return`<${t}${r}>${o}</${t}>`}function uh(e){return new ReadableStream({start(t){t.enqueue(Ot(e)),t.close()}})}function ph(e,t){if(!t)return;for(let[r,n]of Object.entries(t)){if(r==="key"||r==="ref"||r==="children"||r==="innerHTML"||r==="dangerouslySetInnerHTML")continue;let o=Bc[r]||r;if(r.startsWith("on")&&typeof n==="function"){let s=r.slice(2).toLowerCase();e.addEventListener(s,n);continue}if(o==="class"||o==="className"){let s=Bo(n);if(s)e.setAttribute("class",s);continue}if(o==="style"){let s=typeof n==="string"?n:Uc(n);if(s)e.setAttribute("style",s);continue}if(Nc.has(o)){if(n)e.setAttribute(o,"");continue}if(n!=null&&n!==!1)e.setAttribute(o,String(n))}}function ir(e,t){if(e==null||typeof e==="boolean")return;if(typeof e==="string"){t.appendChild(document.createTextNode(e));return}if(typeof e==="number"){t.appendChild(document.createTextNode(String(e)));return}if(Array.isArray(e)){for(let o of e)ir(o,t);return}if(e.type===It){for(let o of e.children)ir(o,t);return}if(typeof e.type==="function"){let o=e.type({...e.props,children:e.children.length===1?e.children[0]:e.children.length>0?e.children:void 0});ir(o,t);return}let r=document.createElement(e.type);ph(r,e.props);let n=e.props?.innerHTML??e.props?.dangerouslySetInnerHTML?.__html;if(n!=null)r.innerHTML=n;else for(let o of e.children)ir(o,r);if(e.ref){if(typeof e.ref==="function")e.ref(r)}t.appendChild(r)}function fh(e){if(e.when)return Lt(It,{children:e.children});return e.fallback??null}function mh(e){let t=e.each;if(!t||t.length===0)return e.fallback??null;let r=Array.isArray(e.children)?e.children[0]:e.children,n=t.map((o,s)=>r(o,s));return Lt(It,{children:n})}function hh(e){return Lt(It,{children:e.children})}function gh(e,t,...r){let{key:n,ref:o,...s}=t||{};return{type:e,props:Object.keys(s).length>0?s:{},children:zc(r.length===1?r[0]:r),key:n??void 0,ref:o??void 0}}function Hc(e,t){let r=new Set,n=new Map,o=new Map,s={globalProperties:{},performance:!1,compilerOptions:{}},i={config:s,_components:n,_directives:o,_installedPlugins:r,use(a,...c){if(r.has(a))return i;if(r.add(a),typeof a==="function")a(i,...c);else if(typeof a.install==="function")a.install(i,...c);return i},provide(a,c){return Fo(a,c),i},component(a,c){if(!c)return n.get(a);return n.set(a,c),i},directive(a,c){if(!c)return o.get(a);return o.set(a,c),i},mount(a){if(typeof document<"u"){let c=globalThis.__stx_globals||(globalThis.__stx_globals={});Object.assign(c,s.globalProperties),document.querySelectorAll("[v-cloak]").forEach((l)=>{l.removeAttribute("v-cloak")})}return i},unmount(){n.clear(),o.clear(),r.clear()}};return i}function yh(e){return class extends HTMLElement{_component;_shadow;constructor(){super();this._shadow=this.attachShadow({mode:"open"}),this._component=e}connectedCallback(){if(this._component?.render){let t=this._component.render();if(typeof t==="string")this._shadow.innerHTML=t}else if(this._component?.template)this._shadow.innerHTML=this._component.template;else if(typeof this._component==="string")this._shadow.innerHTML=this._component}disconnectedCallback(){this._shadow.innerHTML=""}}}import{dirname as xh,resolve as Xc}from"path";function zo(e){return e.endsWith(".md")||e.endsWith(".markdown")}function qc(e){let t=[];n(/<pre\b[^>]*>[\s\S]*?<\/pre>/gi);let r=[...t];n(/<code\b[^>]*>[\s\S]*?<\/code>/gi,r);function n(i,a){let c;while((c=i.exec(e))!==null){let l=c.index,d=l+c[0].length;if(a?.some((u)=>l>=u.start&&d<=u.end))continue;t.push({start:l,end:d})}}if(t.length===0)return e;t.sort((i,a)=>i.start-a.start);let o="",s=0;for(let i of t){if(i.start<s)continue;o+=e.slice(s,i.start),o+=`@raw${e.slice(i.start,i.end)}@endraw`,s=i.end}return o+=e.slice(s),o}async function Uo(e,t={}){let{data:r,content:n}=Wc(e),o=await(t.renderer??((s)=>Vc(s)))(n);return{html:qc(o),frontmatter:r??{}}}function bh(e){let t=e,r=Tt(e);if(r)t=r.content.trim();let n=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,o=[],s=[],i=[],a=(d)=>/\b(?:state|derived|effect|batch)\s*(?:<[^<>()]*>)?\s*\(/.test(d),c;while((c=n.exec(e))!==null){let d=c[1],u=c[2],p=c[0],h=d.includes("server");if(a(u))i.push(p);else if(h)s.push(u);else o.push(p)}let l=t;{let d=/<script\b(?![^>]*\b(?:client|type\s*=\s*["']module["']|src\s*=))[^>]*>/gi,u,p=[];while((u=d.exec(l))!==null){let h=u.index+u[0].length,f=l.indexOf("</script>",h);if(f===-1)continue;p.push({start:u.index,end:f+9}),d.lastIndex=f+9}for(let h=p.length-1;h>=0;h--)l=l.substring(0,p[h].start)+l.substring(p[h].end)}for(let d of o)l=l.replace(d,"");return{templateContent:l,serverScripts:s,clientScripts:o,signalsScripts:i}}function wh(e,t){return`<!DOCTYPE html>
4461
4461
  <html lang="en">
4462
4462
  <head>
4463
4463
  <meta charset="UTF-8">
@@ -4467,15 +4467,15 @@ File changed: ${o}, rebuilding...`);let s=await zm(e);t?.(s)}});return{close:()=
4467
4467
  <body>
4468
4468
  ${e}
4469
4469
  </body>
4470
- </html>`}function Uo(e,t,r){if(e&&typeof e==="object")e[t]=r}async function oS(e,t={}){let r=qc(e),n=Bun.file(r);if(!await n.exists())throw Error(`Template file not found: ${r}`);let o=await n.text(),s=null;if(Bo(r)){let i=await zo(o,{renderer:t.markdownRenderer});o=i.html,s=i.frontmatter}if(s)t={...t,context:{...s,...t.context||{}}};if(t.layout){let i=qc(t.layout),a=Bun.file(i);if(!await a.exists())throw Error(`Layout template not found: ${i}`);let{layout:c,injectCSS:l,...d}=t,u=await on(o,r,{...d,injectCSS:!1}),p=await a.text(),h={...t.context||{},content:u},f={...d,context:h,injectCSS:l};return on(p,i,f)}return on(o,r,t)}async function sS(e,t={},r={}){return on(e,process.cwd(),{context:t,...r})}async function on(e,t,r={}){let{templateContent:n,serverScripts:o,clientScripts:s}=xh(e),i={...Dt,...r.options},a={__filename:t,__dirname:yh(t),__stx:{},__stx_options:i,__stx_sfc_mode:!0,__stx_inject_css:r.injectCSS===!0,__stxServeContext:void 0,setResponseStatus:(d)=>{if(Number.isInteger(d)&&d>=100&&d<=599)Uo(r.context,"__stxResponseStatus",d)},notFound:(d=404)=>{let u=Number.isInteger(d)&&d>=400&&d<=599?d:404;Uo(r.context,"__stxResponseStatus",u)},setResponseHeader:(d,u)=>{if(!d)return;let p=r.context?.__stxResponseHeaders||{};p[String(d)]=String(u),Uo(r.context,"__stxResponseHeaders",p)},definePageMeta:()=>{},...r.context||{}};for(let d of o)await te(d,a,t);let c=new Set,l=n;if(l=await se(l,a,t,i,c),r.templateOnly){if(l=l.replace(/<script data-stx-scoped>[\s\S]*?<\/script>\s*/gi,""),l=l.replace(/<!-- stx SEO Tags -->[\s\S]*?(?=<)/i,""),s.length>0)l+=`
4470
+ </html>`}function Ho(e,t,r){if(e&&typeof e==="object")e[t]=r}async function sS(e,t={}){let r=Xc(e),n=Bun.file(r);if(!await n.exists())throw Error(`Template file not found: ${r}`);let o=await n.text(),s=null;if(zo(r)){let i=await Uo(o,{renderer:t.markdownRenderer});o=i.html,s=i.frontmatter}if(s)t={...t,context:{...s,...t.context||{}}};if(t.layout){let i=Xc(t.layout),a=Bun.file(i);if(!await a.exists())throw Error(`Layout template not found: ${i}`);let{layout:c,injectCSS:l,...d}=t,u=await sn(o,r,{...d,injectCSS:!1}),p=await a.text(),h={...t.context||{},content:u},f={...d,context:h,injectCSS:l};return sn(p,i,f)}return sn(o,r,t)}async function iS(e,t={},r={}){return sn(e,process.cwd(),{context:t,...r})}async function sn(e,t,r={}){let{templateContent:n,serverScripts:o,clientScripts:s}=bh(e),i={...Pt,...r.options},a={__filename:t,__dirname:xh(t),__stx:{},__stx_options:i,__stx_sfc_mode:!0,__stx_inject_css:r.injectCSS===!0,__stxServeContext:void 0,setResponseStatus:(d)=>{if(Number.isInteger(d)&&d>=100&&d<=599)Ho(r.context,"__stxResponseStatus",d)},notFound:(d=404)=>{let u=Number.isInteger(d)&&d>=400&&d<=599?d:404;Ho(r.context,"__stxResponseStatus",u)},setResponseHeader:(d,u)=>{if(!d)return;let p=r.context?.__stxResponseHeaders||{};p[String(d)]=String(u),Ho(r.context,"__stxResponseHeaders",p)},definePageMeta:()=>{},...r.context||{}};for(let d of o)await re(d,a,t);let c=new Set,l=n;if(l=await ie(l,a,t,i,c),r.templateOnly){if(l=l.replace(/<script data-stx-scoped>[\s\S]*?<\/script>\s*/gi,""),l=l.replace(/<!-- stx SEO Tags -->[\s\S]*?(?=<)/i,""),s.length>0)l+=`
4471
4471
  ${s.join(`
4472
- `)}`}else{if(r.processClientScripts!==!1&&s.length>0){let d=a.__stx_event_bindings||[],u=Xc(a),p=(await Promise.all(s.map(async(h)=>{let f=h.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!f)return h;return await sn(f[1],{eventBindings:d,templateContent:l,serverData:u,filePath:t})}))).join(`
4472
+ `)}`}else{if(r.processClientScripts!==!1&&s.length>0){let d=a.__stx_event_bindings||[],u=Jc(a),p=(await Promise.all(s.map(async(h)=>{let f=h.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!f)return h;return await an(f[1],{eventBindings:d,templateContent:l,serverData:u,filePath:t})}))).join(`
4473
4473
  `);if(l.match(/(<\/body>)/i))l=l.replace(/(<\/body>)/i,`${p}
4474
4474
  $1`);else l+=`
4475
- ${p}`}l=await Fr(l)}if(r.wrapInDocument){if(!l.trim().toLowerCase().startsWith("<!doctype")&&!l.trim().toLowerCase().startsWith("<html"))l=bh(l,r.title)}if(r.injectCSS)try{let{injectCrosswindCSS:d}=await import("./chunk-fjf53b44.js");l=await d(l)}catch{}return l}import ir from"fs";import an from"path";var Jc="layout-types.d.ts";function Yc(e){let t=[],r=(n,o)=>{let s;try{s=ir.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){if(i.name.startsWith("."))continue;let a=an.join(n,i.name);if(i.isDirectory())r(a,o?`${o}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".stx")&&i.name!=="_layout.stx"){let c=i.name.slice(0,-4);t.push(o?`${o}/${c}`:c)}}};return r(e,""),t.sort()}function Kc(e){let t=["// Auto-generated by stx \u2014 do not edit.","//","// Makes `definePageMeta({ layout })` reject a name with no layout behind it.","// Include this file in your tsconfig (it lives in the stx state directory,","// `.stx/` by default) for the check to apply.",""];if(e.length===0)return t.push("// No layouts found \u2014 `layout` stays typed as `string`.","export {}",""),t.join(`
4475
+ ${p}`}l=await Nr(l)}if(r.wrapInDocument){if(!l.trim().toLowerCase().startsWith("<!doctype")&&!l.trim().toLowerCase().startsWith("<html"))l=wh(l,r.title)}if(r.injectCSS)try{let{injectCrosswindCSS:d}=await import("./chunk-fqhckdt8.js");l=await d(l)}catch{}return l}import ar from"fs";import cn from"path";var Yc="layout-types.d.ts";function Kc(e){let t=[],r=(n,o)=>{let s;try{s=ar.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){if(i.name.startsWith("."))continue;let a=cn.join(n,i.name);if(i.isDirectory())r(a,o?`${o}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".stx")&&i.name!=="_layout.stx"){let c=i.name.slice(0,-4);t.push(o?`${o}/${c}`:c)}}};return r(e,""),t.sort()}function Gc(e){let t=["// Auto-generated by stx \u2014 do not edit.","//","// Makes `definePageMeta({ layout })` reject a name with no layout behind it.","// Include this file in your tsconfig (it lives in the stx state directory,","// `.stx/` by default) for the check to apply.",""];if(e.length===0)return t.push("// No layouts found \u2014 `layout` stays typed as `string`.","export {}",""),t.join(`
4476
4476
  `);return t.push("declare module '@stacksjs/stx' {"," interface KnownLayouts {",...e.map((r)=>` '${r}': true`)," }","}","","export {}",""),t.join(`
4477
- `)}function wh(e,t){if(!e)return[];let r=an.isAbsolute(e)?e:an.resolve(process.cwd(),e),n=Yc(r),o=Kc(n),s=an.join(t,Jc);try{if(ir.existsSync(s)&&ir.readFileSync(s,"utf8")===o)return n;ir.mkdirSync(t,{recursive:!0}),ir.writeFileSync(s,o)}catch{}return n}function vh(e,...t){let r=t[0]??{},n=new Set,o=String(e).replace(/(\/)?:([^/?*]+)([?*])?/g,(a,c,l,d)=>{let u=r[l];if(n.add(l),u===void 0||u===null||u===""){if(d==="?")return"";return a}let p=Array.isArray(u)?u.map((h)=>encodeURIComponent(String(h))).join("/"):d==="*"?String(u).split("/").map((h)=>encodeURIComponent(h)).join("/"):encodeURIComponent(String(u));return`${c??""}${p}`}),s=Object.keys(r).filter((a)=>!n.has(a));if(s.length===0)return o;let i=new URLSearchParams;for(let a of s){let c=r[a];if(Array.isArray(c))c.forEach((l)=>i.append(a,String(l)));else if(c!==void 0&&c!==null)i.set(a,String(c))}return`${o}?${i.toString()}`}import Lt from"fs";import et from"path";function Gc(e){try{return Lt.statSync(e).mtimeMs}catch{return null}}function cn(e,t){let r=Math.max(0,Math.round((t-e)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function $h(e,t){try{return globalThis.Bun?.resolveSync(e,t)??null}catch{return null}}function Zc(e,t="stx"){let r=et.resolve(e);for(let n=0;n<10;n++){let o=et.join(r,"pantry","@stacksjs",t);if(Lt.existsSync(o))return o;let s=et.dirname(r);if(s===r)break;r=s}return null}async function Sh(e={}){let t=e.cwd?et.resolve(e.cwd):process.cwd(),r=e.resolve??$h,n=Date.now(),o=[],s=r("@stacksjs/stx",t);o.push(s?{name:"@stacksjs/stx resolves to",status:"ok",detail:s}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let i=r("bun-plugin-stx",t);if(i)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:i});let a=Zc(t,"stx");if(!a)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let c=et.join(a,"src/signals.ts"),l=[et.join(a,"dist/index.js"),et.join(a,"dist/signals.js")].find((f)=>Lt.existsSync(f))||null,d=Gc(c),u=l?Gc(l):null;if(d==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${a} but no src/signals.ts to compare`});else if(u==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${a} && bun build.ts`});else if(u<d){let f=Math.round((d-u)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${cn(u,n)}) is OLDER than src/signals.ts (${cn(d,n)}) by ${f}s \u2014 your edit isn't built`,fix:`cd ${a} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${cn(d,n)}, dist ${cn(u,n)})`});let p=et.join(t,"node_modules/@stacksjs/stx"),h=null;try{h=Lt.lstatSync(p)}catch{h=null}if(!h)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(h.isSymbolicLink()){let f=null;try{f=Lt.realpathSync(p)}catch{}let g=(()=>{try{return Lt.realpathSync(a)}catch{return a}})();o.push(f===g?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${f||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),e.generateRuntime)try{let c=e.generateRuntime().length;o.push(c>1000?{name:"signals runtime",status:"ok",detail:`generated ${c.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${c} chars \u2014 suspiciously short`})}catch(c){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${c.message}`})}return{checks:o,ok:!o.some((c)=>c.status==="error")}}function kh(e){let t={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let n of e.checks)if(r.push(` ${t[n.status]} ${n.name}: ${n.detail}`),n.fix)r.push(` \u2192 ${n.fix}`);return r.push(""),r.push(e.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
4478
- `)}var{Glob:zh}=globalThis.Bun;import{cpSync as al,existsSync as bn,mkdirSync as cl,readFileSync as ll,readdirSync as Uh,rmSync as Hh,statSync as Wh,unlinkSync as Vh,writeFileSync as yn}from"fs";import{dirname as qh,join as Pe,relative as Xh}from"path";import dl from"process";import tt from"path";function Qc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function el(e,t,r){let n=Qc(t),o=r?Qc(r):"";return`<!DOCTYPE html>
4477
+ `)}function vh(e,t){if(!e)return[];let r=cn.isAbsolute(e)?e:cn.resolve(process.cwd(),e),n=Kc(r),o=Gc(n),s=cn.join(t,Yc);try{if(ar.existsSync(s)&&ar.readFileSync(s,"utf8")===o)return n;ar.mkdirSync(t,{recursive:!0}),ar.writeFileSync(s,o)}catch{}return n}function $h(e,...t){let r=t[0]??{},n=new Set,o=String(e).replace(/(\/)?:([^/?*]+)([?*])?/g,(a,c,l,d)=>{let u=r[l];if(n.add(l),u===void 0||u===null||u===""){if(d==="?")return"";return a}let p=Array.isArray(u)?u.map((h)=>encodeURIComponent(String(h))).join("/"):d==="*"?String(u).split("/").map((h)=>encodeURIComponent(h)).join("/"):encodeURIComponent(String(u));return`${c??""}${p}`}),s=Object.keys(r).filter((a)=>!n.has(a));if(s.length===0)return o;let i=new URLSearchParams;for(let a of s){let c=r[a];if(Array.isArray(c))c.forEach((l)=>i.append(a,String(l)));else if(c!==void 0&&c!==null)i.set(a,String(c))}return`${o}?${i.toString()}`}import Ft from"fs";import tt from"path";function Zc(e){try{return Ft.statSync(e).mtimeMs}catch{return null}}function ln(e,t){let r=Math.max(0,Math.round((t-e)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function Sh(e,t){try{return globalThis.Bun?.resolveSync(e,t)??null}catch{return null}}function Qc(e,t="stx"){let r=tt.resolve(e);for(let n=0;n<10;n++){let o=tt.join(r,"pantry","@stacksjs",t);if(Ft.existsSync(o))return o;let s=tt.dirname(r);if(s===r)break;r=s}return null}async function kh(e={}){let t=e.cwd?tt.resolve(e.cwd):process.cwd(),r=e.resolve??Sh,n=Date.now(),o=[],s=r("@stacksjs/stx",t);o.push(s?{name:"@stacksjs/stx resolves to",status:"ok",detail:s}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let i=r("bun-plugin-stx",t);if(i)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:i});let a=Qc(t,"stx");if(!a)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let c=tt.join(a,"src/signals.ts"),l=[tt.join(a,"dist/index.js"),tt.join(a,"dist/signals.js")].find((f)=>Ft.existsSync(f))||null,d=Zc(c),u=l?Zc(l):null;if(d==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${a} but no src/signals.ts to compare`});else if(u==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${a} && bun build.ts`});else if(u<d){let f=Math.round((d-u)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${ln(u,n)}) is OLDER than src/signals.ts (${ln(d,n)}) by ${f}s \u2014 your edit isn't built`,fix:`cd ${a} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${ln(d,n)}, dist ${ln(u,n)})`});let p=tt.join(t,"node_modules/@stacksjs/stx"),h=null;try{h=Ft.lstatSync(p)}catch{h=null}if(!h)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(h.isSymbolicLink()){let f=null;try{f=Ft.realpathSync(p)}catch{}let g=(()=>{try{return Ft.realpathSync(a)}catch{return a}})();o.push(f===g?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${f||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),e.generateRuntime)try{let c=e.generateRuntime().length;o.push(c>1000?{name:"signals runtime",status:"ok",detail:`generated ${c.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${c} chars \u2014 suspiciously short`})}catch(c){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${c.message}`})}return{checks:o,ok:!o.some((c)=>c.status==="error")}}function Th(e){let t={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let n of e.checks)if(r.push(` ${t[n.status]} ${n.name}: ${n.detail}`),n.fix)r.push(` \u2192 ${n.fix}`);return r.push(""),r.push(e.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
4478
+ `)}var{Glob:Uh}=globalThis.Bun;import{cpSync as cl,existsSync as wn,mkdirSync as ll,readFileSync as dl,readdirSync as Hh,rmSync as Wh,statSync as Vh,unlinkSync as qh,writeFileSync as xn}from"fs";import{dirname as Xh,join as Oe,relative as Jh}from"path";import ul from"process";import rt from"path";function el(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function tl(e,t,r){let n=el(t),o=r?el(r):"";return`<!DOCTYPE html>
4479
4479
  <html>
4480
4480
  <head>
4481
4481
  <title>stx Error</title>
@@ -4491,50 +4491,50 @@ ${p}`}l=await Fr(l)}if(r.wrapInDocument){if(!l.trim().toLowerCase().startsWith("
4491
4491
  ${o?`<div class="file-path">File: ${o}</div>`:""}
4492
4492
  <pre>${n}</pre>
4493
4493
  </body>
4494
- </html>`}function rl(e){return{name:"bun-plugin-stx",async setup(t){let r={...Dt,...e},n=new Set;if(!t.config.root&&t.config.entrypoints?.length){let a=t.config.entrypoints.map((c)=>tt.dirname(tt.resolve(c))).reduce((c,l)=>{let d=c.split(tt.sep),u=l.split(tt.sep),p=0;while(p<d.length&&p<u.length&&d[p]===u[p])p++;return d.slice(0,p).join(tt.sep)});t.config.root=a}let o=r.webComponents?.enabled?`./${tt.relative(tt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",s=[];if(r.webComponents?.enabled)try{let i=await Or(r,n);if(s.push(...i),r.debug&&i.length>0)console.log(`Successfully built ${i.length} web components`)}catch(i){console.error("Failed to build web components:",i)}t.onResolve({filter:/^\//},(i)=>{if(i.path.startsWith("//"))return null;if(!i.importer)return null;return{external:!0,path:i.path}}),t.onLoad({filter:/\.md$/},async(i)=>{let a=i.path;try{let{content:c,data:l}=await $e(a,r);return{contents:`// ${a}
4494
+ </html>`}function nl(e){return{name:"bun-plugin-stx",async setup(t){let r={...Pt,...e},n=new Set;if(!t.config.root&&t.config.entrypoints?.length){let a=t.config.entrypoints.map((c)=>rt.dirname(rt.resolve(c))).reduce((c,l)=>{let d=c.split(rt.sep),u=l.split(rt.sep),p=0;while(p<d.length&&p<u.length&&d[p]===u[p])p++;return d.slice(0,p).join(rt.sep)});t.config.root=a}let o=r.webComponents?.enabled?`./${rt.relative(rt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",s=[];if(r.webComponents?.enabled)try{let i=await Ir(r,n);if(s.push(...i),r.debug&&i.length>0)console.log(`Successfully built ${i.length} web components`)}catch(i){console.error("Failed to build web components:",i)}t.onResolve({filter:/^\//},(i)=>{if(i.path.startsWith("//"))return null;if(!i.importer)return null;return{external:!0,path:i.path}}),t.onLoad({filter:/\.md$/},async(i)=>{let a=i.path;try{let{content:c,data:l}=await Se(a,r);return{contents:`// ${a}
4495
4495
  const content = ${JSON.stringify(c)};
4496
4496
  const data = ${JSON.stringify(l)};
4497
4497
 
4498
4498
  export { content, data };
4499
4499
  export { content as default };
4500
- `,loader:"js"}}catch(c){console.error("Markdown Processing Error:",c);let l=el("Markdown Processing Error",c.message||"Unknown error",a);return{contents:`// ${a}
4500
+ `,loader:"js"}}catch(c){console.error("Markdown Processing Error:",c);let l=tl("Markdown Processing Error",c.message||"Unknown error",a);return{contents:`// ${a}
4501
4501
  const content = ${JSON.stringify(l)};
4502
4502
  const data = {};
4503
4503
 
4504
4504
  export { content, data };
4505
4505
  export { content as default };
4506
- `,loader:"js"}}}),t.onLoad({filter:/\.(jsx|tsx)$/},async(i)=>{let a=i.path;try{let c=await Bun.file(a).text(),l=a.endsWith(".tsx")?"tsx":"jsx";return{contents:new Bun.Transpiler({loader:l,jsxOptimizationInline:!0}).transformSync(c),loader:"js"}}catch(c){return console.error("JSX Processing Error:",c),{contents:"export default function() { return null; }",loader:"js"}}}),t.onLoad({filter:/\.stx$/},async({path:i})=>{try{let a=new Set;if(r.cache&&r.cachePath){let y=await Ir(i,r);if(y){if(r.debug)console.log(`Using cached version of ${i}`);return{contents:y,loader:"html"}}}let c=await Bun.file(i).text(),l=c,d=c.match(/<template\b[^>]*>([\s\S]*?)<\/template>/i);if(d)l=d[1].trim();let u=tl(c),p=u.client.map((y)=>y.fullTag),h=u.server.map((y)=>y.content),f=l;for(let y of h){let b=y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");f=f.replace(new RegExp(`<script\\b[^>]*>${b}<\\/script>`,"gi"),"")}for(let y of p){let b=y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");f=f.replace(b,"")}let g={__filename:i,__dirname:tt.dirname(i),__stx:{webComponentsPath:o,builtComponents:s},__stx_options:r,__stx_sfc_mode:!0};for(let y of h)await te(y,g,i);let x=f;if(x=await se(x,g,i,r,a),p.length>0){let y=g.__stx_event_bindings||[],w=(await Promise.all(p.map(async(S)=>{let T=S.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!T)return S;return sn(T[1],{eventBindings:y,templateContent:x})}))).join(`
4506
+ `,loader:"js"}}}),t.onLoad({filter:/\.(jsx|tsx)$/},async(i)=>{let a=i.path;try{let c=await Bun.file(a).text(),l=a.endsWith(".tsx")?"tsx":"jsx";return{contents:new Bun.Transpiler({loader:l,jsxOptimizationInline:!0}).transformSync(c),loader:"js"}}catch(c){return console.error("JSX Processing Error:",c),{contents:"export default function() { return null; }",loader:"js"}}}),t.onLoad({filter:/\.stx$/},async({path:i})=>{try{let a=new Set;if(r.cache&&r.cachePath){let y=await Lr(i,r);if(y){if(r.debug)console.log(`Using cached version of ${i}`);return{contents:y,loader:"html"}}}let c=await Bun.file(i).text(),l=c,d=c.match(/<template\b[^>]*>([\s\S]*?)<\/template>/i);if(d)l=d[1].trim();let u=rl(c),p=u.client.map((y)=>y.fullTag),h=u.server.map((y)=>y.content),f=l;for(let y of h){let b=y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");f=f.replace(new RegExp(`<script\\b[^>]*>${b}<\\/script>`,"gi"),"")}for(let y of p){let b=y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");f=f.replace(b,"")}let g={__filename:i,__dirname:rt.dirname(i),__stx:{webComponentsPath:o,builtComponents:s},__stx_options:r,__stx_sfc_mode:!0};for(let y of h)await re(y,g,i);let x=f;if(x=await ie(x,g,i,r,a),p.length>0){let y=g.__stx_event_bindings||[],w=(await Promise.all(p.map(async(k)=>{let C=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!C)return k;return an(C[1],{eventBindings:y,templateContent:x})}))).join(`
4507
4507
  `);if(x.match(/(<\/body>)/i))x=x.replace(/(<\/body>)/i,`${w}
4508
4508
  $1`);else x+=`
4509
- ${w}`;g.__stx_event_bindings=[]}if(a.forEach((y)=>n.add(y)),r.cache&&r.cachePath){if(await Lr(i,x,a,r),r.debug)console.log(`Cached template ${i} with ${a.size} dependencies`)}return{contents:x,loader:"html"}}catch(a){return console.error("stx Plugin Error:",a),{contents:el("stx Rendering Error",a.message||String(a),i),loader:"html"}}})}}}var Ho=rl;function ln(e,t,r={},n="/"){let o=t.seo??{},s=r.title??o.title??t.name,i=r.description??o.description??t.description??"",a=r.image??o.image,c=`${t.url.replace(/\/$/,"")}${n}`,l=o.siteName??t.name,d=o.type??"website",u=o.locale??"en_US",p=[];if(o.favicon){let k=o.favicon.toLowerCase().split(".").pop(),L=k==="svg"?"image/svg+xml":k==="ico"?"image/x-icon":k==="png"?"image/png":k==="jpg"||k==="jpeg"?"image/jpeg":"";p.push(`<link rel="icon"${L?` type="${L}"`:""} href="${ae(o.favicon)}">`)}if(p.push(`<title>${Th(s)}</title>`,`<link rel="canonical" href="${ae(c)}">`,`<meta name="description" content="${ae(i)}">`,`<meta property="og:title" content="${ae(s)}">`,`<meta property="og:description" content="${ae(i)}">`,`<meta property="og:type" content="${ae(d)}">`,`<meta property="og:url" content="${ae(c)}">`,`<meta property="og:site_name" content="${ae(l)}">`,`<meta property="og:locale" content="${ae(u)}">`,`<meta name="twitter:card" content="${a?"summary_large_image":"summary"}">`,`<meta name="twitter:title" content="${ae(s)}">`,`<meta name="twitter:description" content="${ae(i)}">`),a)p.push(`<meta property="og:image" content="${ae(a)}">`),p.push(`<meta name="twitter:image" content="${ae(a)}">`);if(o.twitter)p.push(`<meta name="twitter:site" content="@${ae(o.twitter.replace(/^@/,""))}">`),p.push(`<meta name="twitter:creator" content="@${ae(o.twitter.replace(/^@/,""))}">`);let h=/<!--\s*stx SEO Tags\s*-->[\s\S]*?<meta\s+name="twitter:description"[^>]*>\s*/i;if(h.test(e))e=e.replace(h,"");e=e.replace(/<!--\s*SEO\s*-->[\s\S]*?<!--\s*\/SEO\s*-->\s*/g,""),e=e.replace(/<meta\s+name="title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+property="og:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+property="og:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"");let f=e.search(/<\/head>/i),g=f===-1?e:e.slice(0,f),x=/^(?:stx App|stx Project|Document|Untitled)$/i,y=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(g)?.[1]?.trim(),b=y===void 0||y===""||x.test(y),w=(k)=>{if(/^<title[\s>]/i.test(k))return/<title[\s>]/i.test(g)&&!b;if(/rel="canonical"/i.test(k))return/<link[^>]+rel=["']canonical["']/i.test(g);let L=/(?:property|name)="([^"]+)"/i.exec(k)?.[1];if(!L)return!1;return new RegExp(`<meta[^>]+(?:property|name)=["']${L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["']`,"i").test(g)},v=p.filter((k)=>!w(k));if(v.length===0)return e;let S=e,T=v.find((k)=>/^<title[\s>]/i.test(k));if(T&&b&&/<title[^>]*>[\s\S]*?<\/title>/i.test(S)){if(S=S.replace(/<title[^>]*>[\s\S]*?<\/title>/i,()=>T),v=v.filter((k)=>k!==T),v.length===0)return S}let C=`<!-- SEO -->
4509
+ ${w}`;g.__stx_event_bindings=[]}if(a.forEach((y)=>n.add(y)),r.cache&&r.cachePath){if(await Fr(i,x,a,r),r.debug)console.log(`Cached template ${i} with ${a.size} dependencies`)}return{contents:x,loader:"html"}}catch(a){return console.error("stx Plugin Error:",a),{contents:tl("stx Rendering Error",a.message||String(a),i),loader:"html"}}})}}}var Wo=nl;function dn(e,t,r={},n="/"){let o=t.seo??{},s=r.title??o.title??t.name,i=r.description??o.description??t.description??"",a=r.image??o.image,c=`${t.url.replace(/\/$/,"")}${n}`,l=o.siteName??t.name,d=o.type??"website",u=o.locale??"en_US",p=[];if(o.favicon){let T=o.favicon.toLowerCase().split(".").pop(),F=T==="svg"?"image/svg+xml":T==="ico"?"image/x-icon":T==="png"?"image/png":T==="jpg"||T==="jpeg"?"image/jpeg":"";p.push(`<link rel="icon"${F?` type="${F}"`:""} href="${ce(o.favicon)}">`)}if(p.push(`<title>${Ch(s)}</title>`,`<link rel="canonical" href="${ce(c)}">`,`<meta name="description" content="${ce(i)}">`,`<meta property="og:title" content="${ce(s)}">`,`<meta property="og:description" content="${ce(i)}">`,`<meta property="og:type" content="${ce(d)}">`,`<meta property="og:url" content="${ce(c)}">`,`<meta property="og:site_name" content="${ce(l)}">`,`<meta property="og:locale" content="${ce(u)}">`,`<meta name="twitter:card" content="${a?"summary_large_image":"summary"}">`,`<meta name="twitter:title" content="${ce(s)}">`,`<meta name="twitter:description" content="${ce(i)}">`),a)p.push(`<meta property="og:image" content="${ce(a)}">`),p.push(`<meta name="twitter:image" content="${ce(a)}">`);if(o.twitter)p.push(`<meta name="twitter:site" content="@${ce(o.twitter.replace(/^@/,""))}">`),p.push(`<meta name="twitter:creator" content="@${ce(o.twitter.replace(/^@/,""))}">`);let h=/<!--\s*stx SEO Tags\s*-->[\s\S]*?<meta\s+name="twitter:description"[^>]*>\s*/i;if(h.test(e))e=e.replace(h,"");e=e.replace(/<!--\s*SEO\s*-->[\s\S]*?<!--\s*\/SEO\s*-->\s*/g,""),e=e.replace(/<meta\s+name="title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+property="og:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+property="og:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:title"\s+content="stx Project"[^>]*>\s*/g,"").replace(/<meta\s+name="twitter:description"\s+content="A website built with stx[^"]*"[^>]*>\s*/g,"");let f=e.search(/<\/head>/i),g=f===-1?e:e.slice(0,f),x=/^(?:stx App|stx Project|Document|Untitled)$/i,y=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(g)?.[1]?.trim(),b=y===void 0||y===""||x.test(y),w=(T)=>{if(/^<title[\s>]/i.test(T))return/<title[\s>]/i.test(g)&&!b;if(/rel="canonical"/i.test(T))return/<link[^>]+rel=["']canonical["']/i.test(g);let F=/(?:property|name)="([^"]+)"/i.exec(T)?.[1];if(!F)return!1;return new RegExp(`<meta[^>]+(?:property|name)=["']${F.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}["']`,"i").test(g)},v=p.filter((T)=>!w(T));if(v.length===0)return e;let k=e,C=v.find((T)=>/^<title[\s>]/i.test(T));if(C&&b&&/<title[^>]*>[\s\S]*?<\/title>/i.test(k)){if(k=k.replace(/<title[^>]*>[\s\S]*?<\/title>/i,()=>C),v=v.filter((T)=>T!==C),v.length===0)return k}let E=`<!-- SEO -->
4510
4510
  ${v.join(`
4511
4511
  `)}
4512
- <!-- /SEO -->`,j=S.search(/<\/head>/i);if(j!==-1)return`${S.slice(0,j)}${C}
4513
- ${S.slice(j)}`;if(/<head[^>]*>/i.test(S))return S.replace(/<head([^>]*)>/i,`<head$1>
4514
- ${C}`);return`${C}
4515
- ${S}`}function ae(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Th(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function dn(e,t){let r=e.url.replace(/\/$/,""),n=new Date().toISOString().slice(0,10);return['<?xml version="1.0" encoding="UTF-8"?>','<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',t.filter((o)=>o.page?.sitemap!==!1).map((o)=>{let s=`${r}${o.path}`,i=o.page?.priority??(o.path==="/"?1:0.8),a=o.page?.changefreq??"monthly";return[" <url>",` <loc>${Ch(s)}</loc>`,` <lastmod>${n}</lastmod>`,` <changefreq>${a}</changefreq>`,` <priority>${i.toFixed(1)}</priority>`," </url>"].join(`
4512
+ <!-- /SEO -->`,R=k.search(/<\/head>/i);if(R!==-1)return`${k.slice(0,R)}${E}
4513
+ ${k.slice(R)}`;if(/<head[^>]*>/i.test(k))return k.replace(/<head([^>]*)>/i,`<head$1>
4514
+ ${E}`);return`${E}
4515
+ ${k}`}function ce(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ch(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function un(e,t){let r=e.url.replace(/\/$/,""),n=new Date().toISOString().slice(0,10);return['<?xml version="1.0" encoding="UTF-8"?>','<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',t.filter((o)=>o.page?.sitemap!==!1).map((o)=>{let s=`${r}${o.path}`,i=o.page?.priority??(o.path==="/"?1:0.8),a=o.page?.changefreq??"monthly";return[" <url>",` <loc>${Eh(s)}</loc>`,` <lastmod>${n}</lastmod>`,` <changefreq>${a}</changefreq>`,` <priority>${i.toFixed(1)}</priority>`," </url>"].join(`
4516
4516
  `)}).join(`
4517
4517
  `),"</urlset>",""].join(`
4518
- `)}function Ch(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function un(e){let t=e.robots??"allow";if(t===!1)return null;if(typeof t==="string"&&t!=="allow"&&t!=="disallow")return t.endsWith(`
4518
+ `)}function Eh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function pn(e){let t=e.robots??"allow";if(t===!1)return null;if(typeof t==="string"&&t!=="allow"&&t!=="disallow")return t.endsWith(`
4519
4519
  `)?t:`${t}
4520
4520
  `;let r=e.sitemap!==!1?`Sitemap: ${e.url.replace(/\/$/,"")}/sitemap.xml
4521
4521
  `:"";if(t==="disallow")return["User-agent: *","Disallow: /","",r].filter(Boolean).join(`
4522
4522
  `);return["User-agent: *","Allow: /","",r].filter(Boolean).join(`
4523
- `)}var Ft=null;async function Eh(){if(Ft!==null)return Ft;try{let e=await import("./chunk-4x3b4b4q.js");if(typeof e.getRouterScript==="function")Ft=e.getRouterScript();else Ft=""}catch{Ft=""}return Ft}async function Wo(e,t){let r=await Eh();if(!r)return e;let n={interceptAllLinks:!0,container:"main",...t},o=`${`<script>window.__stxRouterConfig=${JSON.stringify(n)};</script>
4523
+ `)}var Nt=null;async function _h(){if(Nt!==null)return Nt;try{let e=await import("./chunk-q5dv1kyy.js");if(typeof e.getRouterScript==="function")Nt=e.getRouterScript();else Nt=""}catch{Nt=""}return Nt}async function Vo(e,t){let r=await _h();if(!r)return e;let n={interceptAllLinks:!0,container:"main",...t},o=`${`<script>window.__stxRouterConfig=${JSON.stringify(n)};</script>
4524
4524
  `}<script>${r}</script>`;if(/<\/body>/i.test(e))return e.replace(/<\/body>/i,`${o}
4525
4525
  </body>`);return`${e}
4526
- ${o}`}var _h=`window.__stxThemeIcon=function(isDark){try{var want=isDark?'dark':'light';var pick=document.querySelector('link[rel~="icon"][media*="prefers-color-scheme: '+want+'"]');if(!pick)return;var live=document.querySelector('link[rel~="icon"]:not([media])');if(!live){live=document.createElement('link');live.setAttribute('rel','icon');document.head.appendChild(live)}if(pick.type)live.setAttribute('type',pick.type);var href=pick.getAttribute('href');if(live.getAttribute('href')!==href)live.setAttribute('href',href)}catch(e){}};`,Ah=(e,t,r,n)=>`(function(){${_h}function read(){try{var k=${JSON.stringify(t)};var t=localStorage.getItem(k);return t===null?(${JSON.stringify(e)}==='dark'||(${JSON.stringify(e)}==='auto'&&window.matchMedia('(prefers-color-scheme: dark)').matches)):t==='dark'}catch(e){return ${JSON.stringify(e)}==='dark'}}function apply(){var isDark=read();var html=document.documentElement;html.classList[isDark?'add':'remove']('dark');var color=isDark?${JSON.stringify(n)}:${JSON.stringify(r)};if(!document.head)return;var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(!tc){tc=document.createElement('meta');tc.setAttribute('name','theme-color');tc.setAttribute('data-stx-theme-meta','1')}tc.setAttribute('content',color);if(tc!==document.head.firstChild){document.head.insertBefore(tc,document.head.firstChild)}if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)}apply();window.addEventListener('stx:navigate',apply);window.addEventListener('popstate',apply)})();`,jh=(e,t,r)=>`document.addEventListener('click',function(e){var t=e.target&&e.target.closest&&e.target.closest('#theme-toggle');if(!t)return;var html=document.documentElement;var isDark=html.classList.toggle('dark');try{localStorage.setItem(${JSON.stringify(e)},isDark?'dark':'light')}catch(e){}var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(tc)tc.setAttribute('content',isDark?${JSON.stringify(r)}:${JSON.stringify(t)});if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)});`;function pn(e,t){if(t.theme===!1)return e;let r=e.includes(nl),n=typeof t.theme==="object"&&t.theme!==null?t.theme:{},o=n.default??"dark",s=n.storageKey??"theme",i=n.colors?.light??"#ffffff",a=n.colors?.dark??"#000000";if(o==="dark"&&!r){if(!/<html\b[^>]*\bclass=/.test(e))e=e.replace(/<html\b([^>]*)>/i,'<html$1 class="dark">');else if(!/<html\b[^>]*\bclass="[^"]*\bdark\b/.test(e))e=e.replace(/<html\b([^>]*\bclass=")([^"]*)(")/i,"<html$1$2 dark$3")}if(!e.includes("data-stx-theme-meta")&&/<head\b[^>]*>/i.test(e)){let c=['<meta name="color-scheme" content="dark light" data-stx-theme-meta="1">',`<meta name="theme-color" media="(prefers-color-scheme: light)" content="${i}" data-stx-theme-meta="1">`,`<meta name="theme-color" media="(prefers-color-scheme: dark)" content="${a}" data-stx-theme-meta="1">`].join(`
4526
+ ${o}`}var Ah=`window.__stxThemeIcon=function(isDark){try{var want=isDark?'dark':'light';var pick=document.querySelector('link[rel~="icon"][media*="prefers-color-scheme: '+want+'"]');if(!pick)return;var live=document.querySelector('link[rel~="icon"]:not([media])');if(!live){live=document.createElement('link');live.setAttribute('rel','icon');document.head.appendChild(live)}if(pick.type)live.setAttribute('type',pick.type);var href=pick.getAttribute('href');if(live.getAttribute('href')!==href)live.setAttribute('href',href)}catch(e){}};`,jh=(e,t,r,n)=>`(function(){${Ah}function read(){try{var k=${JSON.stringify(t)};var t=localStorage.getItem(k);return t===null?(${JSON.stringify(e)}==='dark'||(${JSON.stringify(e)}==='auto'&&window.matchMedia('(prefers-color-scheme: dark)').matches)):t==='dark'}catch(e){return ${JSON.stringify(e)}==='dark'}}function apply(){var isDark=read();var html=document.documentElement;html.classList[isDark?'add':'remove']('dark');var color=isDark?${JSON.stringify(n)}:${JSON.stringify(r)};if(!document.head)return;var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(!tc){tc=document.createElement('meta');tc.setAttribute('name','theme-color');tc.setAttribute('data-stx-theme-meta','1')}tc.setAttribute('content',color);if(tc!==document.head.firstChild){document.head.insertBefore(tc,document.head.firstChild)}if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)}apply();window.addEventListener('stx:navigate',apply);window.addEventListener('popstate',apply)})();`,Rh=(e,t,r)=>`document.addEventListener('click',function(e){var t=e.target&&e.target.closest&&e.target.closest('#theme-toggle');if(!t)return;var html=document.documentElement;var isDark=html.classList.toggle('dark');try{localStorage.setItem(${JSON.stringify(e)},isDark?'dark':'light')}catch(e){}var tc=document.querySelector('meta[name="theme-color"]:not([media])');if(tc)tc.setAttribute('content',isDark?${JSON.stringify(r)}:${JSON.stringify(t)});if(window.__stxThemeIcon)window.__stxThemeIcon(isDark)});`;function fn(e,t){if(t.theme===!1)return e;let r=e.includes(ol),n=typeof t.theme==="object"&&t.theme!==null?t.theme:{},o=n.default??"dark",s=n.storageKey??"theme",i=n.colors?.light??"#ffffff",a=n.colors?.dark??"#000000";if(o==="dark"&&!r){if(!/<html\b[^>]*\bclass=/.test(e))e=e.replace(/<html\b([^>]*)>/i,'<html$1 class="dark">');else if(!/<html\b[^>]*\bclass="[^"]*\bdark\b/.test(e))e=e.replace(/<html\b([^>]*\bclass=")([^"]*)(")/i,"<html$1$2 dark$3")}if(!e.includes("data-stx-theme-meta")&&/<head\b[^>]*>/i.test(e)){let c=['<meta name="color-scheme" content="dark light" data-stx-theme-meta="1">',`<meta name="theme-color" media="(prefers-color-scheme: light)" content="${i}" data-stx-theme-meta="1">`,`<meta name="theme-color" media="(prefers-color-scheme: dark)" content="${a}" data-stx-theme-meta="1">`].join(`
4527
4527
  `);e=e.replace(/<head\b([^>]*)>/i,`<head$1>
4528
- ${c}`)}if(!r&&!e.includes("__stxThemeGuard")&&/<head\b[^>]*>/i.test(e)){let c=`<script data-stx-theme-guard="1">${`window.__STX_COLOR_MODE__=window.__STX_COLOR_MODE__||${JSON.stringify({storageKey:s,initialMode:o,darkClass:"dark"})};`}${Ah(o,s,i,a)};window.__stxThemeGuard=1;</script>`;e=e.replace(/<head\b([^>]*)>/i,`<head$1>
4529
- ${c}`)}if(!r&&!e.includes("__stxThemeToggle")&&/<\/body>/i.test(e)){let c=`<script data-stx-theme-toggle="1">${jh(s,i,a)};window.__stxThemeToggle=1;</script>`;e=e.replace(/<\/body>/i,`${c}
4530
- </body>`)}return e}async function ol(e,t){if(e.length===0)return{succeeded:[],failed:[]};try{return await t(e),{succeeded:[...e],failed:[]}}catch{}let r=[],n=[];for(let o of e)try{await t([o]),r.push(o)}catch(s){n.push({entrypoint:o,error:Ct(s,o)})}return{succeeded:r,failed:n}}import{existsSync as Rh,readFileSync as Mh}from"fs";import{join as Dh,resolve as Ph}from"path";import Oh from"process";function fn(e,t=Oh.cwd()){let r=e.i18n;if(!r||!Array.isArray(r.locales)||r.locales.length===0)return null;let n=r.defaultLocale??r.locales[0],o=Ih(r,t);return{locales:r.locales,defaultLocale:n,labels:r.labels??Object.fromEntries(r.locales.map((s)=>[s,s.toUpperCase()])),translations:o,pickerSelector:r.pickerSelector??"#lang-picker"}}function Ih(e,t){let r=e.translations??{},n={},o=e.translationsDir,s=o===!1?null:Ph(t,typeof o==="string"&&o?o:"translations"),i=e.format??"json";for(let a of e.locales){let c=s?Lh(s,a,i):{};n[a]={...c,...r[a]??{}}}return n}function Lh(e,t,r){let n=r==="json"?[`${t}.json`]:[`${t}.${r}`,`${t}.${r==="yaml"?"yml":"yaml"}`];for(let o of n){let s=Dh(e,o);if(!Rh(s))continue;try{let i=Mh(s,"utf8"),a=r==="json"?JSON.parse(i):Fh(i);return sl(a)}catch{continue}}return{}}function sl(e,t="",r={}){if(!e||typeof e!=="object")return r;for(let[n,o]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(o&&typeof o==="object"&&!Array.isArray(o))sl(o,s,r);else if(typeof o==="string")r[s]=o;else if(typeof o==="number"||typeof o==="boolean")r[s]=String(o)}return r}function Fh(e){let t={},r=[{obj:t,indent:-1}];for(let n of e.split(`
4531
- `)){let o=n.replace(/#.*$/,"").trimEnd();if(!o.trim())continue;let s=o.search(/\S/);if(s===-1)continue;while(r.length>1&&r[r.length-1].indent>=s)r.pop();let i=r[r.length-1].obj,a=o.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(!a)continue;let[,,c,l]=a,d=c.trim(),u=l.trim();if(u==="")i[d]={},r.push({obj:i[d],indent:s});else i[d]=Nh(u)}return t}function Nh(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function qo(e,t,r){let n=e.translations[t]?.[r];if(typeof n==="string")return n;let o=e.translations[e.defaultLocale]?.[r];if(typeof o==="string")return o;return r}function mn(e,t,r){return e.replace(/\{t(!?):([a-zA-Z][\w.-]*)\}/g,(n,o,s)=>{let i=qo(t,r,s);return o==="!"?i:Bh(i)})}function rt(e,t,r){if(t===r)return e;if(e==="/")return`/${t}/`;if(e==="/404.html")return`/${t}/404.html`;return`/${t}${e}`}function il(e,t){for(let r of t){if(e===`/${r}`||e===`/${r}/`)return{locale:r,path:"/"};if(e.startsWith(`/${r}/`))return{locale:r,path:e.slice(r.length+1)}}return{locale:null,path:e}}function hn(e,t,r){let n=e.replace(/\/$/,""),o=[];for(let i of r.locales){let a=`${n}${rt(t,i,r.defaultLocale)}`;o.push(`<link rel="alternate" hreflang="${Vo(i)}" href="${Vo(a)}">`)}let s=`${n}${rt(t,r.defaultLocale,r.defaultLocale)}`;return o.push(`<link rel="alternate" hreflang="x-default" href="${Vo(s)}">`),o.join(`
4532
- `)}function gn(e,t){return`<script data-stx-lang-picker="1">window.__stxI18n=${JSON.stringify({locales:e.locales,defaultLocale:e.defaultLocale,current:t,pickerSelector:e.pickerSelector})};(function(){function cfg(){return window.__stxI18n}function localeFromPath(p){var d=cfg();for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/')return c;if(p.indexOf('/'+c+'/')===0)return c}return d.defaultLocale}function localePathFor(loc,p){var d=cfg();var stripped=p;for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/'){stripped='/';break}if(p.indexOf('/'+c+'/')===0){stripped=p.slice(c.length+1);break}}if(loc===d.defaultLocale)return stripped;if(stripped==='/')return '/'+loc+'/';return '/'+loc+stripped}cfg().localizeHref=function(href){try{var u=new URL(href,location.origin);if(u.origin!==location.origin)return href;return localePathFor(localeFromPath(location.pathname),u.pathname)+(u.search||'')+(u.hash||'')}catch(_){return href}};function syncFromUrl(){var d=cfg();var loc=localeFromPath(location.pathname);d.current=loc;var picker=document.querySelector(d.pickerSelector);if(picker){var btns=picker.querySelectorAll('[data-lang]');for(var i=0;i<btns.length;i++){var b=btns[i];if(b.getAttribute('data-lang')===loc)b.setAttribute('aria-current','true');else b.removeAttribute('aria-current')}}if(document.documentElement.lang!==loc)document.documentElement.lang=loc}function onLangClick(e){var d=cfg();var btn=e.target&&e.target.closest&&e.target.closest('[data-lang]');if(!btn)return;var picker=document.querySelector(d.pickerSelector);if(!picker||!picker.contains(btn))return;e.preventDefault();e.stopPropagation();var loc=btn.getAttribute('data-lang');if(!loc||loc===localeFromPath(location.pathname))return;var dest=localePathFor(loc,location.pathname);var r=window.__stxRouter;if(r&&r.navigate)r.navigate(dest,true,true);else location.assign(dest)}syncFromUrl();if(window.__stxLangPickerBound){document.removeEventListener('click',window.__stxLangPickerClick,true);window.removeEventListener('stx:navigate',window.__stxLangPickerSync);window.removeEventListener('popstate',window.__stxLangPickerSync)}window.__stxLangPickerClick=onLangClick;window.__stxLangPickerSync=syncFromUrl;window.__stxLangPickerBound=1;document.addEventListener('click',onLangClick,true);window.addEventListener('stx:navigate',syncFromUrl);window.addEventListener('popstate',syncFromUrl)})();</script>`}function Vo(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Bh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}async function fl(e){let t=Date.now(),r=e.pagesDir??"pages",n=e.outDir??"dist",o=e.publicDir??"public";if(!e.noClean)Hh(n,{recursive:!0,force:!0});cl(n,{recursive:!0});let s=new zh(`${r}/**/*.stx`),i=await Array.fromAsync(s.scan(".")),a=e.excludeDirs??["layouts","partials","components"],c=[],l=i.filter((w)=>{let v=w.slice(r.length).replace(/^[\\/]+/,"");if(v.split(/[\\/]/).slice(0,-1).some((S)=>a.includes(S)))return c.push(w),!1;return!v.split(/[\\/]/).some((S)=>S.startsWith("_"))});if(c.length>0)console.warn(`[stx] ${c.length} file(s) under ${r}/ skipped as non-pages: ${a.join(", ")}`);if(l.length===0)throw Error(`No .stx files found in ${r}/`);let d=await ol(l,(w)=>Bun.build({entrypoints:w,outdir:n,plugins:[Ho()],naming:{entry:"[name].[ext]"}}));if(d.failed.length>0){for(let{entrypoint:w,error:v}of d.failed)console.error(`[stx] failed to build ${w}:
4533
- ${v}`);if(d.succeeded.length===0)throw Error(`Build failed: none of the ${l.length} page(s) could be built`);console.error(`[stx] ${d.failed.length} of ${l.length} page(s) skipped; the rest were built.`)}Kh(n);let u=Jo(n).filter((w)=>w.endsWith(".html")),p=fn(e,dl.cwd()),h=new Set(u.map(xn));for(let w of u){let v=Pe(n,w),S=ll(v,"utf8"),T=xn(w),C=p?p.locales:[e.seo?.locale?.split(/[_-]/)[0]??"en"];for(let j of C){let k=S;if(k=Gh(k),p)k=mn(k,p,j);if(k=await re(k,dl.cwd()),k=ln(k,e,e.pages?.[T],T),p)k=Zh(k,e,p,j,T),k=Qh(k,j,p.defaultLocale,h);if(k=pn(k,e),k=eg(k),p)k=k.replace(/<\/body>/i,`${gn(p,j)}
4534
- </body>`);if(e.spa!==!1)k=await Wo(k,e.router);let L=p?Yh(T,j,p.defaultLocale):w,X=Pe(n,L);if(cl(Jh(X),{recursive:!0}),yn(X,k),p&&j!==p.defaultLocale&&L!==w);}}let f=Tn(n);if(f.assets>0)console.log(`[stx] externalized ${f.assets} asset(s) from ${f.pages} page(s) (${(f.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(bn(o))al(o,n,{recursive:!0});let g=pl();if(g)al(g,Pe(n,ul),{recursive:!0});let x=Pe(n,"404.html");if(!bn(x)&&bn(Pe(n,"index.html"))){let w=ll(Pe(n,"index.html"),"utf8").replace(/<title>[^<]*<\/title>/i,`<title>404 \u2014 ${tg(e.name)}</title>`);yn(x,w)}if(e.sitemap!==!1){let w=[],v=u.filter((T)=>T!=="404.html").map(xn),S=p?p.locales:[null];for(let T of v){let C=e.pages?.[T];for(let j of S){let k=j&&p?rt(T,j,p.defaultLocale):T;w.push({path:k,page:C})}}yn(Pe(n,"sitemap.xml"),dn(e,w))}let y=un(e);if(y!==null)yn(Pe(n,"robots.txt"),y);let b=u.map(xn);return{outDir:n,pages:b,durationMs:Date.now()-t}}function Jh(e){return qh(e)}function Yh(e,t,r){let n=rt(e,t,r);if(n==="/")return"index.html";let o=n.replace(/^\//,"").replace(/\/$/,"");if(!o.includes("/")){if(t!==r&&o===t)return`${t}/index.html`;return`${o}.html`}return`${o}.html`.replace(/\.html\.html$/,".html")}function xn(e){if(e==="index.html")return"/";return`/${e.replace(/\.html$/,"").replace(/\/index$/,"")}`}function Jo(e,t=e){let r=[];if(!bn(e))return r;for(let n of Uh(e,{withFileTypes:!0})){let o=Pe(e,n.name);if(n.isDirectory())r.push(...Jo(o,t));else r.push(Xh(t,o))}return r}function Kh(e){for(let t of Jo(e)){if(!/^chunk-.*\.js(?:\.map)?$/.test(t))continue;let r=Pe(e,t);try{if(Wh(r).size===0)Vh(r)}catch{}}}function Gh(e){return e.replace(/<script[^>]*src=["']\.\/chunk-[^"']*\.js["'][^>]*><\/script>\s*/g,"")}function Zh(e,t,r,n,o){if(!r)return e;if(/<html\b[^>]*\blang=/i.test(e))e=e.replace(/<html\b([^>]*)\blang="[^"]*"/i,`<html$1lang="${n}"`);else e=e.replace(/<html\b([^>]*)>/i,`<html$1 lang="${n}">`);let s=`${t.url.replace(/\/$/,"")}${rt(o,n,r.defaultLocale)}`;if(/<link rel="canonical"/.test(e))e=e.replace(/<link rel="canonical"[^>]*>/,`<link rel="canonical" href="${Xo(s)}">`);let i=n.includes("_")||n.includes("-")?n:n.toLowerCase();if(/<meta property="og:locale"/.test(e))e=e.replace(/<meta property="og:locale"[^>]*>/,`<meta property="og:locale" content="${Xo(i)}">`);if(/<meta property="og:url"/.test(e))e=e.replace(/<meta property="og:url"[^>]*>/,`<meta property="og:url" content="${Xo(s)}">`);let a=hn(t.url,o,r);if(!e.includes("hreflang="))e=e.replace(/<link rel="canonical"[^>]*>/,(c)=>`${a}
4535
- ${c}`);return e}function Xo(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qh(e,t,r,n){if(t===r)return e;return e.replace(/<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi,(o,s,i,a)=>{if(i.startsWith("//"))return o;if(i===`/${t}`||i===`/${t}/`||i.startsWith(`/${t}/`))return o;let c=i.match(/^(\/[^?#]*)(.*)$/);if(!c)return o;let[,l,d]=c,u=l==="/"?"/":l.replace(/\/$/,"");if(!n.has(u))return o;let p=u==="/"?`/${t}/`:`/${t}${u}`;return`<a${s}href="${p}${d}"${a}>`})}function eg(e){if(/<main\b/i.test(e)||/\bdata-stx-content\b/i.test(e))return e;let t=e.match(/<body\b[^>]*>/i),r=e.search(/<\/body\s*>/i);if(!t||r<0)return e;let n=t.index+t[0].length,o=e.slice(n,r),s=0,i=[...o.matchAll(/<\/nav>/gi)];if(i.length>0){let p=i[i.length-1];s=p.index+p[0].length}let a=o.length,c=o.search(/<footer\b/i);if(c!==-1)a=Math.min(a,c);let l=o.search(/<script\b[^>]*data-stx-(?:theme-toggle|reparent-progress)\b/i);if(l!==-1)a=Math.min(a,l);if(a<=s)return e;let d=o.slice(s,a);if(!d.trim())return e;let u=`${o.slice(0,s)}
4528
+ ${c}`)}if(!r&&!e.includes("__stxThemeGuard")&&/<head\b[^>]*>/i.test(e)){let c=`<script data-stx-theme-guard="1">${`window.__STX_COLOR_MODE__=window.__STX_COLOR_MODE__||${JSON.stringify({storageKey:s,initialMode:o,darkClass:"dark"})};`}${jh(o,s,i,a)};window.__stxThemeGuard=1;</script>`;e=e.replace(/<head\b([^>]*)>/i,`<head$1>
4529
+ ${c}`)}if(!r&&!e.includes("__stxThemeToggle")&&/<\/body>/i.test(e)){let c=`<script data-stx-theme-toggle="1">${Rh(s,i,a)};window.__stxThemeToggle=1;</script>`;e=e.replace(/<\/body>/i,`${c}
4530
+ </body>`)}return e}async function sl(e,t){if(e.length===0)return{succeeded:[],failed:[]};try{return await t(e),{succeeded:[...e],failed:[]}}catch{}let r=[],n=[];for(let o of e)try{await t([o]),r.push(o)}catch(s){n.push({entrypoint:o,error:Et(s,o)})}return{succeeded:r,failed:n}}import{existsSync as Mh,readFileSync as Dh}from"fs";import{join as Ph,resolve as Oh}from"path";import Ih from"process";function mn(e,t=Ih.cwd()){let r=e.i18n;if(!r||!Array.isArray(r.locales)||r.locales.length===0)return null;let n=r.defaultLocale??r.locales[0],o=Lh(r,t);return{locales:r.locales,defaultLocale:n,labels:r.labels??Object.fromEntries(r.locales.map((s)=>[s,s.toUpperCase()])),translations:o,pickerSelector:r.pickerSelector??"#lang-picker"}}function Lh(e,t){let r=e.translations??{},n={},o=e.translationsDir,s=o===!1?null:Oh(t,typeof o==="string"&&o?o:"translations"),i=e.format??"json";for(let a of e.locales){let c=s?Fh(s,a,i):{};n[a]={...c,...r[a]??{}}}return n}function Fh(e,t,r){let n=r==="json"?[`${t}.json`]:[`${t}.${r}`,`${t}.${r==="yaml"?"yml":"yaml"}`];for(let o of n){let s=Ph(e,o);if(!Mh(s))continue;try{let i=Dh(s,"utf8"),a=r==="json"?JSON.parse(i):Nh(i);return il(a)}catch{continue}}return{}}function il(e,t="",r={}){if(!e||typeof e!=="object")return r;for(let[n,o]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(o&&typeof o==="object"&&!Array.isArray(o))il(o,s,r);else if(typeof o==="string")r[s]=o;else if(typeof o==="number"||typeof o==="boolean")r[s]=String(o)}return r}function Nh(e){let t={},r=[{obj:t,indent:-1}];for(let n of e.split(`
4531
+ `)){let o=n.replace(/#.*$/,"").trimEnd();if(!o.trim())continue;let s=o.search(/\S/);if(s===-1)continue;while(r.length>1&&r[r.length-1].indent>=s)r.pop();let i=r[r.length-1].obj,a=o.match(/^(\s*)(\S[^:]*):\s*(.*)$/);if(!a)continue;let[,,c,l]=a,d=c.trim(),u=l.trim();if(u==="")i[d]={},r.push({obj:i[d],indent:s});else i[d]=Bh(u)}return t}function Bh(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Xo(e,t,r){let n=e.translations[t]?.[r];if(typeof n==="string")return n;let o=e.translations[e.defaultLocale]?.[r];if(typeof o==="string")return o;return r}function hn(e,t,r){return e.replace(/\{t(!?):([a-zA-Z][\w.-]*)\}/g,(n,o,s)=>{let i=Xo(t,r,s);return o==="!"?i:zh(i)})}function nt(e,t,r){if(t===r)return e;if(e==="/")return`/${t}/`;if(e==="/404.html")return`/${t}/404.html`;return`/${t}${e}`}function al(e,t){for(let r of t){if(e===`/${r}`||e===`/${r}/`)return{locale:r,path:"/"};if(e.startsWith(`/${r}/`))return{locale:r,path:e.slice(r.length+1)}}return{locale:null,path:e}}function gn(e,t,r){let n=e.replace(/\/$/,""),o=[];for(let i of r.locales){let a=`${n}${nt(t,i,r.defaultLocale)}`;o.push(`<link rel="alternate" hreflang="${qo(i)}" href="${qo(a)}">`)}let s=`${n}${nt(t,r.defaultLocale,r.defaultLocale)}`;return o.push(`<link rel="alternate" hreflang="x-default" href="${qo(s)}">`),o.join(`
4532
+ `)}function yn(e,t){return`<script data-stx-lang-picker="1">window.__stxI18n=${JSON.stringify({locales:e.locales,defaultLocale:e.defaultLocale,current:t,pickerSelector:e.pickerSelector})};(function(){function cfg(){return window.__stxI18n}function localeFromPath(p){var d=cfg();for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/')return c;if(p.indexOf('/'+c+'/')===0)return c}return d.defaultLocale}function localePathFor(loc,p){var d=cfg();var stripped=p;for(var i=0;i<d.locales.length;i++){var c=d.locales[i];if(p==='/'+c||p==='/'+c+'/'){stripped='/';break}if(p.indexOf('/'+c+'/')===0){stripped=p.slice(c.length+1);break}}if(loc===d.defaultLocale)return stripped;if(stripped==='/')return '/'+loc+'/';return '/'+loc+stripped}cfg().localizeHref=function(href){try{var u=new URL(href,location.origin);if(u.origin!==location.origin)return href;return localePathFor(localeFromPath(location.pathname),u.pathname)+(u.search||'')+(u.hash||'')}catch(_){return href}};function syncFromUrl(){var d=cfg();var loc=localeFromPath(location.pathname);d.current=loc;var picker=document.querySelector(d.pickerSelector);if(picker){var btns=picker.querySelectorAll('[data-lang]');for(var i=0;i<btns.length;i++){var b=btns[i];if(b.getAttribute('data-lang')===loc)b.setAttribute('aria-current','true');else b.removeAttribute('aria-current')}}if(document.documentElement.lang!==loc)document.documentElement.lang=loc}function onLangClick(e){var d=cfg();var btn=e.target&&e.target.closest&&e.target.closest('[data-lang]');if(!btn)return;var picker=document.querySelector(d.pickerSelector);if(!picker||!picker.contains(btn))return;e.preventDefault();e.stopPropagation();var loc=btn.getAttribute('data-lang');if(!loc||loc===localeFromPath(location.pathname))return;var dest=localePathFor(loc,location.pathname);var r=window.__stxRouter;if(r&&r.navigate)r.navigate(dest,true,true);else location.assign(dest)}syncFromUrl();if(window.__stxLangPickerBound){document.removeEventListener('click',window.__stxLangPickerClick,true);window.removeEventListener('stx:navigate',window.__stxLangPickerSync);window.removeEventListener('popstate',window.__stxLangPickerSync)}window.__stxLangPickerClick=onLangClick;window.__stxLangPickerSync=syncFromUrl;window.__stxLangPickerBound=1;document.addEventListener('click',onLangClick,true);window.addEventListener('stx:navigate',syncFromUrl);window.addEventListener('popstate',syncFromUrl)})();</script>`}function qo(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function zh(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}async function ml(e){let t=Date.now(),r=e.pagesDir??"pages",n=e.outDir??"dist",o=e.publicDir??"public";if(!e.noClean)Wh(n,{recursive:!0,force:!0});ll(n,{recursive:!0});let s=new Uh(`${r}/**/*.stx`),i=await Array.fromAsync(s.scan(".")),a=e.excludeDirs??["layouts","partials","components"],c=[],l=i.filter((w)=>{let v=w.slice(r.length).replace(/^[\\/]+/,"");if(v.split(/[\\/]/).slice(0,-1).some((k)=>a.includes(k)))return c.push(w),!1;return!v.split(/[\\/]/).some((k)=>k.startsWith("_"))});if(c.length>0)console.warn(`[stx] ${c.length} file(s) under ${r}/ skipped as non-pages: ${a.join(", ")}`);if(l.length===0)throw Error(`No .stx files found in ${r}/`);let d=await sl(l,(w)=>Bun.build({entrypoints:w,outdir:n,plugins:[Wo()],naming:{entry:"[name].[ext]"}}));if(d.failed.length>0){for(let{entrypoint:w,error:v}of d.failed)console.error(`[stx] failed to build ${w}:
4533
+ ${v}`);if(d.succeeded.length===0)throw Error(`Build failed: none of the ${l.length} page(s) could be built`);console.error(`[stx] ${d.failed.length} of ${l.length} page(s) skipped; the rest were built.`)}Gh(n);let u=Yo(n).filter((w)=>w.endsWith(".html")),p=mn(e,ul.cwd()),h=new Set(u.map(bn));for(let w of u){let v=Oe(n,w),k=dl(v,"utf8"),C=bn(w),E=p?p.locales:[e.seo?.locale?.split(/[_-]/)[0]??"en"];for(let R of E){let T=k;if(T=Zh(T),p)T=hn(T,p,R);if(T=await ne(T,ul.cwd()),T=dn(T,e,e.pages?.[C],C),p)T=Qh(T,e,p,R,C),T=eg(T,R,p.defaultLocale,h);if(T=fn(T,e),T=tg(T),p)T=T.replace(/<\/body>/i,`${yn(p,R)}
4534
+ </body>`);if(e.spa!==!1)T=await Vo(T,e.router);let F=p?Kh(C,R,p.defaultLocale):w,J=Oe(n,F);if(ll(Yh(J),{recursive:!0}),xn(J,T),p&&R!==p.defaultLocale&&F!==w);}}let f=Cn(n);if(f.assets>0)console.log(`[stx] externalized ${f.assets} asset(s) from ${f.pages} page(s) (${(f.bytesInlined/1024).toFixed(1)}KB removed from HTML)`);if(wn(o))cl(o,n,{recursive:!0});let g=fl();if(g)cl(g,Oe(n,pl),{recursive:!0});let x=Oe(n,"404.html");if(!wn(x)&&wn(Oe(n,"index.html"))){let w=dl(Oe(n,"index.html"),"utf8").replace(/<title>[^<]*<\/title>/i,`<title>404 \u2014 ${rg(e.name)}</title>`);xn(x,w)}if(e.sitemap!==!1){let w=[],v=u.filter((C)=>C!=="404.html").map(bn),k=p?p.locales:[null];for(let C of v){let E=e.pages?.[C];for(let R of k){let T=R&&p?nt(C,R,p.defaultLocale):C;w.push({path:T,page:E})}}xn(Oe(n,"sitemap.xml"),un(e,w))}let y=pn(e);if(y!==null)xn(Oe(n,"robots.txt"),y);let b=u.map(bn);return{outDir:n,pages:b,durationMs:Date.now()-t}}function Yh(e){return Xh(e)}function Kh(e,t,r){let n=nt(e,t,r);if(n==="/")return"index.html";let o=n.replace(/^\//,"").replace(/\/$/,"");if(!o.includes("/")){if(t!==r&&o===t)return`${t}/index.html`;return`${o}.html`}return`${o}.html`.replace(/\.html\.html$/,".html")}function bn(e){if(e==="index.html")return"/";return`/${e.replace(/\.html$/,"").replace(/\/index$/,"")}`}function Yo(e,t=e){let r=[];if(!wn(e))return r;for(let n of Hh(e,{withFileTypes:!0})){let o=Oe(e,n.name);if(n.isDirectory())r.push(...Yo(o,t));else r.push(Jh(t,o))}return r}function Gh(e){for(let t of Yo(e)){if(!/^chunk-.*\.js(?:\.map)?$/.test(t))continue;let r=Oe(e,t);try{if(Vh(r).size===0)qh(r)}catch{}}}function Zh(e){return e.replace(/<script[^>]*src=["']\.\/chunk-[^"']*\.js["'][^>]*><\/script>\s*/g,"")}function Qh(e,t,r,n,o){if(!r)return e;if(/<html\b[^>]*\blang=/i.test(e))e=e.replace(/<html\b([^>]*)\blang="[^"]*"/i,`<html$1lang="${n}"`);else e=e.replace(/<html\b([^>]*)>/i,`<html$1 lang="${n}">`);let s=`${t.url.replace(/\/$/,"")}${nt(o,n,r.defaultLocale)}`;if(/<link rel="canonical"/.test(e))e=e.replace(/<link rel="canonical"[^>]*>/,`<link rel="canonical" href="${Jo(s)}">`);let i=n.includes("_")||n.includes("-")?n:n.toLowerCase();if(/<meta property="og:locale"/.test(e))e=e.replace(/<meta property="og:locale"[^>]*>/,`<meta property="og:locale" content="${Jo(i)}">`);if(/<meta property="og:url"/.test(e))e=e.replace(/<meta property="og:url"[^>]*>/,`<meta property="og:url" content="${Jo(s)}">`);let a=gn(t.url,o,r);if(!e.includes("hreflang="))e=e.replace(/<link rel="canonical"[^>]*>/,(c)=>`${a}
4535
+ ${c}`);return e}function Jo(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function eg(e,t,r,n){if(t===r)return e;return e.replace(/<a\b([^>]*?)\bhref="(\/[^"]*)"([^>]*)>/gi,(o,s,i,a)=>{if(i.startsWith("//"))return o;if(i===`/${t}`||i===`/${t}/`||i.startsWith(`/${t}/`))return o;let c=i.match(/^(\/[^?#]*)(.*)$/);if(!c)return o;let[,l,d]=c,u=l==="/"?"/":l.replace(/\/$/,"");if(!n.has(u))return o;let p=u==="/"?`/${t}/`:`/${t}${u}`;return`<a${s}href="${p}${d}"${a}>`})}function tg(e){if(/<main\b/i.test(e)||/\bdata-stx-content\b/i.test(e))return e;let t=e.match(/<body\b[^>]*>/i),r=e.search(/<\/body\s*>/i);if(!t||r<0)return e;let n=t.index+t[0].length,o=e.slice(n,r),s=0,i=[...o.matchAll(/<\/nav>/gi)];if(i.length>0){let p=i[i.length-1];s=p.index+p[0].length}let a=o.length,c=o.search(/<footer\b/i);if(c!==-1)a=Math.min(a,c);let l=o.search(/<script\b[^>]*data-stx-(?:theme-toggle|reparent-progress)\b/i);if(l!==-1)a=Math.min(a,l);if(a<=s)return e;let d=o.slice(s,a);if(!d.trim())return e;let u=`${o.slice(0,s)}
4536
4536
  <main>${d}</main>
4537
- ${o.slice(a)}`;return`${e.slice(0,n)}${u}${e.slice(r)}`}function tg(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ml(e){return e}var rg=new Set(["if","else","elseif","else-if","for","foreach","show","model","html","text","bind","key","ref","once","memo","slot","teleport","cloak","pre","effect","init"]),ng=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function og(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sg(e){let t=[],r=/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,n;while((n=r.exec(e))!==null)t.push([n.index,n.index+n[0].length]);return t}function ig(e,t){for(let[r,n]of e)if(t>=r&&t<n)return!0;return!1}function vn(e,t){let r=1,n=0;for(let o=0;o<t&&o<e.length;o++)if(e[o]===`
4538
- `)r++,n=o+1;return{line:r,column:t-n+1}}function ag(e,t,r){let n=t.toLowerCase(),o=e.length,s=1,i=r;while(i<o){let a=e.indexOf("<",i);if(a===-1)return-1;if(i=a,e.startsWith("<!--",i)){let d=e.indexOf("-->",i+4);if(d===-1)return-1;i=d+3;continue}if(e[i+1]==="/"){let d=/^<\/([a-z][\w-]*)\s*>/i.exec(e.slice(i,i+64));if(!d){i++;continue}if(d[1].toLowerCase()===n){if(s--,i+=d[0].length,s===0)return i;continue}i+=d[0].length;continue}let c=/^<([a-z][\w-]*)\b/i.exec(e.slice(i,i+64));if(!c){i++;continue}let l=e.indexOf(">",i);if(l===-1)return-1;if(c[1].toLowerCase()===n&&e[l-1]!=="/")s++;i=l+1}return-1}function cg(e,t,r){let n=/@([a-z][\w:-]*)((?:\.[a-z][\w-]*)*)\s*=\s*"([^"]*)"/gi,o;while((o=n.exec(e))!==null){if(ig(t,o.index))continue;let s=o[1].toLowerCase().split(":")[0];if(rg.has(s))continue;let i=o[3].trim();if(/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(i)){let a=e.indexOf(o[3],o.index),{line:c,column:l}=vn(e,a<0?o.index:a);r.push({ruleId:"stx/no-bare-function-ref-in-event",message:`Event handler @${o[1]}="${i}" is a member path, which the runtime does not invoke \u2014 it only auto-calls a plain identifier. Call it: @${o[1]}="${i}($event)".`,line:c,column:l,severity:"error"})}}}function hl(e){let t=e.split("/"),r=[];for(let n of t){if(n===""||n===".")continue;if(n==="..")r.pop();else r.push(n)}return r.join("/")}function lg(e,t,r){let n=t.replace(/\\/g,"/"),o=n.indexOf("resources/stores/");if(o===-1)return;let s=n.slice(0,o+16),i=n.slice(0,n.lastIndexOf("/")),a=/\b(import|export)\s+(type\s+)?([^'"]*?)\s*from\s*['"]([^'"]+)['"]/g,c;while((c=a.exec(e))!==null){if(c[2])continue;let l=c[1],d=c[4],u;if(d.startsWith("."))u=!hl(`${i}/${d}`).startsWith(hl(s));else u=!0;if(u){let{line:p,column:h}=vn(e,c.index),f=l==="export"?"Value re-export":"Value import";r.push({ruleId:"stx/store-value-imports-must-be-local",message:`${f} from "${d}" is outside resources/stores/ and will be stripped from the store bundle. Use \`${l} type\`, or move the value into the stores dir.`,line:p,column:h,severity:"error"})}}}function dg(e){let t=e.trim(),r=(i)=>{let a=i.match(/[A-Za-z_$][\w$]*/g);return a?a:[]},n=/\bas\s+(.+)$/.exec(t);if(n){let i=n[1].trim(),a=/^([A-Za-z_$][\w$]*)\s*=>\s*([A-Za-z_$][\w$]*)/.exec(i);if(a)return[a[1],a[2]];let c=/^\(([^)]*)\)/.exec(i);if(c)return r(c[1]);let l=/^([A-Za-z_$][\w$]*)/.exec(i);return l?[l[1]]:[]}let o=/^\(([^)]*)\)\s+(?:in|of)\s+/.exec(t);if(o)return r(o[1]);let s=/^([A-Za-z_$][\w$]*)\s+(?:in|of)\s+/.exec(t);return s?[s[1]]:[]}function ug(e,t){let r=/(?::for|x-for|@for)\s*=\s*"([^"]*)"/gi,n;while((n=r.exec(e))!==null){let o=dg(n[1]);if(o.length===0)continue;let s=e.lastIndexOf("<",n.index);if(s===-1)continue;let i=/^<([a-z][\w-]*)/i.exec(e.slice(s,s+64));if(!i)continue;let a=e.indexOf(">",n.index);if(a===-1)continue;let c=e[a-1]==="/"||ng.has(i[1].toLowerCase())?a+1:ag(e,i[1],a+1),l=c===-1?a+1:c,d=e.indexOf(n[1],n.index),u=e.slice(s,l);if(d>=0&&d+n[1].length<=l){let p=d-s;u=u.slice(0,p)+" ".repeat(n[1].length)+u.slice(p+n[1].length)}for(let p of o){let h=new RegExp(`(?<![.\\w$])${og(p)}\\s*\\(`,"g"),f;while((f=h.exec(u))!==null){let g=s+f.index,{line:x,column:y}=vn(e,g);t.push({ruleId:"stx/no-signal-call-in-for-iteration-var",message:`"${p}" is a :for iteration variable, not a signal \u2014 calling it as "${p}()" leaves it as a function and silently breaks comparisons. Use "${p}" directly.`,line:x,column:y,severity:"error"})}}}}function pg(e,t){let r=/<!--([\s\S]*?)-->/g,n;while((n=r.exec(e))!==null){let o=n[1].indexOf("`");if(o!==-1){let s=n.index+4+o,{line:i,column:a}=vn(e,s);t.push({ruleId:"stx/no-backticks-in-html-comments",message:"Backtick inside an HTML comment leaks into the merged setup function and flips the JS parser into template-literal mode. Remove it or rephrase the comment.",line:i,column:a,severity:"error"})}}}function wn(e,t){return e?.[t]!==!1}function fg(e,t={}){let r=[],n=sg(e),o=(t.filePath??"").replace(/\\/g,"/"),s=t.fileKind??(/\/components?\//i.test(o)?"component":/\/layouts?\//i.test(o)?"layout":"view");if(wn(t.rules,"stx/no-bare-function-ref-in-event"))cg(e,n,r);if(o&&wn(t.rules,"stx/store-value-imports-must-be-local"))lg(e,o,r);if(wn(t.rules,"stx/no-signal-call-in-for-iteration-var"))ug(e,r);if(wn(t.rules,"stx/no-backticks-in-html-comments"))pg(e,r);r.sort((a,c)=>a.line-c.line||a.column-c.column);let i=new Set;return r.filter((a)=>{let c=`${a.ruleId}:${a.line}:${a.column}`;if(i.has(c))return!1;return i.add(c),!0})}function mg(e,t){return e.kind===t}function gl(e){if(e===String)return"string";if(e===Number)return"number";if(e===Boolean)return"boolean";if(e===Array)return"array";if(e===Object)return"object";if(e===Function)return"function";if(e===Date)return"date";if(e===Symbol)return"symbol";if(typeof e==="function"&&e.name)return e.name;return"unknown"}function hg(e,t){if(e===null||e===void 0)return!0;if(t===String)return typeof e==="string";if(t===Number)return typeof e==="number"&&!Number.isNaN(e);if(t===Boolean)return typeof e==="boolean";if(t===Array)return Array.isArray(e);if(t===Object)return typeof e==="object"&&!Array.isArray(e);if(t===Function)return typeof e==="function";if(t===Date)return e instanceof Date;if(t===Symbol)return typeof e==="symbol";if(typeof t==="function")return e instanceof t;return!0}function yl(e,t,r,n){let o=n?`[${n}]`:"";if(r.required&&(t===void 0||t===null))return{prop:e,message:`${o} Missing required prop: "${e}"`,value:t,expected:r.type?gl(r.type):void 0};if(t===void 0||t===null)return null;if(r.type){let s=Array.isArray(r.type)?r.type:[r.type];if(!s.some((i)=>hg(t,i))){let i=s.map((a)=>gl(a)).join(" | ");return{prop:e,message:`${o} Invalid prop type for "${e}": expected ${i}, got ${typeof t}`,value:t,expected:i}}}if(r.validator){if(!r.validator(t))return{prop:e,message:`${o} Custom validation failed for prop "${e}"`,value:t}}return null}function gg(e){let t=globalThis.__STX_CURRENT_PROPS__||{};if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=typeof o==="function"||Array.isArray(o)?{type:o}:o||{};if(r[n]===void 0&&s.default!==void 0)r[n]=typeof s.default==="function"?s.default():s.default}return r}function yg(e,t={}){let{componentName:r,throwOnError:n=!1,logWarnings:o=!0}=t,s=globalThis.__STX_CURRENT_PROPS__||{},i={...s},a={valid:!0,errors:[],warnings:[]};for(let[c,l]of Object.entries(e)){let d=typeof l==="function"||Array.isArray(l)?{type:l}:l||{};if(i[c]===void 0&&d.default!==void 0)i[c]=typeof d.default==="function"?d.default():d.default;let u=yl(c,i[c],d,r);if(u){if(a.valid=!1,a.errors.push(u),o)console.warn(u.message)}}for(let c of Object.keys(s))if(!(c in e)){let l=`${r?`[${r}]`:""} Unknown prop: "${c}"`;if(a.warnings.push(l),o)console.warn(l)}if(n&&!a.valid){let c=a.errors.map((l)=>l.message).join(`
4537
+ ${o.slice(a)}`;return`${e.slice(0,n)}${u}${e.slice(r)}`}function rg(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hl(e){return e}var ng=new Set(["if","else","elseif","else-if","for","foreach","show","model","html","text","bind","key","ref","once","memo","slot","teleport","cloak","pre","effect","init"]),og=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function sg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ig(e){let t=[],r=/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,n;while((n=r.exec(e))!==null)t.push([n.index,n.index+n[0].length]);return t}function ag(e,t){for(let[r,n]of e)if(t>=r&&t<n)return!0;return!1}function $n(e,t){let r=1,n=0;for(let o=0;o<t&&o<e.length;o++)if(e[o]===`
4538
+ `)r++,n=o+1;return{line:r,column:t-n+1}}function cg(e,t,r){let n=t.toLowerCase(),o=e.length,s=1,i=r;while(i<o){let a=e.indexOf("<",i);if(a===-1)return-1;if(i=a,e.startsWith("<!--",i)){let d=e.indexOf("-->",i+4);if(d===-1)return-1;i=d+3;continue}if(e[i+1]==="/"){let d=/^<\/([a-z][\w-]*)\s*>/i.exec(e.slice(i,i+64));if(!d){i++;continue}if(d[1].toLowerCase()===n){if(s--,i+=d[0].length,s===0)return i;continue}i+=d[0].length;continue}let c=/^<([a-z][\w-]*)\b/i.exec(e.slice(i,i+64));if(!c){i++;continue}let l=e.indexOf(">",i);if(l===-1)return-1;if(c[1].toLowerCase()===n&&e[l-1]!=="/")s++;i=l+1}return-1}function lg(e,t,r){let n=/@([a-z][\w:-]*)((?:\.[a-z][\w-]*)*)\s*=\s*"([^"]*)"/gi,o;while((o=n.exec(e))!==null){if(ag(t,o.index))continue;let s=o[1].toLowerCase().split(":")[0];if(ng.has(s))continue;let i=o[3].trim();if(/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(i)){let a=e.indexOf(o[3],o.index),{line:c,column:l}=$n(e,a<0?o.index:a);r.push({ruleId:"stx/no-bare-function-ref-in-event",message:`Event handler @${o[1]}="${i}" is a member path, which the runtime does not invoke \u2014 it only auto-calls a plain identifier. Call it: @${o[1]}="${i}($event)".`,line:c,column:l,severity:"error"})}}}function gl(e){let t=e.split("/"),r=[];for(let n of t){if(n===""||n===".")continue;if(n==="..")r.pop();else r.push(n)}return r.join("/")}function dg(e,t,r){let n=t.replace(/\\/g,"/"),o=n.indexOf("resources/stores/");if(o===-1)return;let s=n.slice(0,o+16),i=n.slice(0,n.lastIndexOf("/")),a=/\b(import|export)\s+(type\s+)?([^'"]*?)\s*from\s*['"]([^'"]+)['"]/g,c;while((c=a.exec(e))!==null){if(c[2])continue;let l=c[1],d=c[4],u;if(d.startsWith("."))u=!gl(`${i}/${d}`).startsWith(gl(s));else u=!0;if(u){let{line:p,column:h}=$n(e,c.index),f=l==="export"?"Value re-export":"Value import";r.push({ruleId:"stx/store-value-imports-must-be-local",message:`${f} from "${d}" is outside resources/stores/ and will be stripped from the store bundle. Use \`${l} type\`, or move the value into the stores dir.`,line:p,column:h,severity:"error"})}}}function ug(e){let t=e.trim(),r=(i)=>{let a=i.match(/[A-Za-z_$][\w$]*/g);return a?a:[]},n=/\bas\s+(.+)$/.exec(t);if(n){let i=n[1].trim(),a=/^([A-Za-z_$][\w$]*)\s*=>\s*([A-Za-z_$][\w$]*)/.exec(i);if(a)return[a[1],a[2]];let c=/^\(([^)]*)\)/.exec(i);if(c)return r(c[1]);let l=/^([A-Za-z_$][\w$]*)/.exec(i);return l?[l[1]]:[]}let o=/^\(([^)]*)\)\s+(?:in|of)\s+/.exec(t);if(o)return r(o[1]);let s=/^([A-Za-z_$][\w$]*)\s+(?:in|of)\s+/.exec(t);return s?[s[1]]:[]}function pg(e,t){let r=/(?::for|x-for|@for)\s*=\s*"([^"]*)"/gi,n;while((n=r.exec(e))!==null){let o=ug(n[1]);if(o.length===0)continue;let s=e.lastIndexOf("<",n.index);if(s===-1)continue;let i=/^<([a-z][\w-]*)/i.exec(e.slice(s,s+64));if(!i)continue;let a=e.indexOf(">",n.index);if(a===-1)continue;let c=e[a-1]==="/"||og.has(i[1].toLowerCase())?a+1:cg(e,i[1],a+1),l=c===-1?a+1:c,d=e.indexOf(n[1],n.index),u=e.slice(s,l);if(d>=0&&d+n[1].length<=l){let p=d-s;u=u.slice(0,p)+" ".repeat(n[1].length)+u.slice(p+n[1].length)}for(let p of o){let h=new RegExp(`(?<![.\\w$])${sg(p)}\\s*\\(`,"g"),f;while((f=h.exec(u))!==null){let g=s+f.index,{line:x,column:y}=$n(e,g);t.push({ruleId:"stx/no-signal-call-in-for-iteration-var",message:`"${p}" is a :for iteration variable, not a signal \u2014 calling it as "${p}()" leaves it as a function and silently breaks comparisons. Use "${p}" directly.`,line:x,column:y,severity:"error"})}}}}function fg(e,t){let r=/<!--([\s\S]*?)-->/g,n;while((n=r.exec(e))!==null){let o=n[1].indexOf("`");if(o!==-1){let s=n.index+4+o,{line:i,column:a}=$n(e,s);t.push({ruleId:"stx/no-backticks-in-html-comments",message:"Backtick inside an HTML comment leaks into the merged setup function and flips the JS parser into template-literal mode. Remove it or rephrase the comment.",line:i,column:a,severity:"error"})}}}function vn(e,t){return e?.[t]!==!1}function mg(e,t={}){let r=[],n=ig(e),o=(t.filePath??"").replace(/\\/g,"/"),s=t.fileKind??(/\/components?\//i.test(o)?"component":/\/layouts?\//i.test(o)?"layout":"view");if(vn(t.rules,"stx/no-bare-function-ref-in-event"))lg(e,n,r);if(o&&vn(t.rules,"stx/store-value-imports-must-be-local"))dg(e,o,r);if(vn(t.rules,"stx/no-signal-call-in-for-iteration-var"))pg(e,r);if(vn(t.rules,"stx/no-backticks-in-html-comments"))fg(e,r);r.sort((a,c)=>a.line-c.line||a.column-c.column);let i=new Set;return r.filter((a)=>{let c=`${a.ruleId}:${a.line}:${a.column}`;if(i.has(c))return!1;return i.add(c),!0})}function hg(e,t){return e.kind===t}function yl(e){if(e===String)return"string";if(e===Number)return"number";if(e===Boolean)return"boolean";if(e===Array)return"array";if(e===Object)return"object";if(e===Function)return"function";if(e===Date)return"date";if(e===Symbol)return"symbol";if(typeof e==="function"&&e.name)return e.name;return"unknown"}function gg(e,t){if(e===null||e===void 0)return!0;if(t===String)return typeof e==="string";if(t===Number)return typeof e==="number"&&!Number.isNaN(e);if(t===Boolean)return typeof e==="boolean";if(t===Array)return Array.isArray(e);if(t===Object)return typeof e==="object"&&!Array.isArray(e);if(t===Function)return typeof e==="function";if(t===Date)return e instanceof Date;if(t===Symbol)return typeof e==="symbol";if(typeof t==="function")return e instanceof t;return!0}function xl(e,t,r,n){let o=n?`[${n}]`:"";if(r.required&&(t===void 0||t===null))return{prop:e,message:`${o} Missing required prop: "${e}"`,value:t,expected:r.type?yl(r.type):void 0};if(t===void 0||t===null)return null;if(r.type){let s=Array.isArray(r.type)?r.type:[r.type];if(!s.some((i)=>gg(t,i))){let i=s.map((a)=>yl(a)).join(" | ");return{prop:e,message:`${o} Invalid prop type for "${e}": expected ${i}, got ${typeof t}`,value:t,expected:i}}}if(r.validator){if(!r.validator(t))return{prop:e,message:`${o} Custom validation failed for prop "${e}"`,value:t}}return null}function yg(e){let t=globalThis.__STX_CURRENT_PROPS__||{};if(!e)return t;let r={...t};for(let[n,o]of Object.entries(e)){let s=typeof o==="function"||Array.isArray(o)?{type:o}:o||{};if(r[n]===void 0&&s.default!==void 0)r[n]=typeof s.default==="function"?s.default():s.default}return r}function xg(e,t={}){let{componentName:r,throwOnError:n=!1,logWarnings:o=!0}=t,s=globalThis.__STX_CURRENT_PROPS__||{},i={...s},a={valid:!0,errors:[],warnings:[]};for(let[c,l]of Object.entries(e)){let d=typeof l==="function"||Array.isArray(l)?{type:l}:l||{};if(i[c]===void 0&&d.default!==void 0)i[c]=typeof d.default==="function"?d.default():d.default;let u=xl(c,i[c],d,r);if(u){if(a.valid=!1,a.errors.push(u),o)console.warn(u.message)}}for(let c of Object.keys(s))if(!(c in e)){let l=`${r?`[${r}]`:""} Unknown prop: "${c}"`;if(a.warnings.push(l),o)console.warn(l)}if(n&&!a.valid){let c=a.errors.map((l)=>l.message).join(`
4539
4539
  `);throw Error(`Prop validation failed:
4540
- ${c}`)}return{props:i,validation:a}}function xg(e,t){let r={...e};for(let[n,o]of Object.entries(t))if(r[n]===void 0)r[n]=typeof o==="function"?o():o;return r}function bg(e){return e}function wg(e){return{type:e,required:!0}}function vg(e,t){return{type:t,default:e}}function $g(e,t={}){return{...t,validator:e}}function Sg(e,t={}){return{...t,validator:(r)=>e.includes(r)}}function kg(e,t={}){return{...t,type:Array,validator:(r)=>{if(!Array.isArray(r))return!1;return!0}}}function Tg(e,t={}){return{...t,type:Object}}function Cg(e,t,r){if(!t)return e;let n={};for(let[o,s]of Object.entries(t)){let i=typeof s==="function"||Array.isArray(s)?{type:s}:s||{},a=e[o];if(a===void 0&&i.default!==void 0)a=typeof i.default==="function"?i.default():i.default;{let c=yl(o,a,i,r);if(c)console.warn(c.message)}n[o]=a}for(let[o,s]of Object.entries(e))if(!(o in n))n[o]=s;return n}var mk={};export{jn as writeNetlifyConfig,eD as writeManifest,Vl as writeImageManifest,k0 as wrapComponentForHMR,xg as withDefaults,o_ as webComponentDirectiveHandler,ha as watermark,N$ as watchViews,Fy as watchMultiple,Ny as watchEffect,Ly as watch,tx as waitForStore,lj as waitForLocale,ji as virtualPathFor,Bm as videoDirective,jE as validators,$g as validated,YA as validateValueEnhanced,TM as validateTemplate,ba as validateParams,KA as validateFormEnhanced,Po as validateFile,VA as validateFields,WA as validateField,EM as validateDirective,yA as validateCspDirectives,a_ as validateConfig,vx as validateComponentScripts,_x as validateComponentProps,MR as validateClientScript,Pg as v,k_ as usesSignalsInScript,NM as userComponentFileExists,cM as useVirtualList,jA as useTitle,ex as useStoreOrThrow,Wf as useStore,Sl as useStorage,eh as useSlots,Tl as useSessionStorage,EA as useSeoMeta,ld as useRouteParams,rx as useRouteParamOrThrow,dd as useRouteParam,jA as usePageTitle,YT as useOptimistic,nx as useMiddlewareValue,ud as useMiddlewareState,kl as useLocalStorage,Pf as useLoadingIndicator,TA as useHead,Rg as useForm,rh as useAttrs,Mc as uploadFiles,Oo as uploadFile,Xy as updateInstance,XT as untrack,QT as unregisterDirective,Jy as unmountInstance,A_ as unescapeHtml,p0 as typecheckStxFiles,FM as transpileTypeScript,qo as translate,LC as transitionDirective,uD as toUsers,dD as toUser,Zi as thumbnail,Qr as thumbHashToRGBA,Ec as thumbHashToDataURL,vR as templateCache,Ds as stxClientHelpers,zE as structuredDataDirective,il as stripLocalePrefix,Ur as stripDocumentWrapper,dC as stripCommentsAndLiterals,_w as stringToStream,sA as strictCspPreset,Cj as streamingSuspenseDirective,jj as streamToResponse,kj as streamTemplateSimple,xj as streamTemplate,Ht as stopHmrServer,aD as stopBroadcasting,mC as stateDirName,ke as stateDir,Ko as state,mR as startsDocument,Av as startProductionServer,tv as startInteractive,iD as startBroadcasting,WC as staggerDirective,ya as srcsetUrls,VC as springDirective,U_ as splitByPipe,u0 as sourcePathFor,ic as smartBatchSign,zM as slotContentHasExpressions,Jr as signUrl,LM as shouldTranspileTypeScript,jr as shouldReloadOnChange,jo as shouldRefreshSignature,Rr as shouldIgnoreFile,eM as shouldCacheComponent,ra as sharpen,Tg as shape,fC as setStateDir,ax as setRouteParams,cx as setMiddlewareState,Lo as setGlobalProvide,aE as setErrorLocale,My as setCurrentInstance,_m as setCachedVideoResult,$m as setCachedImageResult,gm as setCached,$u as serveStxFile,ku as serveMultipleStxFiles,Kn as serveMarkdownFile,Qv as serveFile,Eu as serveApp,bf as serve,Of as serializeState,oa as sepia,_A as seoMetaToHeadConfig,FC as scrollAnimateDirective,RC as screenReaderDirective,YE as scopeHTML,JE as scopeCSS,WE as scanForSitemapEntries,TC as scanA11yTargets,CC as scanA11yIssues,ca as saturation,wa as sanitizeParams,ME as sanitizeFilePath,DE as sanitizeExpression,PE as sanitizeDirectiveParams,RE as sanitizeDirectiveParam,OE as sanitizeComponentProps,Qn as safeExecuteAsync,EE as safeExecute,Hj as runPreProcessingMiddleware,Wj as runPostProcessingMiddleware,ui as runPageAction,UT as runMountCallbacks,Vn as runMiddleware,xt as runHooks,Sh as runDoctor,HT as runDestroyCallbacks,Ag as runComposers,la as rotate,Jl as rewriteImagesWithSiblings,HM as resolveTemplatePath,yC as resolveStxTargets,s_ as resolveStxDirectories,fn as resolveI18n,Ki as resize,h_ as resetPlaceholders,Tu as resetHead,C0 as resetHMRHandler,xE as resetErrorConfig,wg as required,go as replacePlaceholders,Ic as renderView,Lm as renderVideoComponent,l_ as renderVendorStyleTags,Pt as renderToString,dh as renderToStream,sr as renderToDOM,Cc as renderThumbhashToCanvas,on as renderTemplateString,oS as renderTemplate,sS as renderString,vj as renderStreamingPage,MM as renderSlot,WR as renderSSRSuspense,pc as renderProtectedVideo,uc as renderProtectedImg,sc as renderMediaUpload,zo as renderMarkdownView,Kc as renderLayoutTypes,Qa as renderImgComponent,jl as renderImageComponent,MA as renderHtmlAttrs,RA as renderHead,B$ as renderEmail,ws as renderComponentWithSlot,DA as renderBodyAttrs,F0 as render,aA as relaxedCspPreset,HA as registerValidationRule,_j as registerStreamingDirectives,Xf as registerStoresClient,sx as registerStore,UE as registerSeoDirectives,id as registerMiddleware,v_ as registerFilters,w_ as registerFilter,lE as registerErrorMessages,JA as registerEnhancedValidationRule,KT as registerDirective,gA as registerCspDirectives,jx as registerComponentDirectives,KC as registerAnimationDirectives,MC as registerA11yDirectives,Oy as ref,Iw as redirect,hC as rebaseOntoStateDir,$e as readMarkdownFile,$R as readFileCached,Zl as reactive,fa as quality,lc as pruneSignatureCache,bm as pruneCache,Xm as provide,Vc as protectCodeBlocks,bg as prop,qj as processVueTemplate,iM as processVirtualListDirectives,dM as processVirtualGridDirectives,Im as processVideo,qA as processValidateDirective,gj as processTranslateDirective,FR as processTransitionDirectives,zR as processTransitionAttributes,IA as processTitleDirective,M_ as processTemplateBindings,PR as processTeleportDirectives,UR as processSuspenseDirectives,LE as processStructuredData,$j as processStreamDirectives,SM as processStaticDirectives,zj as processStackReplacements,Bj as processStackPushDirectives,DM as processSlots,oo as processShell,qg as processServerBindings,FE as processSeoDirective,Aj as processSectionDirectives,Yj as processScopedStyles,j_ as processReactiveBindings,fc as processProtectedMedia,gM as processPartialHydrationDirectives,RR as processOnceDirective,Uj as processMiddleware,IE as processMetaDirectives,LA as processMetaDirective,L_ as processMarkdownFileDirectives,sE as processMarkdownDirectives,Ij as processLoops,ZR as processKeepAliveDirectives,jR as processJsonDirective,lM as processInfiniteListDirectives,Nj as processIncludes,tc as processImgComponents,Pl as processImageComponents,qe as processImage,OA as processHeadDirective,NA as processForms,zA as processFormInputDirectives,po as processExpressions,aC as processEventDirectives,UA as processErrorDirective,Xj as processDynamicComponents,se as processDirectives,nC as processDirectiveAttributes,DR as processDeferDirectives,vA as processCustomDirectives,fA as processCspDirectives,Cg as processComponentProps,sn as processClientScript,BA as processBasicFormDirectives,XR as processAsyncDirectives,$A as processAppearanceBootstrapDirective,zC as processAnimationDirectives,wC as processA11yDirectives,sj as preloadTranslationsBackground,oj as preloadTranslations,y0 as preloadIslandHandlers,Vg as preloadIconCollection,_d as poolStrings,Fg as pluginManager,LR as performLeave,IR as performEnter,WT as pendingLifecycleCounts,JT as peek,at as partialsCache,Fm as parseVideoDirectiveOptions,Yi as parseUrl,_c as parseThumbhashString,J_ as parseSwitchBlock,jM as parseSlots,RM as parseSlotElement,Q_ as parseScriptDeclarations,r_ as parseSFCComponent,mc as parseProtectedArgs,Oj as parseLoopBinding,ec as parseImgComponent,Pa as parseImageUrl,rs as parseImageComponent,Ep as parseFormBody,K_ as parseExpressionWithFilters,Dw as parseCookies,Au as parseContainerSelector,V_ as parseConditionalBlock,G_ as parseArguments,JC as parseAnimationShorthand,vg as optional,Ad as optimizeTemplate,ls as optimizeImage,Wl as optimizeDirectory,Sg as oneOf,Lj as onceStore,Hy as onUpdated,Wg as onUpdate,Vy as onUnmounted,dx as onServer,zy as onMounted,BT as onMount,$M as onHydrated,Zm as onErrorCaptured,zT as onDestroy,oM as onDeactivated,lx as onClient,Uy as onBeforeUpdate,Wy as onBeforeUnmount,By as onBeforeMount,nM as onActivated,Sc as observeElement,Lw as notFound,Qj as normalizeCriticalHeadOrder,Gm as nextTick,lu as negotiateEncoding,ed as navigateTo,qy as mountInstance,BC as motionDirective,iA as moderateCspPreset,Ed as minifyHtml,BE as metaDirective,aR as metaDedupKey,Co as mergeParams,lR as mergeHtmlAttrs,CA as mergeHeadConfigs,dA as mergeCspDirectives,Bg as mergeCrosswindConfig,ro as matchRoute,iE as markdownDirectiveHandler,I_ as markdownCache,gC as looksLikeGlob,rt as localizePath,ij as loadTranslationLazy,pj as loadTranslation,it as loadStxConfig,Un as loadMiddlewareFromDirectory,xi as loadManifest,Qe as loadElement,cD as loadChannels,fg as lintStxStrict,vc as lazyLoadAll,wc as lazyLoad,HC as keyframeDirective,ah as jsxs,ch as jsxDEV,It as jsx,Ow as jsonResponse,Ej as islandDirective,hE as isTest,Ws as isSpaNavigation,_o as isSignatureValid,VT as isSignal,Pn as isSharpAvailable,Tw as isServerEnvironment,pd as isServer,mE as isProduction,xC as isPresentationalRole,Ro as isNativeLazySupported,Bo as isMarkdownPath,rj as isLoading,nj as isLoaded,IM as isJavaScriptScript,Mo as isIntersectionObserverSupported,mr as isImageFile,Ve as isImageBackendAvailable,mj as isICUFormat,vM as isHydrated,BM as isHydrateTrigger,kw as isEdgeEnvironment,mg as isDirectiveKind,Rs as isDevelopment,qT as isDerived,Ar as isCssOnlyChange,au as isCompressible,fd as isClient,YR as isAsyncComponent,fo as isActionableMethod,sa as invert,kR as invalidateFileCacheByDir,SR as invalidateFileCache,E_ as interpolateScriptsInTemplate,T_ as interpolateScriptExpressions,C_ as interpolateScriptAttributes,vr as inlineError,pn as injectThemeBootstrap,NE as injectSeoTags,ln as injectSeo,Fr as injectRouterScript,Be as injectHotReload,tE as injectHeatmap,uA as injectCspMetaTag,re as injectCrosswindCSS,gR as injectConfigHeadTags,Zj as injectColorModeBootScript,uR as injectCloakStyle,nR as injectBuildId,u_ as injectBrowserCoreAutoImports,P_ as injectAnalytics,Jm as inject,ox as initStoreRegistry,dy as initNetlify,b0 as initLoadingIndicator,bc as initLazyLoading,Yw as initFile,Do as initBlurUp,jc as initAllBlurUp,nc as imgDirective,Nl as imageDirective,hi as hydrateTemplateStream,yv as hydrateTemplate,g0 as hydrateIslands,xM as hydrateIsland,Pp as hydrateFragment,bM as hydrateByStrategy,wM as hydrateAll,j0 as hydrate,Zv as htmlResponse,pR as hoistLeadingHeadTags,eR as hoistColorModeBootScript,rE as heatmapDirective,pm as hashString,AR as hashFilePath,dm as hashFile,um as hashBuffer,Vj as hasVueTemplateSyntax,Pj as hasVariables,zf as hasStore,Gt as hasPlaceholders,Rn as hasNetlifyConfig,cd as hasMiddleware,cC as hasEventDirectives,hR as hasDocumentShell,_M as hasDirectives,$C as hasDOMSupport,Yl as handleImageRequest,Qm as handleError,hh as h,pr as groupVariantsByFormat,na as grayscale,Rv as gitHash,$d as getUnusedDirectives,aj as getTranslationSync,ej as getTranslationCacheStats,cj as getTranslationAsync,hj as getTranslation,ot as getTotalSize,Ao as getTimeUntilExpiry,Xg as getStoreScript,Uf as getStoreNames,Xi as getStore,_l as getStorageSize,El as getStorageKeys,WM as getSourceLineInfo,vC as getScreenReaderOnlyStyle,KE as getScopeAttribute,xR as getRouteParams,Og as getPublicEnvDefine,Ig as getPublicEnv,CM as getPositionInfo,y_ as getPlaceholderRegistry,Za as getPlaceholderCacheStats,kA as getPageMeta,tA as getNonce,We as getMimeType,zn as getMiddlewareNames,ad as getMiddleware,tj as getLoadingState,dj as getLoadingLocales,ql as getImageMetadata,Ff as getHydrationRuntime,ix as getHydratedStoreState,Mr as getHmrServer,SA as getHead,T0 as getHMRHandler,Fa as getFormatExtension,mm as getFileMtime,ur as getFallbackVariant,uE as getErrorMessage,cE as getErrorLocale,yE as getErrorConfig,fE as getErrorCodeName,ZT as getDirectives,GT as getDirective,Dy as getCurrentInstance,lA as getCspPreset,xA as getCspHeaderName,zg as getCrosswindServeAsset,qM as getComponentCacheStats,Em as getCachedVideoResult,ac as getCachedSignature,CR as getCachedSignalsRuntime,ER as getCachedRouterScript,Ka as getCachedPlaceholder,vm as getCachedImageResult,hm as getCached,xm as getCacheStats,Us as getBuildId,sD as getBroadcastServer,La as getBestVariant,$_ as getAllFilters,Ta as generateWidthSrcset,aM as generateVirtualListCSS,Pc as generateVideoPreview,GA as generateValidationScript,rn as generateUploadRuntime,Sd as generateTreeShakenBundle,BR as generateTransitionRuntime,NR as generateTransitionCSS,Rm as generateThumbnails,Ha as generateThumbhashPlaceholder,Xu as generateTemplatesDocs,qR as generateSuspenseRuntime,VR as generateSuspenseCSS,If as generateStateScript,Oa as generateSrcsetData,Tm as generateSrcset,Bt as generateSrcSet,Mm as generateSpriteSheet,U$ as generateSpaShell,Ia as generateSourceTags,Ra as generateSizesFromBreakpoints,ja as generateSizesAttribute,dr as generateSizes,HE as generateSitemapIndex,dn as generateSitemap,tm as generateSimpleMediaPicker,Gr as generateSignatureRuntime,wR as generateSignalsRuntimeDev,bR as generateSignalsRuntime,m_ as generateServerDataBridge,XE as generateScopeId,n_ as generateSFCWebComponent,sC as generateRuntimeScript,GC as generateRouteTypes,ZC as generateRouteManifest,VE as generateRobotsTxt,un as generateRobots,km as generateResponsiveVariants,QE as generateReactiveWebComponentTS,ZE as generateReactiveWebComponent,t_ as generateReactiveRuntime,e_ as generateReactiveMixin,jm as generatePoster,Ya as generatePlaceholderStyle,Ja as generatePlaceholderCSS,Ua as generatePlaceholder,yM as generatePartialHydrationCSS,eA as generateNonce,An as generateNetlifyToml,lm as generateMinifiedMediaRuntime,Oc as generateMediaRuntime,em as generateMediaManagerEmbed,QM as generateManifest,v0 as generateLoadingIndicatorHtml,Zr as generateLazyLoadRuntime,wh as generateLayoutTypes,Va as generateLQIP,rM as generateKeepAliveRuntime,tM as generateKeepAliveCSS,kM as generateIslandManifest,Dc as generateImagePreview,ds as generateImageManifest,A0 as generateHydrationScript,Rj as generateHydrationRuntime,R0 as generateHydrationCSS,uM as generateHydrationBootstrap,wu as generateHotReloadScript,eE as generateHeatmapScript,S0 as generateHMRClientScript,Dm as generateHLSManifest,_0 as generateEventBindings,Aa as generateDprSrcsetWithVariableQuality,_a as generateDprSrcset,fR as generateDocumentShell,Zu as generateDocs,Ju as generateDirectivesDocs,rC as generateDirectiveRuntime,qE as generateDefaultRobotsTxt,Pm as generateDASHManifest,oA as generateCspMetaTag,nA as generateCspHeader,Hg as generateCrosswindCSS,oh as generateCompositionRuntime,qu as generateComponentsDocs,pM as generateComponentManifest,Vu as generateComponentDoc,Xa as generateColorPlaceholder,Gj as generateColorModeBootScript,Yy as generateClientRuntime,fm as generateCacheKey,f_ as generateBrowserAutoImportDestructuring,en as generateBlurUpRuntime,tn as generateBlurUpCSS,R_ as generateBindingsRuntime,Ca as generateAutoWidthSrcset,p_ as generateAutoImportDestructuring,GR as generateAsyncComponentRuntime,KR as generateAsyncComponentCSS,YC as generateAnimationRuntime,XC as generateAnimationCSS,D_ as generateAnalyticsScript,f0 as formatTypecheckDiagnostics,o0 as formatTypeErrors,mp as formatStxContent,gt as formatSize,Ns as formatRoutes,Ww as formatMarkdownContent,pE as formatLocalizedError,fj as formatICU,bE as formatFilePath,kE as formatError,kh as formatDoctorReport,Yu as formatDocsAsMarkdown,Gu as formatDocsAsJson,Ku as formatDocsAsHtml,pa as format,Cd as foldConstants,ua as flipVertical,da as flipHorizontal,JM as fingerprint,Ef as findRuntimeTypeDeclarations,Zc as findPantryPackage,W_ as findMatchingEndTag,B_ as findMatchingDelimiter,lC as findInterpolationEnd,q_ as findIfBlocks,Y_ as findExpressions,Fs as findErrorPage,X_ as findDirectiveBlocks,kd as findDeadCode,kd as findDeadBranches,mw as findContainerRegion,Zs as findComponentFiles,Is as findCommonDir,_n as filterRequiredFiles,Vt as fileExists,te as extractVariables,Sf as extractTemplateExpressions,Sj as extractStreamBoundaries,Lf as extractState,PM as extractSlotContent,Dj as extractScriptFromTemplate,qr as extractScriptBlocks,x_ as extractPlaceholders,H_ as extractParenthesizedExpression,Nn as extractPageResponseStatus,Hr as extractLayoutMetadata,qa as extractDominantColor,Z_ as extractDirectiveParams,AM as extractDirectiveNames,Vs as extractContainerContent,Hu as extractComponentProps,fM as extractComponentName,Wu as extractComponentDescription,Ug as extractClassNames,Xc as extractBridgeData,mM as extractBoundProps,z_ as extractBalancedExpression,c_ as extractAndStripCssImports,GE as extractAndScopeStyles,iC as extractAndProcessEvents,Tn as externalizeSharedAssets,Yo as externalizeHtml,yo as evaluateExpression,qn as evaluateConstant,F_ as evaluateAuthExpression,Re as escapeHtml,_E as errorRecovery,Pr as errorLogger,OR as ensureTeleportTargets,yR as ensureDocumentShell,XA as enhancedValidationRules,Ru as enableDevTools,Td as eliminateDeadCode,Go as effect,xa as dprUrls,vw as docsCommand,Yc as discoverLayoutNames,kc as disconnectObserver,Mu as disableDevTools,Ms as devHelpers,Hs as detectShell,qt as detectRuntime,cr as detectProjectConfig,Na as detectFormat,wx as detectBuildMode,FT as derived,ly as deploy,i_ as defineStxConfig,Vf as defineStore,th as defineSlots,ml as defineSiteConfig,yg as definePropsWithValidation,gg as defineProps,Lg as definePlugin,AA as definePageMeta,rd as defineMiddleware,Mg as defineForm,Km as defineExpose,Ym as defineEmits,os as defineDirective,gh as defineCustomElement,uv as defineConfig,eC as defineClientDirective,JR as defineAsyncComponent,S$ as defaultMediaConfig,Sy as defaultImageConfig,ZA as defaultI18nConfig,QC as defaultHeatmapConfig,FA as defaultFormClasses,b_ as defaultFilters,wA as defaultCspConfig,Dt as defaultConfig,mk as default,Ng as deepMergeThemes,Jj as dedupeScopedStyles,Wa as decodeThumbhash,hA as cspNonceDirective,mA as cspDirective,Ac as crossfadeTransition,Gi as crop,sM as createVirtualList,Nm as createVideoDirective,Rw as createVercelHandler,Ai as createTypeChecker,yj as createTranslateFilter,Ew as createTextEncoderStream,Uc as createStxApp,Cw as createStreamingResponse,Tj as createStreamRenderer,Ji as createStore,sd as createStorageManager,nd as createServerCookieManager,Gl as createScope,HR as createSSRSuspense,no as createRouter,Hn as createRouteLocation,Ci as createRoute,Oy as createRef,Zl as createReactive,nh as createProvideContext,Fv as createProject,dv as createProductionBuild,g_ as createPlaceholder,Sx as createOptimizedBuild,Mw as createNetlifyHandler,Cn as createNetlifyClient,Wn as createMiddlewareContext,Ti as createMiddleware,$c as createLazyObserver,QR as createKeepAliveCache,ep as createKVNamespace,hM as createIslandRegistry,rc as createImgDirective,Bl as createImagePlugin,Kl as createImageHandler,is as createImageDirective,oE as createHeatmapAggregator,En as createFileManifest,Qu as createEnvAccessor,CE as createEnhancedError,Vr as createEdgeHandler,np as createEdgeCache,VM as createDetailedErrorMessage,jw as createDenoHandler,lr as createDefaultNetlifyConfig,bA as createCspHeaders,Pw as createCookie,Iy as createComputed,Py as createComponentInstance,Aw as createCloudflareHandler,od as createClientCookieManager,tC as createBuiltinDirectives,Uc as createApp,qC as createAnimationTimeline,ea as cover,Mj as convertToCommonJS,aa as contrast,Qi as contain,TE as consoleError,gE as configureErrorHandling,je as config,Iy as computed,wt as compressResponse,_g as composerPattern,Eg as composer,zr as composeShellWithPage,Md as componentDirective,UM as componentClientSignalNames,ZM as compileTemplate,ar as collectDeployFiles,Am as clearVideoCache,QA as clearTranslationCache,Jg as clearStoreCache,Cl as clearStorage,cc as clearSignatureCache,Ga as clearPlaceholderCache,Fj as clearOnceStore,rA as clearNonce,Bn as clearMiddleware,ss as clearImageCache,dE as clearErrorMessages,_R as clearDevCaches,S_ as clearCustomFilters,jg as clearComposers,Yg as clearComposableCache,ct as clearComponentCache,ym as clearCache,w0 as cleanupLoadingIndicator,XM as classifyScript,tl as classifyAllScripts,r0 as checkTemplateFile,n0 as checkTemplate,Ir as checkCache,or as checkAuthAccess,SC as checkA11yWithRegex,kC as checkA11y,oD as channel,Uw as captureScreenshots,fp as captureScreenshot,uj as cancelPendingLoads,es as calculateSha1,Ea as calculateOptimalWidths,Lr as cacheTemplate,Or as buildWebComponents,Tf as buildVirtualSource,zm as buildViews,W as buildUrl,bj as buildSuspenseResolveScript,fl as buildStaticSite,YM as buildRuntimeAsset,KM as buildRouterAsset,gn as buildLangPickerScript,Da as buildImageUrl,cR as buildHtmlAttrs,tD as buildForProduction,Px as buildComponentLibrary,Kr as buildAuthParams,gx as buildApp,hn as buildAlternateLinks,lv as build,pD as broadcastPrivate,fD as broadcastPresence,lD as broadcast,ia as brightness,ta as blur,Yr as batchSignUrls,NT as batch,_C as autoFixA11yFile,AC as autoFixA11yDirectory,EC as autoFixA11y,ma as auto,bC as attributeValue,GM as assetTags,oC as asInvocableStatement,kg as arrayOf,mn as applyTranslations,Sm as applyTransformations,OM as applySlots,Ax as applyPropDefaults,ga as applyPreset,dR as applyHtmlAttrs,PA as applyHead,__ as applyFilters,cA as apiCspPreset,NC as animationGroupDirective,Om as analyzeVideo,xs as analyzeUsage,md as analyzeTemplate,px as analyzeProject,xs as analyzeDirectiveUsage,O_ as analyticsDirective,zv as addStore,Bv as addPage,pA as addNonceToInlineContent,Uv as addLayout,Nv as addComponent,pi as actionRedirectResponse,td as abortNavigation,jC as a11yDirective,TR as __setSignalsGeneratorsForTest,rR as __setBuildIdForTest,Cm as VideoProcessorCache,Dg as Validator,DC as TransitionType,OC as TransitionEase,PC as TransitionDirection,N_ as Tokenizer,_i as TemplateTypeChecker,Jw as TEMPLATE_PRESETS,SE as StxValidationError,vE as StxSyntaxError,$E as StxSecurityError,Gn as StxRuntimeError,Zn as StxFileError,wE as StxError,ph as Show,wj as SUSPENSE_RESOLVER_RUNTIME,d_ as STX_AUTO_IMPORTS,pC as STATE_DIR_ENV_VAR,UC as SPRING_PRESETS,ho as ProductionBuild,mh as Portal,Lv as PROJECT_TEMPLATES,Eo as PRESETS,Nf as MemorySessionStore,ka as MIME_TYPES,va as MEDIA_DEFAULT_WIDTHS,Sa as MEDIA_DEFAULT_FORMATS,Jc as LAYOUT_TYPES_FILE,wm as ImageProcessorCache,Xl as ImageProcessingError,Wi as HydrationRuntime,js as HotReloadServer,nE as HeatmapAggregator,iR as HTML_CLASS_MARKER,sR as HTML_ATTRS_MARKER,Ot as Fragment,fh as For,AE as ErrorLogger,wr as ErrorCodes,kn as EXTERNALIZED_ASSET_DIR,st as DeployError,Ie as DEFAULT_WIDTHS,IC as DEFAULT_TRANSITION_OPTIONS,uC as DEFAULT_STATE_DIR,Fe as DEFAULT_QUALITY,Ba as DEFAULT_PLACEHOLDER_OPTIONS,Le as DEFAULT_FORMATS,$a as DEFAULT_DPR_VALUES,Ui as ComponentHMRHandler,Ma as COMMON_SIZES,nl as COLOR_MODE_BOOT_MARKER,Kj as COLOR_MODE_BOOT_GLOBAL,oR as CLOAK_STYLE,rD as BroadcastServer,nD as Broadcast,tR as BUILD_ID_META,zs as BUILD_ID_HEADER,za as BLUR_UP_CSS,vh as $path};
4540
+ ${c}`)}return{props:i,validation:a}}function bg(e,t){let r={...e};for(let[n,o]of Object.entries(t))if(r[n]===void 0)r[n]=typeof o==="function"?o():o;return r}function wg(e){return e}function vg(e){return{type:e,required:!0}}function $g(e,t){return{type:t,default:e}}function Sg(e,t={}){return{...t,validator:e}}function kg(e,t={}){return{...t,validator:(r)=>e.includes(r)}}function Tg(e,t={}){return{...t,type:Array,validator:(r)=>{if(!Array.isArray(r))return!1;return!0}}}function Cg(e,t={}){return{...t,type:Object}}function Eg(e,t,r){if(!t)return e;let n={};for(let[o,s]of Object.entries(t)){let i=typeof s==="function"||Array.isArray(s)?{type:s}:s||{},a=e[o];if(a===void 0&&i.default!==void 0)a=typeof i.default==="function"?i.default():i.default;{let c=xl(o,a,i,r);if(c)console.warn(c.message)}n[o]=a}for(let[o,s]of Object.entries(e))if(!(o in n))n[o]=s;return n}var hk={};export{$h as $path,Ua as BLUR_UP_CSS,Us as BUILD_ID_HEADER,rR as BUILD_ID_META,oD as Broadcast,nD as BroadcastServer,sR as CLOAK_STYLE,Gj as COLOR_MODE_BOOT_GLOBAL,ol as COLOR_MODE_BOOT_MARKER,Da as COMMON_SIZES,Hi as ComponentHMRHandler,Sa as DEFAULT_DPR_VALUES,Fe as DEFAULT_FORMATS,za as DEFAULT_PLACEHOLDER_OPTIONS,Ne as DEFAULT_QUALITY,pC as DEFAULT_STATE_DIR,LC as DEFAULT_TRANSITION_OPTIONS,Le as DEFAULT_WIDTHS,it as DeployError,Tn as EXTERNALIZED_ASSET_DIR,vr as ErrorCodes,jE as ErrorLogger,mh as For,It as Fragment,iR as HTML_ATTRS_MARKER,aR as HTML_CLASS_MARKER,oE as HeatmapAggregator,Rs as HotReloadServer,Vi as HydrationRuntime,Jl as ImageProcessingError,vm as ImageProcessorCache,Yc as LAYOUT_TYPES_FILE,ka as MEDIA_DEFAULT_FORMATS,$a as MEDIA_DEFAULT_WIDTHS,Ta as MIME_TYPES,Bf as MemorySessionStore,_o as PRESETS,Fv as PROJECT_TEMPLATES,hh as Portal,go as ProductionBuild,HC as SPRING_PRESETS,fC as STATE_DIR_ENV_VAR,u_ as STX_AUTO_IMPORTS,vj as SUSPENSE_RESOLVER_RUNTIME,fh as Show,vE as StxError,Qn as StxFileError,Zn as StxRuntimeError,SE as StxSecurityError,$E as StxSyntaxError,kE as StxValidationError,Yw as TEMPLATE_PRESETS,Ai as TemplateTypeChecker,B_ as Tokenizer,OC as TransitionDirection,IC as TransitionEase,PC as TransitionType,Pg as Validator,Em as VideoProcessorCache,nR as __setBuildIdForTest,CR as __setSignalsGeneratorsForTest,RC as a11yDirective,rd as abortNavigation,fi as actionRedirectResponse,Bv as addComponent,Hv as addLayout,fA as addNonceToInlineContent,zv as addPage,Uv as addStore,I_ as analyticsDirective,bs as analyzeDirectiveUsage,fx as analyzeProject,hd as analyzeTemplate,bs as analyzeUsage,Im as analyzeVideo,BC as animationGroupDirective,lA as apiCspPreset,A_ as applyFilters,OA as applyHead,uR as applyHtmlAttrs,ya as applyPreset,jx as applyPropDefaults,IM as applySlots,km as applyTransformations,hn as applyTranslations,Tg as arrayOf,sC as asInvocableStatement,ZM as assetTags,wC as attributeValue,ha as auto,_C as autoFixA11y,jC as autoFixA11yDirectory,AC as autoFixA11yFile,BT as batch,Kr as batchSignUrls,ra as blur,aa as brightness,dD as broadcast,mD as broadcastPresence,fD as broadcastPrivate,dv as build,gn as buildAlternateLinks,yx as buildApp,Gr as buildAuthParams,Ox as buildComponentLibrary,rD as buildForProduction,lR as buildHtmlAttrs,Pa as buildImageUrl,yn as buildLangPickerScript,GM as buildRouterAsset,KM as buildRuntimeAsset,ml as buildStaticSite,wj as buildSuspenseResolveScript,V as buildUrl,Um as buildViews,Cf as buildVirtualSource,Ir as buildWebComponents,Fr as cacheTemplate,_a as calculateOptimalWidths,ts as calculateSha1,pj as cancelPendingLoads,mp as captureScreenshot,Hw as captureScreenshots,sD as channel,TC as checkA11y,kC as checkA11yWithRegex,sr as checkAuthAccess,Lr as checkCache,o0 as checkTemplate,n0 as checkTemplateFile,rl as classifyAllScripts,JM as classifyScript,v0 as cleanupLoadingIndicator,xm as clearCache,lt as clearComponentCache,Kg as clearComposableCache,Rg as clearComposers,k_ as clearCustomFilters,AR as clearDevCaches,uE as clearErrorMessages,is as clearImageCache,zn as clearMiddleware,nA as clearNonce,Nj as clearOnceStore,Za as clearPlaceholderCache,lc as clearSignatureCache,El as clearStorage,Yg as clearStoreCache,ej as clearTranslationCache,jm as clearVideoCache,cr as collectDeployFiles,QM as compileTemplate,HM as componentClientSignalNames,Dd as componentDirective,Ur as composeShellWithPage,_g as composer,Ag as composerPattern,vt as compressResponse,Ly as computed,Re as config,yE as configureErrorHandling,CE as consoleError,ea as contain,ca as contrast,Dj as convertToCommonJS,ta as cover,XC as createAnimationTimeline,Hc as createApp,rC as createBuiltinDirectives,sd as createClientCookieManager,jw as createCloudflareHandler,Oy as createComponentInstance,Ly as createComputed,Ow as createCookie,wA as createCspHeaders,dr as createDefaultNetlifyConfig,Rw as createDenoHandler,qM as createDetailedErrorMessage,op as createEdgeCache,qr as createEdgeHandler,EE as createEnhancedError,ep as createEnvAccessor,_n as createFileManifest,sE as createHeatmapAggregator,as as createImageDirective,Gl as createImageHandler,zl as createImagePlugin,nc as createImgDirective,gM as createIslandRegistry,tp as createKVNamespace,eM as createKeepAliveCache,Sc as createLazyObserver,Ci as createMiddleware,Vn as createMiddlewareContext,En as createNetlifyClient,Dw as createNetlifyHandler,kx as createOptimizedBuild,y_ as createPlaceholder,uv as createProductionBuild,Nv as createProject,oh as createProvideContext,Ql as createReactive,Iy as createRef,Ei as createRoute,Wn as createRouteLocation,oo as createRouter,WR as createSSRSuspense,Zl as createScope,od as createServerCookieManager,id as createStorageManager,Yi as createStore,Cj as createStreamRenderer,Ew as createStreamingResponse,Hc as createStxApp,_w as createTextEncoderStream,xj as createTranslateFilter,ji as createTypeChecker,Mw as createVercelHandler,Bm as createVideoDirective,iM as createVirtualList,Zi as crop,jc as crossfadeTransition,hA as cspDirective,gA as cspNonceDirective,Va as decodeThumbhash,Yj as dedupeScopedStyles,Bg as deepMergeThemes,hk as default,Pt as defaultConfig,vA as defaultCspConfig,w_ as defaultFilters,NA as defaultFormClasses,eE as defaultHeatmapConfig,QA as defaultI18nConfig,ky as defaultImageConfig,k$ as defaultMediaConfig,YR as defineAsyncComponent,tC as defineClientDirective,pv as defineConfig,yh as defineCustomElement,ss as defineDirective,Km as defineEmits,Gm as defineExpose,Dg as defineForm,nd as defineMiddleware,jA as definePageMeta,Fg as definePlugin,yg as defineProps,xg as definePropsWithValidation,hl as defineSiteConfig,rh as defineSlots,qf as defineStore,a_ as defineStxConfig,dy as deploy,NT as derived,vx as detectBuildMode,Ba as detectFormat,lr as detectProjectConfig,Xt as detectRuntime,Ws as detectShell,Ds as devHelpers,Du as disableDevTools,Tc as disconnectObserver,Kc as discoverLayoutNames,$w as docsCommand,ba as dprUrls,Zo as effect,Cd as eliminateDeadCode,Mu as enableDevTools,JA as enhancedValidationRules,xR as ensureDocumentShell,IR as ensureTeleportTargets,Or as errorLogger,AE as errorRecovery,Me as escapeHtml,N_ as evaluateAuthExpression,Xn as evaluateConstant,xo as evaluateExpression,Ko as externalizeHtml,Cn as externalizeSharedAssets,aC as extractAndProcessEvents,ZE as extractAndScopeStyles,l_ as extractAndStripCssImports,U_ as extractBalancedExpression,hM as extractBoundProps,Jc as extractBridgeData,Hg as extractClassNames,Vu as extractComponentDescription,mM as extractComponentName,Wu as extractComponentProps,qs as extractContainerContent,jM as extractDirectiveNames,Q_ as extractDirectiveParams,Xa as extractDominantColor,Wr as extractLayoutMetadata,Bn as extractPageResponseStatus,W_ as extractParenthesizedExpression,b_ as extractPlaceholders,Xr as extractScriptBlocks,Pj as extractScriptFromTemplate,OM as extractSlotContent,Ff as extractState,kj as extractStreamBoundaries,kf as extractTemplateExpressions,re as extractVariables,qt as fileExists,An as filterRequiredFiles,Ls as findCommonDir,Qs as findComponentFiles,hw as findContainerRegion,Td as findDeadBranches,Td as findDeadCode,J_ as findDirectiveBlocks,Ns as findErrorPage,K_ as findExpressions,X_ as findIfBlocks,dC as findInterpolationEnd,z_ as findMatchingDelimiter,V_ as findMatchingEndTag,Qc as findPantryPackage,_f as findRuntimeTypeDeclarations,YM as fingerprint,ua as flipHorizontal,pa as flipVertical,Ed as foldConstants,fa as format,Gu as formatDocsAsHtml,Zu as formatDocsAsJson,Ku as formatDocsAsMarkdown,Th as formatDoctorReport,TE as formatError,wE as formatFilePath,mj as formatICU,fE as formatLocalizedError,Vw as formatMarkdownContent,Bs as formatRoutes,yt as formatSize,hp as formatStxContent,s0 as formatTypeErrors,m0 as formatTypecheckDiagnostics,P_ as generateAnalyticsScript,JC as generateAnimationCSS,KC as generateAnimationRuntime,GR as generateAsyncComponentCSS,ZR as generateAsyncComponentRuntime,f_ as generateAutoImportDestructuring,Ea as generateAutoWidthSrcset,M_ as generateBindingsRuntime,rn as generateBlurUpCSS,tn as generateBlurUpRuntime,m_ as generateBrowserAutoImportDestructuring,mm as generateCacheKey,Ky as generateClientRuntime,Zj as generateColorModeBootScript,Ja as generateColorPlaceholder,qu as generateComponentDoc,fM as generateComponentManifest,Xu as generateComponentsDocs,sh as generateCompositionRuntime,Wg as generateCrosswindCSS,oA as generateCspHeader,sA as generateCspMetaTag,Om as generateDASHManifest,XE as generateDefaultRobotsTxt,nC as generateDirectiveRuntime,Yu as generateDirectivesDocs,Qu as generateDocs,mR as generateDocumentShell,Aa as generateDprSrcset,ja as generateDprSrcsetWithVariableQuality,A0 as generateEventBindings,Pm as generateHLSManifest,k0 as generateHMRClientScript,tE as generateHeatmapScript,vu as generateHotReloadScript,pM as generateHydrationBootstrap,M0 as generateHydrationCSS,Mj as generateHydrationRuntime,j0 as generateHydrationScript,us as generateImageManifest,Pc as generateImagePreview,TM as generateIslandManifest,rM as generateKeepAliveCSS,nM as generateKeepAliveRuntime,qa as generateLQIP,vh as generateLayoutTypes,Qr as generateLazyLoadRuntime,$0 as generateLoadingIndicatorHtml,eD as generateManifest,tm as generateMediaManagerEmbed,Ic as generateMediaRuntime,dm as generateMinifiedMediaRuntime,jn as generateNetlifyToml,tA as generateNonce,xM as generatePartialHydrationCSS,Ha as generatePlaceholder,Ya as generatePlaceholderCSS,Ka as generatePlaceholderStyle,Rm as generatePoster,t_ as generateReactiveMixin,r_ as generateReactiveRuntime,QE as generateReactiveWebComponent,e_ as generateReactiveWebComponentTS,Tm as generateResponsiveVariants,pn as generateRobots,qE as generateRobotsTxt,QC as generateRouteManifest,ZC as generateRouteTypes,iC as generateRuntimeScript,o_ as generateSFCWebComponent,JE as generateScopeId,h_ as generateServerDataBridge,wR as generateSignalsRuntime,vR as generateSignalsRuntimeDev,Zr as generateSignatureRuntime,rm as generateSimpleMediaPicker,un as generateSitemap,WE as generateSitemapIndex,ur as generateSizes,Ra as generateSizesAttribute,Ma as generateSizesFromBreakpoints,La as generateSourceTags,H$ as generateSpaShell,Dm as generateSpriteSheet,zt as generateSrcSet,Cm as generateSrcset,Ia as generateSrcsetData,Lf as generateStateScript,qR as generateSuspenseCSS,XR as generateSuspenseRuntime,Ju as generateTemplatesDocs,Wa as generateThumbhashPlaceholder,Mm as generateThumbnails,BR as generateTransitionCSS,zR as generateTransitionRuntime,kd as generateTreeShakenBundle,nn as generateUploadRuntime,ZA as generateValidationScript,Oc as generateVideoPreview,cM as generateVirtualListCSS,Ca as generateWidthSrcset,S_ as getAllFilters,Fa as getBestVariant,iD as getBroadcastServer,Hs as getBuildId,bm as getCacheStats,gm as getCached,$m as getCachedImageResult,Ga as getCachedPlaceholder,_R as getCachedRouterScript,ER as getCachedSignalsRuntime,cc as getCachedSignature,_m as getCachedVideoResult,XM as getComponentCacheStats,Ug as getCrosswindServeAsset,bA as getCspHeaderName,dA as getCspPreset,Py as getCurrentInstance,ZT as getDirective,QT as getDirectives,mE as getErrorCodeName,xE as getErrorConfig,lE as getErrorLocale,pE as getErrorMessage,pr as getFallbackVariant,hm as getFileMtime,Na as getFormatExtension,C0 as getHMRHandler,kA as getHead,Dr as getHmrServer,ax as getHydratedStoreState,Nf as getHydrationRuntime,Xl as getImageMetadata,uj as getLoadingLocales,rj as getLoadingState,cd as getMiddleware,Un as getMiddlewareNames,Ve as getMimeType,rA as getNonce,TA as getPageMeta,Qa as getPlaceholderCacheStats,x_ as getPlaceholderRegistry,EM as getPositionInfo,Lg as getPublicEnv,Ig as getPublicEnvDefine,bR as getRouteParams,GE as getScopeAttribute,$C as getScreenReaderOnlyStyle,VM as getSourceLineInfo,_l as getStorageKeys,Al as getStorageSize,Ji as getStore,Hf as getStoreNames,Jg as getStoreScript,jo as getTimeUntilExpiry,st as getTotalSize,gj as getTranslation,lj as getTranslationAsync,tj as getTranslationCacheStats,cj as getTranslationSync,Sd as getUnusedDirectives,Mv as gitHash,oa as grayscale,fr as groupVariantsByFormat,gh as h,eh as handleError,Kl as handleImageRequest,SC as hasDOMSupport,AM as hasDirectives,gR as hasDocumentShell,lC as hasEventDirectives,ld as hasMiddleware,Mn as hasNetlifyConfig,Zt as hasPlaceholders,Uf as hasStore,Oj as hasVariables,qj as hasVueTemplateSyntax,pm as hashBuffer,um as hashFile,jR as hashFilePath,fm as hashString,nE as heatmapDirective,tR as hoistColorModeBootScript,fR as hoistLeadingHeadTags,Qv as htmlResponse,R0 as hydrate,vM as hydrateAll,wM as hydrateByStrategy,Op as hydrateFragment,bM as hydrateIsland,y0 as hydrateIslands,xv as hydrateTemplate,gi as hydrateTemplateStream,Bl as imageDirective,oc as imgDirective,Rc as initAllBlurUp,Po as initBlurUp,Kw as initFile,wc as initLazyLoading,w0 as initLoadingIndicator,uy as initNetlify,sx as initStoreRegistry,Ym as inject,O_ as injectAnalytics,p_ as injectBrowserCoreAutoImports,oR as injectBuildId,pR as injectCloakStyle,Qj as injectColorModeBootScript,yR as injectConfigHeadTags,ne as injectCrosswindCSS,pA as injectCspMetaTag,rE as injectHeatmap,ze as injectHotReload,Nr as injectRouterScript,dn as injectSeo,BE as injectSeoTags,fn as injectThemeBootstrap,$r as inlineError,E_ as interpolateScriptAttributes,C_ as interpolateScriptExpressions,__ as interpolateScriptsInTemplate,kR as invalidateFileCache,TR as invalidateFileCacheByDir,ia as invert,mo as isActionableMethod,KR as isAsyncComponent,md as isClient,cu as isCompressible,jr as isCssOnlyChange,XT as isDerived,Ms as isDevelopment,hg as isDirectiveKind,Tw as isEdgeEnvironment,zM as isHydrateTrigger,$M as isHydrated,hj as isICUFormat,qe as isImageBackendAvailable,hr as isImageFile,Do as isIntersectionObserverSupported,LM as isJavaScriptScript,oj as isLoaded,nj as isLoading,zo as isMarkdownPath,Mo as isNativeLazySupported,bC as isPresentationalRole,hE as isProduction,fd as isServer,Cw as isServerEnvironment,On as isSharpAvailable,qT as isSignal,Ao as isSignatureValid,Vs as isSpaNavigation,gE as isTest,_j as islandDirective,Iw as jsonResponse,Lt as jsx,lh as jsxDEV,ch as jsxs,WC as keyframeDirective,vc as lazyLoad,$c as lazyLoadAll,mg as lintStxStrict,lD as loadChannels,et as loadElement,bi as loadManifest,Hn as loadMiddlewareFromDirectory,at as loadStxConfig,fj as loadTranslation,aj as loadTranslationLazy,nt as localizePath,yC as looksLikeGlob,L_ as markdownCache,aE as markdownDirectiveHandler,no as matchRoute,zg as mergeCrosswindConfig,uA as mergeCspDirectives,EA as mergeHeadConfigs,dR as mergeHtmlAttrs,Eo as mergeParams,cR as metaDedupKey,zE as metaDirective,_d as minifyHtml,aA as moderateCspPreset,zC as motionDirective,Xy as mountInstance,td as navigateTo,du as negotiateEncoding,Zm as nextTick,eR as normalizeCriticalHeadOrder,Fw as notFound,kc as observeElement,oM as onActivated,zy as onBeforeMount,Vy as onBeforeUnmount,Hy as onBeforeUpdate,dx as onClient,sM as onDeactivated,UT as onDestroy,Qm as onErrorCaptured,SM as onHydrated,zT as onMount,Uy as onMounted,ux as onServer,qy as onUnmounted,Vg as onUpdate,Wy as onUpdated,Fj as onceStore,kg as oneOf,Vl as optimizeDirectory,ds as optimizeImage,jd as optimizeTemplate,$g as optional,YC as parseAnimationShorthand,Z_ as parseArguments,q_ as parseConditionalBlock,ju as parseContainerSelector,Pw as parseCookies,G_ as parseExpressionWithFilters,_p as parseFormBody,ns as parseImageComponent,Oa as parseImageUrl,tc as parseImgComponent,Ij as parseLoopBinding,hc as parseProtectedArgs,n_ as parseSFCComponent,eA as parseScriptDeclarations,MM as parseSlotElement,RM as parseSlots,Y_ as parseSwitchBlock,Ac as parseThumbhashString,Ki as parseUrl,Nm as parseVideoDirectiveOptions,ct as partialsCache,YT as peek,VT as pendingLifecycleCounts,LR as performEnter,FR as performLeave,Ng as pluginManager,Ad as poolStrings,qg as preloadIconCollection,x0 as preloadIslandHandlers,sj as preloadTranslations,ij as preloadTranslationsBackground,vC as processA11yDirectives,UC as processAnimationDirectives,SA as processAppearanceBootstrapDirective,JR as processAsyncDirectives,zA as processBasicFormDirectives,an as processClientScript,Eg as processComponentProps,mA as processCspDirectives,$A as processCustomDirectives,PR as processDeferDirectives,oC as processDirectiveAttributes,ie as processDirectives,Jj as processDynamicComponents,HA as processErrorDirective,cC as processEventDirectives,fo as processExpressions,UA as processFormInputDirectives,BA as processForms,IA as processHeadDirective,Xe as processImage,Ol as processImageComponents,rc as processImgComponents,Bj as processIncludes,dM as processInfiniteListDirectives,RR as processJsonDirective,QR as processKeepAliveDirectives,Lj as processLoops,iE as processMarkdownDirectives,F_ as processMarkdownFileDirectives,FA as processMetaDirective,LE as processMetaDirectives,Hj as processMiddleware,MR as processOnceDirective,yM as processPartialHydrationDirectives,mc as processProtectedMedia,R_ as processReactiveBindings,Kj as processScopedStyles,jj as processSectionDirectives,NE as processSeoDirective,Xg as processServerBindings,so as processShell,PM as processSlots,zj as processStackPushDirectives,Uj as processStackReplacements,kM as processStaticDirectives,Sj as processStreamDirectives,FE as processStructuredData,HR as processSuspenseDirectives,OR as processTeleportDirectives,D_ as processTemplateBindings,LA as processTitleDirective,UR as processTransitionAttributes,NR as processTransitionDirectives,yj as processTranslateDirective,XA as processValidateDirective,Lm as processVideo,uM as processVirtualGridDirectives,aM as processVirtualListDirectives,Xj as processVueTemplate,wg as prop,qc as protectCodeBlocks,Jm as provide,wm as pruneCache,dc as pruneSignatureCache,ma as quality,Ql as reactive,SR as readFileCached,Se as readMarkdownFile,gC as rebaseOntoStateDir,Lw as redirect,Iy as ref,DC as registerA11yDirectives,GC as registerAnimationDirectives,Rx as registerComponentDirectives,yA as registerCspDirectives,GT as registerDirective,YA as registerEnhancedValidationRule,dE as registerErrorMessages,v_ as registerFilter,$_ as registerFilters,ad as registerMiddleware,HE as registerSeoDirectives,ix as registerStore,Jf as registerStoresClient,Aj as registerStreamingDirectives,WA as registerValidationRule,cA as relaxedCspPreset,N0 as render,PA as renderBodyAttrs,vs as renderComponentWithSlot,z$ as renderEmail,MA as renderHead,DA as renderHtmlAttrs,Rl as renderImageComponent,ec as renderImgComponent,Gc as renderLayoutTypes,Uo as renderMarkdownView,ic as renderMediaUpload,pc as renderProtectedImg,fc as renderProtectedVideo,VR as renderSSRSuspense,DM as renderSlot,$j as renderStreamingPage,iS as renderString,sS as renderTemplate,sn as renderTemplateString,Ec as renderThumbhashToCanvas,ir as renderToDOM,uh as renderToStream,Ot as renderToString,d_ as renderVendorStyleTags,Fm as renderVideoComponent,Lc as renderView,yo as replacePlaceholders,vg as required,bE as resetErrorConfig,E0 as resetHMRHandler,Cu as resetHead,g_ as resetPlaceholders,Gi as resize,mn as resolveI18n,i_ as resolveStxDirectories,xC as resolveStxTargets,WM as resolveTemplatePath,Yl as rewriteImagesWithSiblings,da as rotate,jg as runComposers,WT as runDestroyCallbacks,kh as runDoctor,bt as runHooks,qn as runMiddleware,HT as runMountCallbacks,pi as runPageAction,Vj as runPostProcessingMiddleware,Wj as runPreProcessingMiddleware,_E as safeExecute,eo as safeExecuteAsync,IE as sanitizeComponentProps,ME as sanitizeDirectiveParam,OE as sanitizeDirectiveParams,PE as sanitizeExpression,DE as sanitizeFilePath,va as sanitizeParams,la as saturation,EC as scanA11yIssues,CC as scanA11yTargets,VE as scanForSitemapEntries,YE as scopeCSS,KE as scopeHTML,MC as screenReaderDirective,NC as scrollAnimateDirective,AA as seoMetaToHeadConfig,sa as sepia,If as serializeState,wf as serve,_u as serveApp,e0 as serveFile,Gn as serveMarkdownFile,Tu as serveMultipleStxFiles,Su as serveStxFile,ym as setCached,Sm as setCachedImageResult,Am as setCachedVideoResult,Dy as setCurrentInstance,cE as setErrorLocale,Fo as setGlobalProvide,lx as setMiddlewareState,cx as setRouteParams,mC as setStateDir,Cg as shape,na as sharpen,tM as shouldCacheComponent,Mr as shouldIgnoreFile,Ro as shouldRefreshSignature,Rr as shouldReloadOnChange,FM as shouldTranspileTypeScript,Yr as signUrl,UM as slotContentHasExpressions,ac as smartBatchSign,p0 as sourcePathFor,H_ as splitByPipe,qC as springDirective,xa as srcsetUrls,VC as staggerDirective,aD as startBroadcasting,rv as startInteractive,jv as startProductionServer,hR as startsDocument,Go as state,Te as stateDir,hC as stateDirName,cD as stopBroadcasting,Wt as stopHmrServer,bj as streamTemplate,Tj as streamTemplateSimple,Rj as streamToResponse,Ej as streamingSuspenseDirective,iA as strictCspPreset,Aw as stringToStream,uC as stripCommentsAndLiterals,Hr as stripDocumentWrapper,al as stripLocalePrefix,UE as structuredDataDirective,Ps as stxClientHelpers,$R as templateCache,_c as thumbHashToDataURL,en as thumbHashToRGBA,Qi as thumbnail,uD as toUser,pD as toUsers,FC as transitionDirective,Xo as translate,NM as transpileTypeScript,f0 as typecheckStxFiles,j_ as unescapeHtml,Yy as unmountInstance,eC as unregisterDirective,JT as untrack,Jy as updateInstance,Io as uploadFile,Dc as uploadFiles,nh as useAttrs,Mg as useForm,CA as useHead,Of as useLoadingIndicator,Tl as useLocalStorage,pd as useMiddlewareState,ox as useMiddlewareValue,KT as useOptimistic,RA as usePageTitle,ud as useRouteParam,nx as useRouteParamOrThrow,dd as useRouteParams,_A as useSeoMeta,Cl as useSessionStorage,th as useSlots,kl as useStorage,Vf as useStore,tx as useStoreOrThrow,RA as useTitle,lM as useVirtualList,BM as userComponentFileExists,T_ as usesSignalsInScript,Og as v,DR as validateClientScript,Ax as validateComponentProps,$x as validateComponentScripts,c_ as validateConfig,xA as validateCspDirectives,_M as validateDirective,VA as validateField,qA as validateFields,Oo as validateFile,GA as validateFormEnhanced,wa as validateParams,CM as validateTemplate,KA as validateValueEnhanced,Sg as validated,RE as validators,zm as videoDirective,Ri as virtualPathFor,dj as waitForLocale,rx as waitForStore,Fy as watch,By as watchEffect,Ny as watchMultiple,B$ as watchViews,ga as watermark,s_ as webComponentDirectiveHandler,bg as withDefaults,T0 as wrapComponentForHMR,ql as writeImageManifest,tD as writeManifest,Rn as writeNetlifyConfig};