@stacksjs/stx 0.2.529 → 0.2.531

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 (219) hide show
  1. package/dist/{chunk-35j1evvy.js → chunk-03wggzg8.js} +3 -3
  2. package/dist/chunk-08emfsq3.js +2 -0
  3. package/dist/{chunk-2twfqcxm.js → chunk-0dqxnx20.js} +2 -2
  4. package/dist/{chunk-f1n4e4jy.js → chunk-0wvsfs4s.js} +2 -2
  5. package/dist/chunk-0zmv31nc.js +2 -0
  6. package/dist/{chunk-c322rrge.js → chunk-12e4a0ab.js} +2 -2
  7. package/dist/chunk-12v4d123.js +2 -0
  8. package/dist/{chunk-2m5mx0x8.js → chunk-15r72kw7.js} +1 -1
  9. package/dist/chunk-1cdanx2v.js +2 -0
  10. package/dist/chunk-1wt5fagh.js +2 -0
  11. package/dist/{chunk-y8h823cb.js → chunk-292vew7b.js} +36 -36
  12. package/dist/chunk-2936t942.js +2 -0
  13. package/dist/chunk-2a4szpje.js +3 -0
  14. package/dist/{chunk-8m3k43d3.js → chunk-2dzd2h15.js} +7 -7
  15. package/dist/{chunk-0rt5ec7a.js → chunk-2jk0vceh.js} +4 -4
  16. package/dist/{chunk-ktvr45qg.js → chunk-2qbvsvwc.js} +2 -2
  17. package/dist/chunk-2y6tzn6d.js +3 -0
  18. package/dist/{chunk-csbft3wz.js → chunk-31c1g3rt.js} +3 -3
  19. package/dist/{chunk-21rm5kv6.js → chunk-38w14qs7.js} +2 -2
  20. package/dist/chunk-3dd5zxbt.js +2 -0
  21. package/dist/chunk-3v91cb0g.js +2 -0
  22. package/dist/{chunk-raqbqt1r.js → chunk-3vvppnws.js} +6 -6
  23. package/dist/chunk-3zyvhf4p.js +2 -0
  24. package/dist/chunk-458etq5a.js +4 -0
  25. package/dist/chunk-4cmqjmqr.js +3 -0
  26. package/dist/chunk-4cyjdghc.js +2 -0
  27. package/dist/{chunk-4drgbkga.js → chunk-587ehsxn.js} +2 -2
  28. package/dist/chunk-5achv4zv.js +2 -0
  29. package/dist/{chunk-5tyes97j.js → chunk-5tj6expd.js} +2 -2
  30. package/dist/chunk-5yg6m30k.js +2 -0
  31. package/dist/{chunk-hkjqqx92.js → chunk-6abvk7vj.js} +3 -3
  32. package/dist/chunk-6qzjyr8e.js +2 -0
  33. package/dist/{chunk-ba88n1j7.js → chunk-6v1gwdbv.js} +2 -2
  34. package/dist/chunk-785ckss2.js +2 -0
  35. package/dist/{chunk-5zk6kyjt.js → chunk-7b2hj6nt.js} +2 -2
  36. package/dist/{chunk-y0c1srgj.js → chunk-7s14bthq.js} +5 -5
  37. package/dist/{chunk-2etevws0.js → chunk-7tabykst.js} +2 -2
  38. package/dist/{chunk-zw029e7n.js → chunk-7wfh2hqy.js} +4 -4
  39. package/dist/chunk-7ybgfk0m.js +3 -0
  40. package/dist/chunk-88kjwkza.js +2 -0
  41. package/dist/chunk-8bcvb86w.js +2 -0
  42. package/dist/chunk-8h1zg44w.js +2 -0
  43. package/dist/chunk-8jtyra19.js +2 -0
  44. package/dist/{chunk-jwgzj5at.js → chunk-8n7qsr17.js} +3 -3
  45. package/dist/{chunk-v2zxxjqn.js → chunk-90wh9zzy.js} +6 -6
  46. package/dist/{chunk-1c7v7pqv.js → chunk-95z7yemm.js} +2 -2
  47. package/dist/{chunk-d8ramz4s.js → chunk-9a73re8k.js} +2 -2
  48. package/dist/{chunk-ze832cpr.js → chunk-9f3m5ecs.js} +93 -93
  49. package/dist/{chunk-p4gbvge6.js → chunk-9pztpvvk.js} +1 -1
  50. package/dist/chunk-9skdekv5.js +2 -0
  51. package/dist/{chunk-7p0zerfj.js → chunk-9sqjmd9a.js} +10 -10
  52. package/dist/{chunk-czmw5xsd.js → chunk-9w2vmfha.js} +2 -2
  53. package/dist/chunk-9xq5yer8.js +2 -0
  54. package/dist/{chunk-2hc5mbw8.js → chunk-azb58ven.js} +2 -2
  55. package/dist/{chunk-7mg0cybn.js → chunk-b0tmg1q1.js} +11 -11
  56. package/dist/{chunk-869wyw0j.js → chunk-b7xdk1g4.js} +6 -6
  57. package/dist/chunk-bnsz09pg.js +2 -0
  58. package/dist/{chunk-9mjy16pw.js → chunk-bpr4bkde.js} +2 -2
  59. package/dist/chunk-c9rwnsk7.js +2 -0
  60. package/dist/chunk-cp4dr9ch.js +2 -0
  61. package/dist/{chunk-wsjrvxs9.js → chunk-cp8f1pv4.js} +3 -3
  62. package/dist/chunk-csjax0ej.js +2 -0
  63. package/dist/{chunk-6rdnzn77.js → chunk-cxxcy624.js} +5 -5
  64. package/dist/{chunk-6t0rq51y.js → chunk-d2r8t40y.js} +2 -2
  65. package/dist/{chunk-smn7sssc.js → chunk-d3mssbgp.js} +2 -2
  66. package/dist/{chunk-6k7spr38.js → chunk-d7x6n702.js} +7 -7
  67. package/dist/chunk-dd31q423.js +2 -0
  68. package/dist/chunk-dptjyncv.js +2 -0
  69. package/dist/{chunk-f5pmyxtn.js → chunk-ennxrn5g.js} +5 -5
  70. package/dist/{chunk-xevnx24r.js → chunk-er031j13.js} +2 -2
  71. package/dist/chunk-et8ejd7k.js +2 -0
  72. package/dist/{chunk-tn7nvmah.js → chunk-fmp8dmt0.js} +2 -2
  73. package/dist/chunk-frw35d2v.js +2 -0
  74. package/dist/chunk-fyxydww2.js +4 -0
  75. package/dist/{chunk-x1tzt7yc.js → chunk-g12j8ahm.js} +4 -4
  76. package/dist/chunk-g1kyy5h1.js +2 -0
  77. package/dist/{chunk-3cn7973z.js → chunk-gsxb0ry9.js} +1 -1
  78. package/dist/{chunk-e6y6s7q8.js → chunk-gxfnmjzp.js} +2 -2
  79. package/dist/chunk-h791c7sb.js +2 -0
  80. package/dist/chunk-h88jcr3k.js +2 -0
  81. package/dist/chunk-hpeg9erh.js +3 -0
  82. package/dist/{chunk-kpns3659.js → chunk-hrrxggpx.js} +12 -8
  83. package/dist/chunk-hvvbppt4.js +2 -0
  84. package/dist/chunk-j4rb9rxx.js +2 -0
  85. package/dist/{chunk-346zc43s.js → chunk-jjwg83xv.js} +1 -1
  86. package/dist/chunk-ka7qdsha.js +2 -0
  87. package/dist/{chunk-58jyc7kp.js → chunk-kg77xs08.js} +3 -3
  88. package/dist/{chunk-yy19rrw6.js → chunk-ktmacsqc.js} +2 -2
  89. package/dist/{chunk-299xbyhn.js → chunk-kwvexxey.js} +4 -4
  90. package/dist/chunk-ky25egh1.js +2 -0
  91. package/dist/chunk-m4d99a9r.js +2 -0
  92. package/dist/{chunk-f3y397xy.js → chunk-m5c2gts6.js} +55 -55
  93. package/dist/chunk-m5gdwq1d.js +2 -0
  94. package/dist/{chunk-ycxz2exz.js → chunk-mc5agc81.js} +6 -6
  95. package/dist/{chunk-vbv5jqkz.js → chunk-mwte3cbe.js} +7 -7
  96. package/dist/chunk-ndv44bgs.js +2 -0
  97. package/dist/chunk-nz5ekyxn.js +2 -0
  98. package/dist/{chunk-yh3p86qa.js → chunk-p8qr0q85.js} +2 -2
  99. package/dist/{chunk-6k4f583z.js → chunk-p8yh7mgr.js} +2 -2
  100. package/dist/chunk-pkfwxp9n.js +2 -0
  101. package/dist/chunk-pr5q4wev.js +2 -0
  102. package/dist/{chunk-fk45zc1b.js → chunk-q6e45gnw.js} +5 -5
  103. package/dist/chunk-qwpgggkj.js +2837 -0
  104. package/dist/{chunk-wqxdx2td.js → chunk-r6gxy92f.js} +2 -2
  105. package/dist/chunk-rchwwcxy.js +2 -0
  106. package/dist/chunk-rsy1r1t2.js +18 -0
  107. package/dist/{chunk-wn5zjs5m.js → chunk-rtk6n3vh.js} +3 -3
  108. package/dist/chunk-s5cb4hkj.js +2 -0
  109. package/dist/{chunk-7rz4fy4y.js → chunk-srcv6wvm.js} +8 -8
  110. package/dist/chunk-st79dqpz.js +2 -0
  111. package/dist/chunk-t2mjeezd.js +2 -0
  112. package/dist/chunk-t94z65ry.js +2 -0
  113. package/dist/{chunk-0ytm2ecf.js → chunk-tkeabv04.js} +16 -16
  114. package/dist/{chunk-k3tq1k4m.js → chunk-tvssmzc2.js} +5 -5
  115. package/dist/{chunk-5ew3rq40.js → chunk-tyts58ks.js} +1 -1
  116. package/dist/{chunk-1e7g79x4.js → chunk-v1m9nrn9.js} +1 -1
  117. package/dist/{chunk-baxwjmj3.js → chunk-v38kqjew.js} +2 -2
  118. package/dist/{chunk-07abr1v4.js → chunk-vg8thz41.js} +3 -3
  119. package/dist/chunk-vk18649m.js +2 -0
  120. package/dist/chunk-vmfw4svt.js +2 -0
  121. package/dist/{chunk-bs2e3g25.js → chunk-w3xs6kb9.js} +5 -5
  122. package/dist/chunk-wbv6vjhm.js +2 -0
  123. package/dist/{chunk-1v6yyvxf.js → chunk-wk85dz07.js} +3 -3
  124. package/dist/chunk-wpnv0naj.js +2 -0
  125. package/dist/chunk-wv2crxm6.js +2 -0
  126. package/dist/chunk-wzymzex7.js +2 -0
  127. package/dist/{chunk-hbwmmt91.js → chunk-xab6b4mt.js} +2 -2
  128. package/dist/{chunk-1s7qdv2h.js → chunk-xcfhy5bj.js} +3 -3
  129. package/dist/chunk-xda69f13.js +2 -0
  130. package/dist/chunk-xmwd2xm6.js +2 -0
  131. package/dist/chunk-xtknewf7.js +2 -0
  132. package/dist/chunk-ym182eg0.js +2 -0
  133. package/dist/{chunk-p8c5g5n2.js → chunk-yn3kp3qy.js} +5 -5
  134. package/dist/chunk-z14e2qyn.js +3 -0
  135. package/dist/chunk-zah67v44.js +2 -0
  136. package/dist/chunk-zpdq0kx1.js +2 -0
  137. package/dist/chunk-zpf9he2x.js +2 -0
  138. package/dist/chunk-zpftj8s8.js +2 -0
  139. package/dist/{chunk-xpvvne6r.js → chunk-zzphh8g9.js} +9 -9
  140. package/dist/cli.js +62 -62
  141. package/dist/craft-entry.js +2 -2
  142. package/dist/craft.js +2 -2
  143. package/dist/framework-composables.js +1 -1
  144. package/dist/image-optimization/processor.js +6 -8
  145. package/dist/native-build.js +12 -7
  146. package/dist/pwa.js +3 -3
  147. package/dist/ssg.js +13 -13
  148. package/dist/temp-dir.d.ts +52 -0
  149. package/dist/temp-dir.js +140 -0
  150. package/package.json +5 -5
  151. package/dist/chunk-0fad6jf4.js +0 -2
  152. package/dist/chunk-0fna7gd0.js +0 -2
  153. package/dist/chunk-0ksq0e6s.js +0 -2
  154. package/dist/chunk-16k8mkwm.js +0 -2
  155. package/dist/chunk-1n8d0htz.js +0 -2
  156. package/dist/chunk-1q4yn31s.js +0 -2
  157. package/dist/chunk-1wp8qb5f.js +0 -2
  158. package/dist/chunk-2bwhc8ea.js +0 -2
  159. package/dist/chunk-2fb4yx25.js +0 -4
  160. package/dist/chunk-2p0dbz34.js +0 -2
  161. package/dist/chunk-2y82wf9d.js +0 -3
  162. package/dist/chunk-3j02tj5n.js +0 -2
  163. package/dist/chunk-3j9de8yh.js +0 -2
  164. package/dist/chunk-3v2bf157.js +0 -2
  165. package/dist/chunk-4dm3fj16.js +0 -2
  166. package/dist/chunk-4mmz9xxh.js +0 -2837
  167. package/dist/chunk-62s4jb6m.js +0 -2
  168. package/dist/chunk-7c1ntx2e.js +0 -2
  169. package/dist/chunk-84p3bcpx.js +0 -2
  170. package/dist/chunk-8a4mndgc.js +0 -2
  171. package/dist/chunk-8dbnvypv.js +0 -2
  172. package/dist/chunk-9x9bp5w8.js +0 -2
  173. package/dist/chunk-9z76qhdm.js +0 -2
  174. package/dist/chunk-ad0czgpa.js +0 -2
  175. package/dist/chunk-axjzqh7v.js +0 -2
  176. package/dist/chunk-dvph69ej.js +0 -2
  177. package/dist/chunk-dzt3bvvn.js +0 -2
  178. package/dist/chunk-e1c9gypy.js +0 -2
  179. package/dist/chunk-e9f55nee.js +0 -2
  180. package/dist/chunk-eadr1eph.js +0 -2
  181. package/dist/chunk-eh3nvr2g.js +0 -2
  182. package/dist/chunk-fanmabb0.js +0 -2
  183. package/dist/chunk-fdcrrpgn.js +0 -2
  184. package/dist/chunk-fjd5ka6v.js +0 -2
  185. package/dist/chunk-fq5xecrx.js +0 -2
  186. package/dist/chunk-g7ey7mtw.js +0 -3
  187. package/dist/chunk-gaz311xs.js +0 -2
  188. package/dist/chunk-ggb57j6c.js +0 -3
  189. package/dist/chunk-hmk2x1t8.js +0 -2
  190. package/dist/chunk-hnn0pdz1.js +0 -2
  191. package/dist/chunk-j00h4d3w.js +0 -2
  192. package/dist/chunk-j1tbfabt.js +0 -2
  193. package/dist/chunk-jagpqt9y.js +0 -2
  194. package/dist/chunk-jh6nh2m0.js +0 -2
  195. package/dist/chunk-jj8ssn0d.js +0 -3
  196. package/dist/chunk-jkd0c82m.js +0 -2
  197. package/dist/chunk-jwx0h9qb.js +0 -2
  198. package/dist/chunk-k4p80n25.js +0 -2
  199. package/dist/chunk-m2wzrk3d.js +0 -2
  200. package/dist/chunk-n26xx6x5.js +0 -2
  201. package/dist/chunk-n6rzr34r.js +0 -2
  202. package/dist/chunk-pkwed7dt.js +0 -2
  203. package/dist/chunk-pqwx5hw8.js +0 -2
  204. package/dist/chunk-qap3fwv8.js +0 -2
  205. package/dist/chunk-rnnead1w.js +0 -2
  206. package/dist/chunk-s1evrkrv.js +0 -3
  207. package/dist/chunk-v70hfs6d.js +0 -2
  208. package/dist/chunk-vr0fb0x1.js +0 -2
  209. package/dist/chunk-vrdg365w.js +0 -2
  210. package/dist/chunk-w5kx0qzg.js +0 -2
  211. package/dist/chunk-wpm4emgb.js +0 -2
  212. package/dist/chunk-ww68p1kb.js +0 -2
  213. package/dist/chunk-wy36z6qp.js +0 -2
  214. package/dist/chunk-xgmqes1s.js +0 -2
  215. package/dist/chunk-y4b60ke0.js +0 -2
  216. package/dist/chunk-yn2d8x8m.js +0 -3
  217. package/dist/chunk-yqh6dny3.js +0 -2
  218. package/dist/chunk-yyb5se8j.js +0 -18
  219. package/dist/chunk-zc8cz12e.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{X,yn,te,P,Rt}from"./chunk-0ytm2ecf.js";import{Qe,xn,lr,dr,ur,et,tt,nt,rt,st,ot,ke}from"./chunk-kpns3659.js";import{U,b,nn,rn,e,kt,sn,f,Be,Ct,Fe,ze,Z,N,ce,K,u,be,fi,bs,n,r,ee,Jn,o,A,le}from"./chunk-4mmz9xxh.js";import{Ae,ao,ne,_,co,Cr,An,me,lo,re}from"./chunk-7rz4fy4y.js";import{It}from"./chunk-1c7v7pqv.js";import{ae}from"./chunk-2hc5mbw8.js";import{a}from"./chunk-2y82wf9d.js";import{D}from"./chunk-ggb57j6c.js";function Ks(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
2
+ import{G,wn,ne,P,Pt}from"./chunk-tkeabv04.js";import{tt,kn,ur,pr,fr,nt,rt,st,ot,it,at,Ce}from"./chunk-hrrxggpx.js";import{W,b,sn,on,e,Et,an,f,ze,Tt,He,Ve,Q,N,le,X,d,we,hi,vs,n,r,te,Zn,o,A,de}from"./chunk-qwpgggkj.js";import{Pe,lo,re,T,uo,Tr,In,he,po,se}from"./chunk-srcv6wvm.js";import{Ot}from"./chunk-95z7yemm.js";import{ce}from"./chunk-azb58ven.js";import{a}from"./chunk-4cmqjmqr.js";import{O}from"./chunk-7ybgfk0m.js";function Gs(t,s){let i=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
3
3
  /* Theme selector for code blocks */
4
4
  .theme-selector {
5
5
  margin: 1rem 0;
@@ -79,12 +79,12 @@ else {
79
79
  <span class="frontmatter-label">${s}:</span>
80
80
  <span>${Array.isArray(i)?i.join(", "):String(i)}</span>
81
81
  </div>`).join("")}
82
- </div>`}import Gt from"net";async function Xn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Gn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Yn(t){if(!await Xn(t))return!1;return await Gn(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await Yn(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Qn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Zn(){try{let t=await import("./chunk-y8h823cb.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let i={...Qn,...s},d=await Zn();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await d.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function St(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
82
+ </div>`}import Gt from"net";async function Xn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Gn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Jn(t){if(!await Xn(t))return!1;return await Gn(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let p=t+i;if(await Jn(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Yn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Qn(){try{let t=await import("./chunk-292vew7b.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let i={...Yn,...s},p=await Qn();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function St(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
83
83
  ${l}
84
84
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
85
- `,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let c=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
86
- Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function er(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function tr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ze(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let d="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(d+=c,d.endsWith("\r")||d.endsWith(`
87
- `)){let l=d.trim().toLowerCase();d="",nr(l,t,s,i)}})}function nr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else tr(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),er(s);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await le(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],H=[...new Set([...x,...T])].map((M)=>`<option value="${M}"${M===v?" selected":""}>${M}</option>`).join(`
85
+ `,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
86
+ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function er(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function tr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
87
+ `)){let l=p.trim().toLowerCase();p="",nr(l,t,s,i)}})}function nr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else tr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),er(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await de(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],H=[...new Set([...x,...C])].map((_)=>`<option value="${_}"${_===v?" selected":""}>${_}</option>`).join(`
88
88
  `);return l=`
89
89
  <!DOCTYPE html>
90
90
  <html lang="en">
@@ -252,14 +252,14 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
252
252
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
253
253
  ${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
254
254
  ${e.yellow}Routes:${e.reset}`);let y=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
255
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(g.url.toString(),()=>{if(d)Bt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(d){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(C,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function or(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fi}=globalThis.Bun;import Ne from"fs";import Se from"path";class Jt{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let d=0;d<i;d++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let p=JSON.parse(m);if(p.type==="console"&&Array.isArray(p.args)){let h=p.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${y}[browser]${p.level!=="log"?` ${p.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let d of this.clients)try{if(d.readyState===1)d.send(s),i++}catch{this.clients.delete(d)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function sr(t,s={}){let{showOverlay:i=!0,reconnectInterval:d=1000,maxReconnectAttempts:c=10}=s;return`
255
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(p)Bt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(h,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function or(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fi}=globalThis.Bun;import Fe from"fs";import Se from"path";class Jt{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let h=u.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${y}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),i++}catch{this.clients.delete(p)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function sr(t,s={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
256
256
  <script>
257
257
  (function() {
258
258
  // stx Hot Reload Client
259
259
  var wsUrl = 'ws://' + window.location.hostname + ':${t}';
260
260
  var reconnectAttempts = 0;
261
261
  var maxAttempts = ${c};
262
- var reconnectInterval = ${d};
262
+ var reconnectInterval = ${p};
263
263
  var socket = null;
264
264
  var overlay = null;
265
265
  var wasConnected = false; // Track if we ever connected successfully
@@ -451,13 +451,13 @@ else {
451
451
  };
452
452
  })();
453
453
  </script>
454
- `}function Xe(t,s,i={}){let d=sr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function Tt(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function $t(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Et(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Pt(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Mt from"path";async function ir(t){try{let s=await Bun.file(t).text(),i=ar(s),d=cr(s,t),c=pr(s,i),l=fr(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function ar(t){let s=t.split(`
454
+ `}function Xe(t,s,i={}){let p=sr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function kt(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function $t(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Ct(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Rt(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import _t from"path";async function ir(t){try{let s=await Bun.file(t).text(),i=ar(s),p=cr(s,t),c=lr(s,i),l=dr(s,i);return{file:t,metrics:i,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function ar(t){let s=t.split(`
455
455
  `),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
456
- `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+p+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function cr(t,s){let i=[],d=Qt(t,"if","endif");if(d>0)i.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Qt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let y=p.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
457
- `).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function pr(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function fr(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:d,recommendations:c}}function Qt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Xs(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await ir(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=mr(i);return{results:i,summary:c}}function mr(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as gr,readFile as xr,readdir as vr,stat as Zt,writeFile as wr}from"fs/promises";import Pe from"path";function ln(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function kr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Tr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function $r(t){let s=[];async function i(d){let c=await vr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Pe.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function Rr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=m.exec(l)){let h=p[1];if(dn.has(h))throw Error(`${s}: client ${ln(h)}`);let g=m.lastIndex,y=1,w="",S=!1,C=g;for(;C<l.length&&y>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,C-1)}}`,m.lastIndex=C}}return i}function Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function en(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
456
+ `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,R=0;for(let C of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,S=Math.max(S,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function cr(t,s){let i=[],p=Qt(t,"if","endif");if(p>0)i.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Qt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let y=u.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
457
+ `).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function lr(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function dr(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Qt(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Js(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await ir(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=mr(i);return{results:i,summary:c}}function mr(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),p=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),h=[];if(p>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:h}}import{mkdir as gr,readFile as hr,readdir as yr,stat as Zt,writeFile as xr}from"fs/promises";import Oe from"path";function ln(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function kr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let s=[];async function i(p){let c=await yr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Oe.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function Rr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let h=u[1];if(dn.has(h))throw Error(`${s}: client ${ln(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=u[0].includes("async")?"async ":"";i[h]=`${v}${h}(${u[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}return i}function Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function en(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
458
458
 
459
- `)}function Or(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function Ar(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function Dr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function Mr(t){let s=[],i=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(d[h]!=="(")return null;let g=0,y="";for(let w=h;w<d.length;w++){let S=d[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:d.slice(h+1,w),end:w+1}}}return null},p=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(d)){p(d.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,C,v]=w;s.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return p(d.slice(i)),s.join(`
460
- `)}function Ot(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function tn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=Ot(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let C="";if(h(),t[p]==="<"){let k=Ot(t,p,"<",">");if(k===-1)return null;C=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=Ot(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=Ot(t,p,"{","}");if(k===-1)return null;for(let[H,M]of Nt(t.slice(p,k)))l[H]=M;p=k}if(h(),t[p]===",")p++,h();if(t[p]===")")p++}if(t[p]===";")p++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of zt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Nt(x)){if(m.push(k),!H.startsWith("{")){let M=tn(H);if(M)c[k]=M;continue}for(let[M,I]of Nt(H))if(M==="default")l[k]=I;else if(M==="type"){let R=tn(I);if(R)c[k]=R}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=_r(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(d,p),propNames:m,defaults:l,declared:c,typeName:T}}function Nt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],d=0;while(d<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=d;let l=c.exec(s);if(!l)break;d=c.lastIndex;let m=0,p="",h=d;while(d<s.length){let y=s[d];if(p){if(y==="\\")d++;else if(y===p)p=""}else if(y==="'"||y==='"'||y==="`")p=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;d++}let g=s.slice(h,d).trim();if(g)i.push([l[1],g]);d++}return i}function Ir(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],p=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Pe.resolve(Pe.dirname(s),x),H=Pe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${T}`})),""});let y=Lr(l);if(y)p.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!p.includes(S))p.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:p,defaults:h,declared:g}}function jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,c,l,m,p)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${p}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,c,l,m)=>{let p=s.length;return s.push({id:p,name:c,expression:m}),` data-stx-bind-${p}=""`}),bindings:s}}function Br(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function on(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,i){let d=Pe.isAbsolute(s.file)?s.file:Pe.resolve(t,s.file),c=await xr(d,"utf8"),l=Rr(c,d),m=Pe.basename(d,".stx"),p=s.name||l.name||Sr(m),h=`${Ut(i.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||h;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!kr(g))throw Error(`${d}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([M,I])=>[M,on(M,I)])),S=jr(Pr(c)),C=Hr(S.template),v=Ir(c,d,Pe.resolve(i.outputDir)),x=Mr(C.template);for(let M of v.propNames){if(w[M])continue;let I=v.defaults[M];w[M]=on(M,{type:Or(v.declared[M])??Ar(I),...I===void 0?{}:{default:Dr(I)}})}let T=l.methods||{},k=s.methods||{},H=Er(c,d);return{file:Pe.relative(t,d),sourcePath:d,name:p,tag:g,description:s.description||l.description||"",template:C.template,styles:en(c),shadowMode:Tr(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...T,...k,...H},eventTypes:S.eventTypes,bindings:C.bindings,slots:Br(C.template),cssProperties:Fr(en(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
459
+ `)}function Or(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function Ar(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function Dr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function Mr(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(p[h]!=="(")return null;let g=0,y="";for(let w=h;w<p.length;w++){let S=p[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,R,v]=w;s.push(R?`for (const [${R}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
460
+ `)}function At(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function tn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=At(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let R="";if(h(),t[u]==="<"){let k=At(t,u,"<",">");if(k===-1)return null;R=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=At(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=At(t,u,"{","}");if(k===-1)return null;for(let[H,_]of Nt(t.slice(u,k)))l[H]=_;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of zt(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Nt(x)){if(m.push(k),!H.startsWith("{")){let _=tn(H);if(_)c[k]=_;continue}for(let[_,I]of Nt(H))if(_==="default")l[k]=I;else if(_==="type"){let E=tn(I);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=_r(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:C}}function Nt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",h=p;while(p<s.length){let y=s[p];if(u){if(y==="\\")p++;else if(y===u)u=""}else if(y==="'"||y==='"'||y==="`")u=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;p++}let g=s.slice(h,p).trim();if(g)i.push([l[1],g]);p++}return i}function Ir(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Oe.resolve(Oe.dirname(s),x),H=Oe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${C}`})),""});let y=Lr(l);if(y)u.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let R=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:h,declared:g}}function jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Br(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function nn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,i){let p=Oe.isAbsolute(s.file)?s.file:Oe.resolve(t,s.file),c=await hr(p,"utf8"),l=Rr(c,p),m=Oe.basename(p,".stx"),u=s.name||l.name||Sr(m),h=`${Ut(i.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!kr(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([_,I])=>[_,nn(_,I)])),S=jr(Pr(c)),R=Hr(S.template),v=Ir(c,p,Oe.resolve(i.outputDir)),x=Mr(R.template);for(let _ of v.propNames){if(w[_])continue;let I=v.defaults[_];w[_]=nn(_,{type:Or(v.declared[_])??Ar(I),...I===void 0?{}:{default:Dr(I)}})}let C=l.methods||{},k=s.methods||{},H=Er(c,p);return{file:Oe.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:R.template,styles:en(c),shadowMode:$r(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...H},eventTypes:S.eventTypes,bindings:R.bindings,slots:Br(R.template),cssProperties:Fr(en(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
461
461
 
462
462
  const escapeHTML = (value) => String(value ?? '')
463
463
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -755,22 +755,22 @@ export function defineComponent(Component, definition) {
755
755
  }
756
756
  return Component;
757
757
  }
758
- `}function Ur(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([p,h])=>{if(dn.has(p))throw Error(`${t.sourcePath}: ${ln(p)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${p}($event) {
758
+ `}function Ur(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([u,h])=>{if(dn.has(u))throw Error(`${t.sourcePath}: ${ln(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${u}($event) {
759
759
  ${h}
760
760
  }`}).join(`
761
761
 
762
- `),d=t.scope,c=[...new Set([...Object.keys(t.properties),...d.propNames])].map((p)=>d.defaults[p]===void 0?p:`${p} = ${d.defaults[p]}`).join(", "),l=(p)=>p.split(`
762
+ `),p=t.scope,c=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
763
763
  `).map((h)=>h.trim()===""?h:` ${h}`).join(`
764
- `),m="";if(t.render.trim()!==""||d.body!==""||c!==""){let p=[c?`const { ${c} } = this._props();`:"",d.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
764
+ `),m="";if(t.render.trim()!==""||p.body!==""||c!==""){let u=[c?`const { ${c} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
765
765
  `),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
766
- ${p}
766
+ ${u}
767
767
  }`),y=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(y+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
768
768
  render(__helpers) {
769
769
  const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
770
770
  ${l(h.trim())}
771
771
  }
772
772
  `}return`import { StxElement, defineComponent } from './runtime.js';
773
- ${d.imports.length?`${d.imports.join(`
773
+ ${p.imports.length?`${p.imports.join(`
774
774
  `)}
775
775
  `:""}
776
776
  /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
@@ -780,16 +780,16 @@ ${i}${m}
780
780
 
781
781
  defineComponent(${t.name}, ${s});
782
782
  export default ${t.name};
783
- `}function At(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Wr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${At(m)}`).join(`
784
- `),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${At(m)}`).join(`
785
- `),d=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
783
+ `}function Dt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Wr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${Dt(m)}`).join(`
784
+ `),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${Dt(m)}`).join(`
785
+ `),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
786
786
  `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
787
787
  `);return`export interface ${t.name}Props {
788
788
  ${s}
789
789
  }
790
790
 
791
791
  export interface ${t.name}EventMap {
792
- ${d}
792
+ ${p}
793
793
  }
794
794
 
795
795
  export declare class ${t.name} extends HTMLElement {
@@ -810,10 +810,10 @@ export default ${t.name}
810
810
  `}function Vr(t){return`declare global {
811
811
  namespace JSX {
812
812
  interface IntrinsicElements {
813
- ${t.map((i)=>{let d=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${At(m)}`).join(`
814
- `),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
813
+ ${t.map((i)=>{let p=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${Dt(m)}`).join(`
814
+ `),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
815
815
  `);return` ${JSON.stringify(i.tag)}: {
816
- ${d}
816
+ ${p}
817
817
  ${c}
818
818
  children?: unknown
819
819
  slot?: string
@@ -826,9 +826,9 @@ ${c}
826
826
  }
827
827
 
828
828
  export {}
829
- `}function qr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,d])=>({kind:"field",name:i,description:d.description,type:{text:At(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||Ut(i),reflects:d.reflect})),events:Object.entries(s.events).map(([i,d])=>({name:i,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function an(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
829
+ `}function qr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,p])=>({kind:"field",name:i,description:p.description,type:{text:Dt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ut(i),reflects:p.reflect})),events:Object.entries(s.events).map(([i,p])=>({name:i,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function rn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
830
830
  ${s}
831
- }`}function cn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
831
+ }`}function cn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
832
832
  `);return`const definitions = ${JSON.stringify(c,null,2)};
833
833
  const escapeHTML = (value) => String(value ?? '')
834
834
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -843,7 +843,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
843
843
  let template = definition.template
844
844
  .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
845
845
  .replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
846
- .replace(new RegExp(${d}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
846
+ .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
847
847
  const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
848
848
  if (property.attribute === false || !(name in props)) return [];
849
849
  const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
@@ -862,27 +862,27 @@ export function renderComponent(tag, props = {}, slots = {}) {
862
862
  }
863
863
 
864
864
  ${l}
865
- `}async function Gs(t){let s=Pe.resolve(t.inputDir),i=Pe.resolve(t.outputDir);if(!(await Zt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await $r(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>zr(s,x,t)));l.sort((x,T)=>x.tag.localeCompare(T.tag));let m=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let p=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await gr(i,{recursive:!0});let h=[],g=async(x,T)=>{let k=Pe.join(i,x);return await wr(k,T.endsWith(`
866
- `)?T:`${T}
867
- `,"utf8"),h.push(k),k};await g("runtime.js",Nr());for(let x of l){if(await g(`${x.tag}.js`,Ur(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Wr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:an(x);await g(`${x.tag}.css`,t.minify?cn(T):T)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
865
+ `}async function Ys(t){let s=Oe.resolve(t.inputDir),i=Oe.resolve(t.outputDir);if(!(await Zt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await Cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>zr(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await gr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Oe.join(i,x);return await xr(k,C.endsWith(`
866
+ `)?C:`${C}
867
+ `,"utf8"),h.push(k),k};await g("runtime.js",Nr());for(let x of l){if(await g(`${x.tag}.js`,Ur(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Wr(x));if(t.css!==!1&&x.styles){let C=x.shadowMode?x.styles:rn(x);await g(`${x.tag}.css`,t.minify?cn(C):C)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
868
868
  `);if(await g("index.js",y),await g("ssr.js",Kr(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
869
869
  `)),await g("custom-elements.d.ts",Vr(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
870
870
  `)}
871
871
  export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
872
872
  ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
873
- `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(qr(l),null,2));let S;if(t.css!==!1){let x=l.filter((T)=>!T.shadowMode&&T.styles).map(an).join(`
873
+ `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(qr(l),null,2));let S;if(t.css!==!1){let x=l.filter((C)=>!C.shadowMode&&C.styles).map(rn).join(`
874
874
 
875
- `);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let C;if(t.bundle!==!1){C=Pe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Pe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],H=k.map((M)=>String(M).trim()).filter(Boolean).join(`
875
+ `);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let R;if(t.bundle!==!1){R=Oe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Oe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],H=k.map((_)=>String(_).trim()).filter(Boolean).join(`
876
876
  `);throw AggregateError(k,`Failed to bundle component library${H?`
877
- ${H}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
878
- `);throw AggregateError(x.logs,`Failed to bundle component library${T?`
879
- ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await Promise.all(h.map(async(x)=>(await Zt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Pe.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}import Wt from"fs";import yt from"path";async function Xr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let C=p.split(`
880
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=C.join(" ").trim(),c.push(g)}if(c.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Gr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
881
- `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,s=!1,i){let d=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let p=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
882
- `);m=`<${d}
883
- ${p}
884
- />`}return{name:d,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function pn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){let c=yt.join(t,d.name);if(d.isDirectory()){let l=await pn(c);i.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let i=await pn(t),d=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),p=!!m,h=m?.tag,g=await Jr(l,p,h);d.push(g)}return d}catch(i){return console.error("Error generating component docs:",i),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let c=yt.join(t,d.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=p?p[1].split(`
885
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let C=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=C.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function Zr(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
877
+ ${H}`:""}`)}if(!x.success){let C=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
878
+ `);throw AggregateError(x.logs,`Failed to bundle component library${C?`
879
+ ${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Zt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Oe.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}import Wt from"fs";import yt from"path";async function Xr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let p=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=u.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=u.split(`
880
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=R.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Gr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
881
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,s=!1,i){let p=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let u=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
882
+ `);m=`<${p}
883
+ ${u}
884
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function pn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await pn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let i=await pn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),u=!!m,h=m?.tag,g=await Jr(l,u,h);p.push(g)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=u?u[1].split(`
885
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=R.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function Zr(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
886
886
  <p>Welcome, {{ user.name }}!</p>
887
887
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
888
888
  <p>Welcome back!</p>
@@ -902,9 +902,9 @@ ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await
902
902
  <p>Page {{ page }}</p>
903
903
  @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
904
904
  {{ This will be displayed as-is }}
905
- @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 i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function eo(t=[],s=[],i=[],d){let c=`# stx Documentation
905
+ @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 i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function no(t=[],s=[],i=[],p){let c=`# stx Documentation
906
906
 
907
- `;if(d)c+=`${d}
907
+ `;if(p)c+=`${p}
908
908
 
909
909
  `;if(t.length>0){c+=`## Components
910
910
 
@@ -944,7 +944,7 @@ ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await
944
944
 
945
945
  `,c+=`#### Example
946
946
 
947
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function to(t=[],s=[],i=[],d){let c=`<!DOCTYPE html>
947
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ro(t=[],s=[],i=[],p){let c=`<!DOCTYPE html>
948
948
  <html lang="en">
949
949
  <head>
950
950
  <meta charset="UTF-8">
@@ -987,7 +987,7 @@ ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await
987
987
  </head>
988
988
  <body>
989
989
  <h1>stx Documentation</h1>
990
- `;if(d)c+=`<div>${d}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
990
+ `;if(p)c+=`<div>${p}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
991
991
  <thead>
992
992
  <tr>
993
993
  <th>Name</th>
@@ -1015,23 +1015,23 @@ ${T}`:""}`)}if(h.push(C),t.sourcemap==="external")h.push(`${C}.map`)}let v=await
1015
1015
  <td>@${l.name}</td>
1016
1016
  <td>${l.description||"-"}</td>
1017
1017
  <td>${l.hasEndTag?"Yes":"No"}</td>
1018
- </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function no(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ro(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await Yr(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await Qr(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",C="";switch(y){case"markdown":S=eo(p,h,g,w),C="md";break;case"html":S=to(p,h,g,w),C="html";break;case"json":S=no(p,h,g,w),C="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Js(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||A.componentsDir,d=t.templatesDir||".";return ro({componentsDir:i,templatesDir:d,webComponentsConfig:A.webComponents,customDirectives:A.customDirectives,config:s})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function hr(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
1019
- `;let d=t;if(i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=io(d,i),d=mo(d,i),d=po(d,i),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1018
+ </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function oo(t=[],s=[],i=[],p){return JSON.stringify({components:t,templates:s,directives:i,extraContent:p||""},null,2)}async function so(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await Yr(s,p),console.log(`Found ${u.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await Qr(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=no(u,h,g,w),R="md";break;case"html":S=ro(u,h,g,w),R="html";break;case"json":S=oo(u,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Zs(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||A.componentsDir,p=t.templatesDir||".";return so({componentsDir:i,templatesDir:p,webComponentsConfig:A.webComponents,customDirectives:A.customDirectives,config:s})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function br(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
1019
+ `;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=co(p,i),p=ho(p,i),p=fo(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1020
1020
  `).replace(/\r/g,`
1021
- `),!d.endsWith(`
1022
- `))d+=`
1023
- `;return d}function Ys(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
1024
- `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,p,h)=>{let g=p.split(`
1025
- `),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1026
- `),v=hr(S,i).trimEnd().split(`
1021
+ `),!p.endsWith(`
1022
+ `))p+=`
1023
+ `;return p}function Qs(t,s={}){let i={...fn,...s};if(t.trim()==="")return`
1024
+ `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,h)=>{let g=u.split(`
1025
+ `),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let C=x.match(/^( *)/);return C?C[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1026
+ `),v=br(S,i).trimEnd().split(`
1027
1027
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1028
1028
  `);return`${l}\`\`\`${m}
1029
1029
  ${v}
1030
- ${l}\`\`\``}),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replace(/\r\n/g,`
1030
+ ${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1031
1031
  `).replace(/\r/g,`
1032
- `),!d.endsWith(`
1033
- `))d+=`
1034
- `;return d}function so(t){let s=t,i=[],d="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${d}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1032
+ `),!p.endsWith(`
1033
+ `))p+=`
1034
+ `;return p}function ao(t){let s=t,i=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1035
1035
  $1
1036
1036
  `),s=s.replace(/(@end\w+)/g,`
1037
1037
  $1
@@ -1039,16 +1039,16 @@ $1
1039
1039
  $1
1040
1040
  `),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1041
1041
  $1
1042
- `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,p)=>{let h=p.substring(m+c.length,Math.min(p.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
1043
- ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,p,h)=>{let g=h.substring(Math.max(0,p-50),p),w=h.substring(p+c.length,Math.min(h.length,p+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1044
- ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,p)=>{let h=p.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
1045
- `}),s=s.replace(new RegExp(`${d}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1042
+ `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let h=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
1043
+ ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,h)=>{let g=h.substring(Math.max(0,u-50),u),w=h.substring(u+c.length,Math.min(h.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1044
+ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let h=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
1045
+ `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1046
1046
  `),s=s.split(`
1047
1047
  `).map((c)=>c.trim()).join(`
1048
- `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function io(t,s){let d=so(t).split(`
1049
- `),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let C=y===">";if(un(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),T=y.startsWith("@")&&fo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),M=y.startsWith("</"),I=y.startsWith("<")&&!M&&!H&&!k,R=y.includes("/>")||uo(y),L=un(y);if(M||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(C)c.push(g);else c.push(p.repeat(B)+y);if(I&&!R&&!L&&!C||T)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1050
- `)}function po(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,d,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,d,c)=>{if(c.trim()==="")return`@${d}`;return`@${d}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,d)=>`{!! ${d.trim()} !!}`);return t}function uo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let d=i[1];return s.includes(d.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function fo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function mo(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,d,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1051
- `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],p;while((p=l.exec(c))!==null)m.push({name:p[1],value:p[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${h?` ${h}`:""}>`})}import mn from"fs";import Vt from"path";async function Zs(t="index.stx",s={}){try{let i=s.force||!1,d=Vt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(d);if(!mn.existsSync(c))mn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=gn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=gn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return go();case"layout":return ho();case"blog":return yo();case"api":return bo();case"app":return xo();default:return hn()}}function hn(){return`<script>
1048
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function co(t,s){let p=ao(t).split(`
1049
+ `),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let R=y===">";if(un(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&go(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),_=y.startsWith("</"),I=y.startsWith("<")&&!_&&!H&&!k,E=y.includes("/>")||mo(y),L=un(y);if(_||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(u.repeat(B)+y);if(I&&!E&&!L&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1050
+ `)}function fo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function mo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function go(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function ho(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1051
+ `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import mn from"fs";import Vt from"path";async function eo(t="index.stx",s={}){try{let i=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!mn.existsSync(c))mn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=gn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=gn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return yo();case"layout":return bo();case"blog":return xo();case"api":return vo();case"app":return wo();default:return hn()}}function hn(){return`<script>
1052
1052
  const title = "My stx Page"
1053
1053
  const description = "A page built with stx"
1054
1054
  const features = [
@@ -1073,7 +1073,7 @@ const features = [
1073
1073
  </div>
1074
1074
  @endforeach
1075
1075
  </main>
1076
- @endsection`}function go(){return`{{-- Component: Card --}}
1076
+ @endsection`}function yo(){return`{{-- Component: Card --}}
1077
1077
  {{-- Props: title, variant, collapsible --}}
1078
1078
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1079
1079
  <script>
@@ -1118,7 +1118,7 @@ const features = [
1118
1118
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
1119
1119
  .card__body { padding: 1rem; }
1120
1120
  .card.collapsed .card__body { display: none; }
1121
- </style>`}function ho(){return`<!DOCTYPE html>
1121
+ </style>`}function bo(){return`<!DOCTYPE html>
1122
1122
  <html lang="en">
1123
1123
  <head>
1124
1124
  <meta charset="UTF-8">
@@ -1169,7 +1169,7 @@ const features = [
1169
1169
 
1170
1170
  @yield('scripts')
1171
1171
  </body>
1172
- </html>`}function yo(){return`<script>
1172
+ </html>`}function xo(){return`<script>
1173
1173
  // Article metadata
1174
1174
  const title = "My Blog Post"
1175
1175
  const author = "Your Name"
@@ -1214,7 +1214,7 @@ const features = [
1214
1214
  <p>Wrap up your thoughts here.</p>
1215
1215
  </div>
1216
1216
  </article>
1217
- @endsection`}function bo(){return`<script>
1217
+ @endsection`}function vo(){return`<script>
1218
1218
  // API endpoint configuration
1219
1219
  const endpoint = "/api/data"
1220
1220
  const method = "GET"
@@ -1249,7 +1249,7 @@ const features = [
1249
1249
  }
1250
1250
  @else
1251
1251
  {{ JSON.stringify(data, null, 2) }}
1252
- @endif`}function xo(){return`<!DOCTYPE html>
1252
+ @endif`}function wo(){return`<!DOCTYPE html>
1253
1253
  <html lang="en">
1254
1254
  <head>
1255
1255
  <meta charset="UTF-8">
@@ -1474,7 +1474,7 @@ const features = [
1474
1474
  })();
1475
1475
  </script>
1476
1476
  </body>
1477
- </html>`}var Qs="f9c3713";function Wi(t){return t}function qi(t){return t}var bn=`
1477
+ </html>`}var to="f9c3713";function Xi(t){return t}function Gi(t){return t}var yn=`
1478
1478
  <script data-stx-helpers>
1479
1479
  (function() {
1480
1480
  'use strict'
@@ -1785,11 +1785,11 @@ else {
1785
1785
 
1786
1786
  })()
1787
1787
  </script>
1788
- `;import _e from"fs";import $e from"path";function On(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Dt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Dn(t,s="stx"){let i=$e.resolve(t);for(let d=0;d<10;d++){let c=$e.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=$e.dirname(i);if(l===i)break;i=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=_e.readFileSync($e.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Oi(t,s=6){let i=$e.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=_e.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of Mn){let S=$e.join(p,w),C=Pi(S);if(C!==null)d.push({name:w,version:C,dir:$e.relative(i,S)||S,nested:h>0})}let y;try{y=_e.readdirSync(p,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=$e.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=$e.join(S,x.name,"node_modules");if(_e.existsSync(T))l(T,h+1)}continue}let C=$e.join(S,"node_modules");if(_e.existsSync(C))l(C,h+1)}}let m=$e.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return d}function Ai(t){let s=[];for(let i of Mn){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function yr(t={}){let s=t.cwd?$e.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,d=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Ai(Oi(s)))c.push(h);let p=Dn(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=$e.join(p,"src/signals.ts"),g=[$e.join(p,"dist/index.js"),$e.join(p,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,y=On(h),w=g?On(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} but no src/signals.ts to compare`});else if(w==null)c.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 ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Dt(w,d)}) is OLDER than src/signals.ts (${Dt(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Dt(y,d)}, dist ${Dt(w,d)})`});let S=$e.join(s,"node_modules/@stacksjs/stx"),C=null;try{C=_e.lstatSync(S)}catch{C=null}if(!C)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(p)}catch{return p}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.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(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function br(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
1789
- `)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Jn(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await nn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await te(()=>Bun.file(m).text(),"",(x)=>{throw new yn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new yn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=U.time("script-extraction",()=>{let x=h,T=Z(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>u(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await U.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-fdcrrpgn.js"),T=x(w.join(`
1790
- `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
1788
+ `;import _e from"fs";import Te from"path";function Pn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function On(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var An=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=_e.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Oi(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of An){let S=Te.join(u,w),R=Pi(S);if(R!==null)p.push({name:w,version:R,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=_e.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=Te.join(S,x.name,"node_modules");if(_e.existsSync(C))l(C,h+1)}continue}let R=Te.join(S,"node_modules");if(_e.existsSync(R))l(R,h+1)}}let m=Te.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return p}function Ai(t){let s=[];for(let i of An){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function wr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Ai(Oi(s)))c.push(h);let u=On(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,y=Pn(h),w=g?Pn(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.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 ${u} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(y,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(y,p)}, dist ${Mt(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=_e.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.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(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function vr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
1789
+ `)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Zn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await sn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ne(()=>Bun.file(m).text(),"",(x)=>{throw new wn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new wn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=W.time("script-extraction",()=>{let x=h,C=Q(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",_=[];for(let E of k){let L=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=E.match(/<script\b([^>]*)>/i),K=B?B[1]:"";if(/\bserver\b/i.test(K))H=L;else _.push(E)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:_}}),S={__filename:m,__dirname:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ne(()=>d(g,S,m),void 0,(x)=>{let C=new G(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await W.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-j4rb9rxx.js"),C=x(w.join(`
1790
+ `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
1791
1791
  `+v.slice(k);else v+=`
1792
- ${T}`}if(v=await K(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await rn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new X(`Plugin processing failed: ${String(p)}`,m);if(P.log(h,{filePath:m,buildConfig:t.config}),Rt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
1792
+ ${C}`}if(v=await X(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await on(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new G(`Plugin processing failed: ${String(u)}`,m);if(P.log(h,{filePath:m,buildConfig:t.config}),Pt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||O()?`<!DOCTYPE html>
1793
1793
  <html lang="en">
1794
1794
  <head>
1795
1795
  <meta charset="UTF-8">
@@ -1830,7 +1830,7 @@ ${T}`}if(v=await K(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await rn
1830
1830
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
1831
1831
  <li>Verify that all variables used in the template are properly defined</li>
1832
1832
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
1833
- <li>Run <code>stx debug ${b(Mt.basename(m))}</code> for detailed analysis</li>
1833
+ <li>Run <code>stx debug ${b(_t.basename(m))}</code> for detailed analysis</li>
1834
1834
  <li>Enable debug mode in your stx config for more detailed error messages</li>
1835
1835
  </ul>
1836
1836
  </div>
@@ -1849,19 +1849,19 @@ ${T}`}if(v=await K(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await rn
1849
1849
  <h1>Something went wrong</h1>
1850
1850
  <p>An internal error occurred. Please try again later.</p>
1851
1851
  </body>
1852
- </html>`,loader:"html"}}})}};async function Cn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=Se.resolve(t);if(!Ne.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return Ft(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Ne.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup(Ce){Ce.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ye)=>({path:ye.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let G=B.outputs.find((Ce)=>Ce.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(p);await kt(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Pt({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-8dbnvypv.js"),B=await L();if(T=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:oe}=await import("./chunk-k4p80n25.js"),Ce=B.broadcasting;await G(Ce);let ye=Ce.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ye}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(De))try{let de=await oe(De);console.log(`${e.blue}Loaded ${e.bright}${de} broadcast channel${de!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(de){console.warn(`${e.yellow}Failed to load channels.ts: ${de.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-7c1ntx2e.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Fi({port:C,async fetch(L){return It(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(p),Se.join(process.cwd(),"public")].some((de)=>H(Se.join(de,B.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let de=await x.handleRequest(L);if(de.status!==404)return de}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(de){return new Response(JSON.stringify({error:de.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await M(L);if(G)return G;if(B.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.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(W.includes("<html"))W=W.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 W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.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(W.includes("<html"))W=W.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 W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let oe=Se.join(h,B.pathname);if(Ne.existsSync(oe)&&Ne.statSync(oe).isFile()){let de=Bun.file(oe),W=Se.extname(oe).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}let Ce=Se.dirname(p),ye=Se.join(Ce,B.pathname);if(Ne.existsSync(ye)&&Ne.statSync(ye).isFile()){let de=Bun.file(ye),W=Se.extname(ye).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}let De=Se.join(process.cwd(),"public",B.pathname);if(Ne.existsSync(De)&&Ne.statSync(De).isFile()){let de=Bun.file(De),W=Se.extname(De).toLowerCase(),j="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
1852
+ </html>`,loader:"html"}}})}};async function Tn(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Fe.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Fe.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ye)=>({path:ye.path,external:!0}))}},B=await Bun.build({entrypoints:[u],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let K=B.outputs.find(($e)=>$e.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(u);await Et(S);let R=i;try{if(R=await Ye(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||R+1;l=Rt({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,C;try{let{loadStxConfig:L}=await import("./chunk-1cdanx2v.js"),B=await L();if(C=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:ee}=await import("./chunk-12v4d123.js"),$e=B.broadcasting;await K($e);let ye=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ye}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(Fe.existsSync(De))try{let ae=await ee(De);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-ka7qdsha.js"),_=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Fi({port:R,async fetch(L){return Ot(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(u),Se.join(process.cwd(),"public")].some((ae)=>H(Se.join(ae,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(L);if(ae.status!==404)return ae}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await _(L);if(K)return K;if(B.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.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(U.includes("<html"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.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(U.includes("<html"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let ee=Se.join(h,B.pathname);if(Fe.existsSync(ee)&&Fe.statSync(ee).isFile()){let ae=Bun.file(ee),U=Se.extname(ee).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let $e=Se.dirname(u),ye=Se.join($e,B.pathname);if(Fe.existsSync(ye)&&Fe.statSync(ye).isFile()){let ae=Bun.file(ye),U=Se.extname(ye).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}let De=Se.join(process.cwd(),"public",B.pathname);if(Fe.existsSync(De)&&Fe.statSync(De).isFile()){let ae=Bun.file(De),U=Se.extname(De).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
1853
1853
  ${L.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1854
1854
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1855
- ${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
1856
- ${e.yellow}Routes:${e.reset}`);let R=Se.relative(process.cwd(),p);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${R}${e.reset}`),console.log(`
1857
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(I.url.toString(),()=>{if(d)Ne.watch(Se.dirname(p),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(p).text(),B=St(L);await dt(C,{title:Se.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(d){let L=Se.dirname(p);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let B=Ne.watch(L,{recursive:!0},async(G,oe)=>{if(!oe||Et(oe))return;if($t(oe)){console.log(`${e.yellow}File ${e.bright}${oe}${e.yellow} changed, rebuilding...${e.reset}`),be.clear(),ee();let Ce=await y();if(await sn(S),c&&l)if(Ce)l.reload(oe);else l.error("Build failed - check console for details")}else if(Tt(oe)){if(console.log(`${e.cyan}CSS ${e.bright}${oe}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(oe)}});process.on("SIGINT",()=>{if(B.close(),l)ht();I.stop(),process.exit(0)})}return!0}var{serve:zi}=globalThis.Bun;import it from"fs";import Oe from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Oe.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Oe.sep)}async function En(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Oe.resolve(v);if(!it.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");it.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Oe.dirname(Oe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Oe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await le(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),M=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,I=M?.defaultTheme||"github-dark",R=["github-dark"],L=M?.additionalThemes||[],G=[...new Set([...R,...L])].map((De)=>`<option value="${De}"${De===I?" selected":""}>${De}</option>`).join(`
1858
- `),oe=`
1855
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
1856
+ ${e.yellow}Routes:${e.reset}`);let E=Se.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
1857
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.url.toString(),()=>{if(p)Fe.watch(Se.dirname(u),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(u).text(),B=St(L);await dt(R,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(p){let L=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let B=Fe.watch(L,{recursive:!0},async(K,ee)=>{if(!ee||Ct(ee))return;if($t(ee)){console.log(`${e.yellow}File ${e.bright}${ee}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te();let $e=await y();if(await an(S),c&&l)if($e)l.reload(ee);else l.error("Build failed - check console for details")}else if(kt(ee)){if(console.log(`${e.cyan}CSS ${e.bright}${ee}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(ee)}});process.on("SIGINT",()=>{if(B.close(),l)ht();I.stop(),process.exit(0)})}return!0}var{serve:zi}=globalThis.Bun;import Ze from"fs";import Ae from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Ae.sep)}async function _n(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],h=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await de(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),_=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,I=_?.defaultTheme||"github-dark",E=["github-dark"],L=_?.additionalThemes||[],K=[...new Set([...E,...L])].map((De)=>`<option value="${De}"${De===I?" selected":""}>${De}</option>`).join(`
1858
+ `),ee=`
1859
1859
  <!DOCTYPE html>
1860
1860
  <html lang="en">
1861
1861
  <head>
1862
1862
  <meta charset="UTF-8">
1863
1863
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1864
- <title>${Wn(H.title||Oe.basename(x))}</title>
1864
+ <title>${Wn(H.title||Ae.basename(x))}</title>
1865
1865
  <!-- Syntax highlighting styles -->
1866
1866
  <style id="syntax-theme">
1867
1867
  :root {
@@ -2008,7 +2008,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(I.u
2008
2008
  </head>
2009
2009
  <body>
2010
2010
  ${wt(H)}
2011
- ${xt(G)}
2011
+ ${xt(K)}
2012
2012
 
2013
2013
  ${k}
2014
2014
 
@@ -2017,17 +2017,17 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(I.u
2017
2017
  </script>
2018
2018
  </body>
2019
2019
  </html>
2020
- `,ye=`/${Oe.relative(l,x).replace(/\.md$/,"")}`;if(ye.endsWith("/index"))ye=ye.slice(0,-6)||"/";m[ye||"/"]={filePath:x,content:oe,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(R){R.onResolve({filter:/^\/(images|fonts|assets|public)\//},(L)=>({path:L.path,external:!0}))}},H;try{let R=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!R.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,ae(R.logs,x));continue}let L=R.outputs.find((B)=>B.path.endsWith(".html"));if(!L){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(L.path).text()}catch(R){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
2021
- ${ae(R,x)}`);continue}let I=`/${Oe.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:R,params:L}=lr(I,{page:!0});p.push({pattern:R,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ae(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=zi({port:y,async fetch(v){let x=new URL(v.url),T=Oe.join(process.cwd(),"public",x.pathname);if(it.existsSync(T)&&it.statSync(T).isFile()){let M=Bun.file(T),I=Oe.extname(T).toLowerCase(),R="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(M,{headers:{"Content-Type":R}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let M of p){let I=x.pathname.match(M.pattern);if(I){let R=m[M.routeTemplate];if(R){let L={};for(let oe=0;oe<M.paramNames.length;oe++)L[M.paramNames[oe]]=decodeURIComponent(I[oe+1]);let B=R.content,G=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${G}
2022
- </head>`);else B=G+B;k={...R,content:B}}break}}if(k)return f(k.content).then((M)=>{if(M.includes("</head>"))M=M.replace("</head>",`${bn}
2023
- </head>`);return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Oe.join(c,x.pathname);if(it.existsSync(H)&&it.statSync(H).isFile()){let M=Bun.file(H),I=Oe.extname(H).toLowerCase(),R="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(M,{headers:{"Content-Type":R}})}if(x.pathname!=="/"&&m["/"]){let M=ne(v);return f(m["/"].content).then((I)=>{if(M){let R=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(R){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=L?L[1]:"",G=`<!DOCTYPE html><html><head><title>${Wn(B)}</title></head><body><main>${R[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",..._(),"Cache-Control":Ae,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{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(v){return new Response(`<pre>${v}
2020
+ `,ye=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(ye.endsWith("/index"))ye=ye.slice(0,-6)||"/";m[ye||"/"]={filePath:x,content:ee,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(L)=>({path:L.path,external:!0}))}},H;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,ce(E.logs,x));continue}let L=E.outputs.find((B)=>B.path.endsWith(".html"));if(!L){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(L.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
2021
+ ${ce(E,x)}`);continue}let I=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:E,params:L}=ur(I,{page:!0});u.push({pattern:E,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ce(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=zi({port:y,async fetch(v){let x=new URL(v.url),C=Ae.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(C)&&Ze.statSync(C).isFile()){let _=Bun.file(C),I=Ae.extname(C).toLowerCase(),E="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),K=L.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let _ of u){let I=x.pathname.match(_.pattern);if(I){let E=m[_.routeTemplate];if(E){let L={};for(let ee=0;ee<_.paramNames.length;ee++)L[_.paramNames[ee]]=decodeURIComponent(I[ee+1]);let B=E.content,K=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${K}
2022
+ </head>`);else B=K+B;k={...E,content:B}}break}}if(k)return f(k.content).then((_)=>{if(_.includes("</head>"))_=_.replace("</head>",`${yn}
2023
+ </head>`);return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Ae.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let _=Bun.file(H),I=Ae.extname(H).toLowerCase(),E="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),K=L.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let _=re(v);return f(m["/"].content).then((I)=>{if(_){let E=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=L?L[1]:"",K=`<!DOCTYPE html><html><head><title>${Wn(B)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":Pe,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
2024
2024
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
2025
2025
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
2026
2026
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
2027
- ${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),C=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Oe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Oe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
2028
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(d)it.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),be.clear(),ee(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ni}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return Ct(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),d={".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"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function $n(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-8dbnvypv.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-7c1ntx2e.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(p,S),v=g.root&&g.root!=="."?ie.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!ve.existsSync(T)&&!g._layerPageDirs?.some((E)=>ve.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(ve.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let V of z){let we=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;M.push({route:{...V,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await co(p,s.stxOptions?.shell),L){if(R=await Cr(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(p,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}et(),await nt(p);let B=tt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:E}=await import("./chunk-8dbnvypv.js"),F=await E(p);if(F?.apiRouter)oe=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-k4p80n25.js"),we=F.broadcasting;await z(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let Ce=a(p,"output");ve.mkdirSync(Ce,{recursive:!0});let ye=new Map,De=new Set,de=async(E)=>{let F=dr(T,E);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:Ce,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-8dbnvypv.js"),{checkCache:se,cacheTemplate:Q,readFileCached:q,templateCache:J}=await import("./chunk-zc8cz12e.js"),Te=await We(p),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(p,pe)},O={...we,...Te,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(p,"cache");let xe=!F&&!s.profile,ue=O.cache!==!1;if(ue&&xe){let pe=J.get(E.filePath);if(pe)try{if((await ve.promises.stat(E.filePath)).mtime.getTime()<=pe.mtime){let He=!0;for(let Ee of pe.dependencies){if(!ve.existsSync(Ee)){He=!1;break}if((await ve.promises.stat(Ee)).mtime.getTime()>pe.mtime){He=!1;break}}if(He){let Ee=pe.output;if(R)Ee=me(Ee,{preserveHead:!0});let gt=W.get(E.filePath);return{route:E,content:Ee,status:gt?.status??await qn(E.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(E.filePath,O);if(Ie){let je=Ie;if(R)je=me(je,{preserveHead:!0});let He=W.get(E.filePath);return{route:E,content:je,status:He?.status??await qn(E.filePath),headers:He?.headers}}}let he=ue?await q(E.filePath):await Bun.file(E.filePath).text(),Re=Ct(he),{classifyAllScripts:Y}=await import("./chunk-8dbnvypv.js"),Le=Y(he),Ve=Le.server.map((pe)=>pe.content),fe=he;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let ge={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,ge,E.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,ge,E.filePath,O,Ke);let Ie=performance.now()-pe,je=ie.relative(p,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,ge,E.filePath,O,Ke);if(!R)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-fdcrrpgn.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${pe(He,ge)}</script>`})}if(R)Me=me(Me,{preserveHead:!0});if(ue&&xe)await Q(E.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-j00h4d3w.js"),lt=Kn(ge),mt=ge.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=ge.streamBoundaries||{},Ie={...O,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...ge,$boundary:gt},E.filePath,Ie,new Set)}})),He=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!He.has(Ee.id)),...je]}if(lt&&lt.length>0)De.add(E.pattern);else lt=void 0;let Kt=Fe(ge),Xt=ze(ge);if(xe)W.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Ue=8,qe=async()=>{ye.clear(),I.clear();for(let E=0;E<k.length;E+=Ue){let F=k.slice(E,E+Ue),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let E=0;E<M.length;E+=Ue){let F=M.slice(E,E+Ue),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await kt(p);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||at+1;l=Pt({wsPort:E,verbose:!1}),m=l.start(E)}let _t=(E,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(E.includes("</head>"))return E.replace("</head>",`${V}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+E};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Ni({port:at,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",V=ie.join(p,z,F.pathname),we=ie.join(p,F.pathname),We=ie.join(Ce,F.pathname);if([V,we,We].some((O)=>w(O,p,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,p,S))return qt(V);if(se?.isFile()&&!w(we,p,S))return qt(we);if(Q?.isFile()&&!w(We,p,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let xe=`<${O} />`,ue={...buildConfig,autoShell:!1},he=await processDirectives(xe,{},ie.join(p,"components",`${O}.stx`),ue,new Set);return new Response(he,{headers:{"Content-Type":"text/html"}})}catch(xe){return new Response(`<div class="stx-async-error">${xe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:O}=await import("./chunk-v70hfs6d.js"),xe=await O(E,{publicDir:ie.join(p,z),cacheDir:a(p,"cache","img")});if(xe)return xe}if(oe)try{let O=await oe.handleRequest(E);if(O.status!==404)return O}catch{}if(G[F.pathname])try{return await G[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(E);if(q)return q;let J=xn(F.pathname,k);if(J){let O=ye.get(J.route.pattern),xe=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||xe){let ue=await j(J.route,J.params);if(ue)O=ue}if(O){let ue=O.status??200,he=O.headers??{},Re=(J.route.filePath?Be(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await de(404);if(Ve){let fe=Ve;if(fe=await f(fe,p),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=rt(F.pathname,J.params,Re,F.search),Ve=st(Le,null,E,{isServer:!0}),fe=await ot(Re.middleware,Ve);if(fe.redirect){let ge=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",ge),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:ge,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ge}</title></head><body><h1>Error ${ge}</h1><p>${Ke}</p></body></html>`,{status:ge,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let ge=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${ge}</head>`)}}let Y=O.content;if(R&&lo(E)){let Le=ke(Y),Ve=ce(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ge=fe?ao(fe[1].trim()):"";if(Object.keys(J.params).length>0)Y=_t(Y,J.params);Y=await f(Y,p);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...ge&&{"X-STX-Title":encodeURIComponent(ge)},[fi]:bs(),..._(),"Cache-Control":Ae}})}if(R)Y=An(R,Y);if(Object.keys(J.params).length>0)Y=_t(Y,J.params);if(Y=await f(Y,p),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.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 Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.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 Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-j00h4d3w.js");return Ve(Le(Y,O.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...he}})}}if(M.length>0){let O=M.map((ue)=>ue.route),xe=xn(F.pathname,O);if(xe){let ue=I.get(xe.route.pattern);if(ue){let he=ue.content;if(R)he=An(R,he);if(Object.keys(xe.params).length>0)he=_t(he,xe.params);if(he=await f(he,p),c)he=Xe(he,m);return new Response(he,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let he=I.get(ue)||I.get(ue+"/");if(he){let Re=he.content;if(R)Re=An(R,Re);if(Re=await f(Re,p),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Qe(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Te=ye.get("/");if(Te){let O=Te.content;if(O=await f(O,p),c)O=Xe(O,m);if(s.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;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await de(404);if(Je){let O=Je;if(O=await f(O,p),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await de(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
2029
- ${E.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
2027
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
2028
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ni}=globalThis.Bun;import xe from"fs";import ie from"path";async function qn(t){try{return Tt(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".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"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function $n(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-1cdanx2v.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-ka7qdsha.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",C=ie.join(v,x);if(!xe.existsSync(C)&&!g._layerPageDirs?.some((D)=>xe.existsSync(D)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],_=[];for(let{dir:D,prefix:F}of H)if(xe.existsSync(D)){let z=N(ie.dirname(D),{pagesDir:ie.basename(D)});for(let V of z){let ve=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:ve},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,E=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await uo(u,s.stxOptions?.shell),L){if(E=await Tr(L,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}nt(),await st(u);let B=rt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let K={},ee=null;try{let{loadStxConfig:D}=await import("./chunk-1cdanx2v.js"),F=await D(u);if(F?.apiRouter)ee=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){K=F.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-12v4d123.js"),ve=F.broadcasting;await z(ve);let Ue=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ue}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let ye=new Map,De=new Set,ae=async(D)=>{let F=pr(C,D);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},U=new Map,j=async(D,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:Ue,injectRouterScript:Ge}=await import("./chunk-1cdanx2v.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-5achv4zv.js"),ke=await Ue(u),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(u,pe)},M={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,ue=M.cache!==!1;if(ue&&be){let pe=J.get(D.filePath);if(pe)try{if((await xe.promises.stat(D.filePath)).mtime.getTime()<=pe.mtime){let Be=!0;for(let Ee of pe.dependencies){if(!xe.existsSync(Ee)){Be=!1;break}if((await xe.promises.stat(Ee)).mtime.getTime()>pe.mtime){Be=!1;break}}if(Be){let Ee=pe.output;if(E)Ee=he(Ee,{preserveHead:!0});let gt=U.get(D.filePath);return{route:D,content:Ee,status:gt?.status??await qn(D.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(D.filePath,M);if(Ie){let je=Ie;if(E)je=he(je,{preserveHead:!0});let Be=U.get(D.filePath);return{route:D,content:je,status:Be?.status??await qn(D.filePath),headers:Be?.headers}}}let ge=ue?await q(D.filePath):await Bun.file(D.filePath).text(),Re=Tt(ge),{classifyAllScripts:Y}=await import("./chunk-1cdanx2v.js"),Le=Y(ge),We=Le.server.map((pe)=>pe.content),fe=ge;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let me={__filename:D.filePath,__dirname:ie.dirname(D.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let pe of We)try{await V(pe,me,D.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",D.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,me,D.filePath,M,Ke);let Ie=performance.now()-pe,je=ie.relative(u,D.filePath)||D.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,D.filePath,M,Ke);if(!E)Me=await Ge(Me,{router:M.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-j4rb9rxx.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Ie;return`<script${je}>${pe(Be,me)}</script>`})}if(E)Me=he(Me,{preserveHead:!0});if(ue&&be)await Z(D.filePath,Me,Ke,M);let{extractStreamBoundaries:Kn}=await import("./chunk-c9rwnsk7.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=me.streamBoundaries||{},Ie={...M,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...me,$boundary:gt},D.filePath,Ie,new Set)}})),Be=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!Be.has(Ee.id)),...je]}if(lt&&lt.length>0)De.add(D.pattern);else lt=void 0;let Kt=He(me),Xt=Ve(me);if(be)U.set(D.filePath,{status:Kt,headers:Xt});return{route:D,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${D.pattern}${e.reset}:`,z),null}},Ne=8,qe=async()=>{ye.clear(),I.clear();for(let D=0;D<k.length;D+=Ne){let F=k.slice(D,D+Ne),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let D=0;D<_.length;D+=Ne){let F=_.slice(D,D+Ne),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Et(u);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let D=s.hmrPort||et+1;l=Rt({wsPort:D,verbose:!1}),m=l.start(D)}let Lt=(D,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(D.includes("</head>"))return D.replace("</head>",`${V}</head>`);if(D.includes("<body"))return D.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+D};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ni({port:et,async fetch(D){let F=new URL(D.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),ve=ie.join(u,F.pathname),Ue=ie.join($e,F.pathname);if([V,ve,Ue].some((M)=>w(M,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Z]=await Promise.all([xe.promises.stat(V).catch(()=>null),xe.promises.stat(ve).catch(()=>null),xe.promises.stat(Ue).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(oe?.isFile()&&!w(ve,u,S))return qt(ve);if(Z?.isFile()&&!w(Ue,u,S))return qt(Ue);if(F.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${M}.stx`),ue,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-t2mjeezd.js"),be=await M(D,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(ee)try{let M=await ee.handleRequest(D);if(M.status!==404)return M}catch{}if(K[F.pathname])try{return await K[F.pathname](D)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await R(D);if(q)return q;let J=kn(F.pathname,k);if(J){let M=ye.get(J.route.pattern),be=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let ue=await j(J.route,J.params);if(ue)M=ue}if(M){let ue=M.status??200,ge=M.headers??{},Re=(J.route.filePath?ze(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let We=await ae(404);if(We){let fe=We;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=ot(F.pathname,J.params,Re,F.search),We=it(Le,null,D,{isServer:!0}),fe=await at(Re.middleware,We);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${me}</head>`)}}let Y=M.content;if(E&&po(D)){let Le=Ce(Y),We=le(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?lo(fe[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=se(Y,Ke),new Response(Y,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":We?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[hi]:vs(),...T(),"Cache-Control":Pe}})}if(E)Y=In(E,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.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 Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.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 Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:We}=await import("./chunk-c9rwnsk7.js");return We(Le(Y,M.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(_.length>0){let M=_.map((ue)=>ue.route),be=kn(F.pathname,M);if(be){let ue=I.get(be.route.pattern);if(ue){let ge=ue.content;if(E)ge=In(E,ge);if(Object.keys(be.params).length>0)ge=Lt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let ge=I.get(ue)||I.get(ue+"/");if(ge){let Re=ge.content;if(E)Re=In(E,Re);if(Re=await f(Re,u),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(tt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=ye.get("/");if(ke){let M=ke.content;if(M=await f(M,u),c)M=Xe(M,m);if(s.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(D){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${D}
2029
+ ${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
2030
2030
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
2031
- ${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
2032
- ${e.yellow}Routes:${e.reset}`);let jt=[...ur(k,p)];for(let{route:E}of M)jt.push(`${E.pattern}`);if(jt.forEach((E,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${E}`)}),console.log(`
2033
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(ve.existsSync(F)){let V=await Bun.file(F).text();E=St(V)}let z=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!E,sidebarConfig:E})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(se)=>se.startsWith("public/")||se.startsWith("public\\"),F=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,V=()=>{let se=new Set([p,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let q of Object.values(Q.resources)){if(!ve.existsSync(q))continue;let J=ve.realpathSync(q);if(![...se].some((Te)=>J===Te||J.startsWith(`${Te}${ie.sep}`)))se.add(J)}for(let[Q,q]of z)if(!se.has(Q))q.close(),z.delete(Q);for(let Q of se)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(q,J)=>{We(Q,q,J).catch((Te)=>console.error("[stx] Layer rebuild failed:",Te))}))},we=Promise.resolve(),We=(se,Q,q)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,q)),we),Ge=async(se,Q,q)=>{if(!q||Et(q))return;if($t(q)){if(g._layerGraph){let J=await h(p);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(E(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),be.clear(),ee();try{let{invalidateFileCache:J,templateCache:Te}=await import("./chunk-zc8cz12e.js");J(ie.resolve(se,q)),Te.delete(ie.resolve(se,q))}catch{}if(L&&q){if(ie.resolve(se,q)===L||ie.basename(L)===q){let Te=await Cr(L,s.stxOptions||{});if(Te)R=Te}}if(await qe(),await sn(p),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),be.clear(),ee();try{let{invalidateFileCache:J,templateCache:Te}=await import("./chunk-zc8cz12e.js");J(ie.resolve(se,q)),Te.delete(ie.resolve(se,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Tt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let se of z.values())se.close();if(l)ht();Lt.stop(),process.exit(0)})}return!0}export{Ks,Xs,Gs,Js,hr,Ys,Zs,Qs,Wi,qi,yr,br,Cn,En,$n};
2031
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
2032
+ ${e.yellow}Routes:${e.reset}`);let jt=[...fr(k,u)];for(let{route:D}of _)jt.push(`${D.pattern}`);if(jt.forEach((D,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${D}`)}),console.log(`
2033
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let D,F=ie.join(C,"index.stx");if(xe.existsSync(F)){let V=await Bun.file(F).text();D=St(V)}let z=g?.app?.window??{};await dt(et,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!D,sidebarConfig:D})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let D=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),F=(oe)=>{let Z=oe.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},z=new Map,V=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>ie.dirname(Z))??[]].filter((Z)=>xe.existsSync(Z)).map((Z)=>xe.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!xe.existsSync(q))continue;let J=xe.realpathSync(q);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Z,q]of z)if(!oe.has(Z))q.close(),z.delete(Z);for(let Z of oe)if(!z.has(Z)&&xe.existsSync(Z))z.set(Z,xe.watch(Z,{recursive:!0},(q,J)=>{Ue(Z,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},ve=Promise.resolve(),Ue=(oe,Z,q)=>(ve=ve.catch(()=>{}).then(()=>Ge(oe,Z,q)),ve),Ge=async(oe,Z,q)=>{if(!q||Ct(q))return;if($t(q)){if(g._layerGraph){let J=await h(u);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[C,...J._layerPageDirs.slice(1)]:void 0})),V()}if(D(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-5achv4zv.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(L&&q){if(ie.resolve(oe,q)===L||ie.basename(L)===q){let ke=await Tr(L,s.stxOptions||{});if(ke)E=ke}}if(await qe(),await an(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-5achv4zv.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(kt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let oe of z.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Gs,Js,Ys,Zs,br,Qs,eo,to,Xi,Gi,wr,vr,Tn,_n,$n};