@stacksjs/stx 0.2.674 → 0.2.676

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 (244) hide show
  1. package/dist/{chunk-szevd7d5.js → chunk-028e9fty.js} +2 -2
  2. package/dist/{chunk-rr527jt6.js → chunk-078qg8r5.js} +2 -2
  3. package/dist/chunk-0gk78x3r.js +2 -0
  4. package/dist/{chunk-fw413k9q.js → chunk-1b9thkg5.js} +2 -2
  5. package/dist/chunk-1e73whqh.js +2 -0
  6. package/dist/chunk-1rztwjdj.js +130 -0
  7. package/dist/{chunk-srq9fqq8.js → chunk-245sas8r.js} +38 -38
  8. package/dist/chunk-248a88mc.js +2 -0
  9. package/dist/chunk-2nqtmp8c.js +2 -0
  10. package/dist/chunk-2pga7zzb.js +4 -0
  11. package/dist/{chunk-bkkpq8dx.js → chunk-304dbbsw.js} +10 -10
  12. package/dist/{chunk-z22zy22p.js → chunk-34e8e8te.js} +2 -2
  13. package/dist/{chunk-md2jn67b.js → chunk-374nhgyf.js} +2 -2
  14. package/dist/chunk-3bfegbpw.js +2 -0
  15. package/dist/chunk-3gdt16xa.js +2 -0
  16. package/dist/chunk-3wsm9g9c.js +2 -0
  17. package/dist/chunk-3xx9d934.js +2 -0
  18. package/dist/{chunk-ham5x7ts.js → chunk-4fhbh04h.js} +4 -4
  19. package/dist/{chunk-5vt48yce.js → chunk-4jnv2v5e.js} +9 -9
  20. package/dist/chunk-4rk5qnqf.js +24 -0
  21. package/dist/chunk-526mf3fr.js +4 -0
  22. package/dist/chunk-54zkkxmb.js +2 -0
  23. package/dist/{chunk-kdebh22m.js → chunk-551s7ha0.js} +10 -10
  24. package/dist/chunk-5v7vm8cv.js +14 -0
  25. package/dist/{chunk-rdr09efy.js → chunk-5z0q3qv3.js} +5 -5
  26. package/dist/{chunk-6sjtyd0k.js → chunk-5z8mq37c.js} +4 -4
  27. package/dist/{chunk-ce6zddpf.js → chunk-6beg47t4.js} +2 -2
  28. package/dist/{chunk-trz8z4j4.js → chunk-6bwca55g.js} +37 -37
  29. package/dist/chunk-6kam8r5y.js +2 -0
  30. package/dist/{chunk-tddnb5bv.js → chunk-6ycyaf5g.js} +2 -2
  31. package/dist/chunk-707sx5sk.js +20 -0
  32. package/dist/chunk-78d5tn4r.js +2 -0
  33. package/dist/{chunk-pb6erpj3.js → chunk-78x52gz3.js} +5 -5
  34. package/dist/{chunk-zp79zkkd.js → chunk-78yjmbbs.js} +2 -2
  35. package/dist/{chunk-v21bhhjb.js → chunk-7j7h1eg3.js} +1 -1
  36. package/dist/{chunk-zmg1peyg.js → chunk-8aq07a1j.js} +3 -3
  37. package/dist/chunk-8p92r2sc.js +2 -0
  38. package/dist/chunk-909ymsjz.js +2 -0
  39. package/dist/{chunk-r7fdw2v5.js → chunk-97h9ga3b.js} +3 -3
  40. package/dist/chunk-9859r1d5.js +2 -0
  41. package/dist/{chunk-25zmy8q6.js → chunk-9wdd7eq6.js} +2 -2
  42. package/dist/{chunk-p6qd7ad0.js → chunk-a2zb5fgg.js} +2 -2
  43. package/dist/chunk-arh1qgmp.js +2 -0
  44. package/dist/chunk-b18x0v21.js +2 -0
  45. package/dist/chunk-b23vscaq.js +2 -0
  46. package/dist/{chunk-4b9s7wgy.js → chunk-be2rswkw.js} +2 -2
  47. package/dist/{chunk-qz5b8ed4.js → chunk-bh19ezq0.js} +5 -5
  48. package/dist/chunk-bm42rsaa.js +2 -0
  49. package/dist/{chunk-cbjabv1w.js → chunk-bpj387yx.js} +6 -6
  50. package/dist/chunk-c4enpsj8.js +2 -0
  51. package/dist/chunk-cdbaanmx.js +2 -0
  52. package/dist/chunk-cfm6a679.js +2 -0
  53. package/dist/chunk-cs8wq7nv.js +2 -0
  54. package/dist/{chunk-hegfgw27.js → chunk-cxgremn0.js} +5 -5
  55. package/dist/chunk-d2xf5hh9.js +2 -0
  56. package/dist/{chunk-rym0309c.js → chunk-d4ch6exz.js} +3 -3
  57. package/dist/chunk-dda8pdya.js +2 -0
  58. package/dist/{chunk-7adznted.js → chunk-dera8fmc.js} +2 -2
  59. package/dist/chunk-dmd7mgjw.js +3 -0
  60. package/dist/chunk-ds91e0fe.js +2 -0
  61. package/dist/{chunk-hgry3mjd.js → chunk-dxh45gve.js} +1 -1
  62. package/dist/chunk-e492je6q.js +2 -0
  63. package/dist/{chunk-7j1zgrnf.js → chunk-ehzd1yc6.js} +9 -9
  64. package/dist/chunk-etz2dmec.js +2 -0
  65. package/dist/{chunk-4s8zacxg.js → chunk-f26n6y9p.js} +4 -4
  66. package/dist/{chunk-4w6baw62.js → chunk-fbrgz3s8.js} +2 -2
  67. package/dist/chunk-fd72t30s.js +2 -0
  68. package/dist/{chunk-sqn3y9qt.js → chunk-fdvfzknd.js} +2 -2
  69. package/dist/chunk-ft3f9nj0.js +2 -0
  70. package/dist/{chunk-dgc1a3yt.js → chunk-fzc98qgn.js} +7 -7
  71. package/dist/{chunk-s0vtjyyj.js → chunk-g12ht81a.js} +2 -2
  72. package/dist/chunk-g6gqja52.js +2 -0
  73. package/dist/{chunk-hb3edeq9.js → chunk-ga5kjf9b.js} +6 -6
  74. package/dist/chunk-ggwvnpwj.js +2 -0
  75. package/dist/{chunk-hsmcbh0p.js → chunk-ghm9f13q.js} +5 -5
  76. package/dist/chunk-gx6wxmbv.js +2 -0
  77. package/dist/chunk-gz5rvwgx.js +2 -0
  78. package/dist/chunk-hamk3dky.js +2 -0
  79. package/dist/{chunk-vayhx642.js → chunk-haz2ezyk.js} +2 -2
  80. package/dist/chunk-hh58k0nh.js +3 -0
  81. package/dist/chunk-hqj28381.js +3 -0
  82. package/dist/chunk-j60jye3e.js +25 -0
  83. package/dist/chunk-jjet6qxq.js +2 -0
  84. package/dist/chunk-jk7chxkt.js +2 -0
  85. package/dist/{chunk-d09q93yf.js → chunk-jv021x8e.js} +2 -2
  86. package/dist/{chunk-pg2v1pb5.js → chunk-k06n5bjp.js} +3 -3
  87. package/dist/{chunk-35ezh7de.js → chunk-k72jqz6a.js} +3 -3
  88. package/dist/chunk-kn34esxw.js +2 -0
  89. package/dist/chunk-kqbpkg8n.js +2 -0
  90. package/dist/{chunk-aet1pgw7.js → chunk-krcd3039.js} +74 -74
  91. package/dist/{chunk-asezs2n3.js → chunk-kxj8e1gd.js} +6 -6
  92. package/dist/{chunk-5zhp87wv.js → chunk-mabja59q.js} +2 -2
  93. package/dist/chunk-mf19qxgv.js +3 -0
  94. package/dist/chunk-mjsebtg6.js +2 -0
  95. package/dist/{chunk-fd49fahd.js → chunk-mn47s2ef.js} +5 -5
  96. package/dist/{chunk-nj343mw2.js → chunk-mq915g3j.js} +5 -5
  97. package/dist/chunk-n63r9b4f.js +2 -0
  98. package/dist/{chunk-j6m8xqh3.js → chunk-n8wvqnfc.js} +2 -2
  99. package/dist/chunk-n94ts3t9.js +21 -0
  100. package/dist/{chunk-w7t2cfgy.js → chunk-p27ptd9f.js} +65 -65
  101. package/dist/{chunk-t0k16vqv.js → chunk-p9az13b2.js} +2 -2
  102. package/dist/chunk-pwn0j1vq.js +2 -0
  103. package/dist/chunk-q1jcf6vm.js +2 -0
  104. package/dist/{chunk-am2w363p.js → chunk-q3gactm1.js} +4 -4
  105. package/dist/chunk-q3nnaxf9.js +2 -0
  106. package/dist/{chunk-w3d98907.js → chunk-q4rejyd2.js} +2 -2
  107. package/dist/{chunk-hz4x7h0n.js → chunk-qbzqary0.js} +5 -5
  108. package/dist/{chunk-a4p18ybc.js → chunk-qr7a378v.js} +3 -3
  109. package/dist/{chunk-bsajk82t.js → chunk-qwdcts9w.js} +19 -19
  110. package/dist/chunk-rc79yyqx.js +2 -0
  111. package/dist/{chunk-yx3dpdwc.js → chunk-rfc5pdv2.js} +3 -3
  112. package/dist/chunk-rnws0dh3.js +2 -0
  113. package/dist/chunk-rxxajm31.js +31 -0
  114. package/dist/{chunk-thceyzj6.js → chunk-rza1p6e4.js} +2 -2
  115. package/dist/chunk-s73z8zss.js +11 -0
  116. package/dist/chunk-s8qe247r.js +2 -0
  117. package/dist/{chunk-d1a86qx8.js → chunk-sptewgky.js} +1 -1
  118. package/dist/{chunk-mwnhdsbp.js → chunk-sqh3tvtw.js} +2 -2
  119. package/dist/{chunk-6s7tvmqp.js → chunk-sr3hmrah.js} +2 -2
  120. package/dist/chunk-sswy3tfc.js +2 -0
  121. package/dist/chunk-swxznm5v.js +2 -0
  122. package/dist/{chunk-9dtbvjpp.js → chunk-tmqrbs98.js} +31 -20
  123. package/dist/chunk-tst8p27s.js +12 -0
  124. package/dist/chunk-tz09earb.js +2 -0
  125. package/dist/{chunk-fbmth6xv.js → chunk-vay5v6sj.js} +13 -13
  126. package/dist/{chunk-ck2e3e47.js → chunk-vd5w1jaz.js} +3 -3
  127. package/dist/chunk-vewt3464.js +2 -0
  128. package/dist/{chunk-xghcsg3f.js → chunk-vg1pg6yt.js} +1 -1
  129. package/dist/{chunk-s2wptfm1.js → chunk-wav0xbnb.js} +2 -2
  130. package/dist/chunk-whzvx5w5.js +2 -0
  131. package/dist/chunk-wk1gt95z.js +2 -0
  132. package/dist/{chunk-t9kxhe46.js → chunk-wr1gm35v.js} +1 -1
  133. package/dist/{chunk-faakv1p6.js → chunk-wscnjtss.js} +2 -2
  134. package/dist/{chunk-t79jfpv6.js → chunk-x4q4bx3q.js} +2 -2
  135. package/dist/chunk-x63f2ywm.js +2 -0
  136. package/dist/{chunk-y1pcdeg9.js → chunk-x7wr720m.js} +5 -5
  137. package/dist/chunk-xk7cp691.js +2 -0
  138. package/dist/chunk-xna6b7km.js +2 -0
  139. package/dist/{chunk-v6peecfp.js → chunk-xnx06qqt.js} +2 -2
  140. package/dist/chunk-xw4rm5zj.js +2 -0
  141. package/dist/{chunk-5qtthtg3.js → chunk-y34tyrpb.js} +7 -7
  142. package/dist/chunk-yar7fwrb.js +2 -0
  143. package/dist/{chunk-2zzc7006.js → chunk-yn9kvsk1.js} +2 -2
  144. package/dist/chunk-yt33wzqk.js +2 -0
  145. package/dist/chunk-z35ftpqp.js +421 -0
  146. package/dist/{chunk-4bgjrrvz.js → chunk-z7ghjs7w.js} +1 -1
  147. package/dist/chunk-zq7xbc1k.js +2 -0
  148. package/dist/cli.js +22 -22
  149. package/dist/client/signals-for-runtime.js +16 -5
  150. package/dist/craft-entry.js +2 -2
  151. package/dist/craft.js +2 -2
  152. package/dist/native/compiler/headwind-to-style.js +13 -1
  153. package/dist/native/compiler/html-to-ir.d.ts +2 -0
  154. package/dist/native/compiler/html-to-ir.js +9 -0
  155. package/dist/native/compiler/ir.d.ts +1 -0
  156. package/dist/native/compiler/render-screen.js +4 -3
  157. package/dist/native/compiler/style-config.d.ts +3 -0
  158. package/dist/native/compiler/style-config.js +5 -0
  159. package/dist/native/components/primitives.d.ts +2 -0
  160. package/dist/native/event-names.js +2 -0
  161. package/dist/native/prop-names.js +1 -0
  162. package/dist/native/runtime/craft-bridge.js +15 -8
  163. package/dist/pwa.js +3 -3
  164. package/dist/signal-processing.js +75 -16
  165. package/dist/ssg-static-paths.d.ts +12 -0
  166. package/dist/ssg-static-paths.js +62 -0
  167. package/dist/ssg.d.ts +2 -4
  168. package/dist/ssg.js +43 -47
  169. package/dist/utils.js +1 -1
  170. package/package.json +2 -2
  171. package/dist/chunk-0jwdcqj8.js +0 -2
  172. package/dist/chunk-0mwdq478.js +0 -2
  173. package/dist/chunk-0nfqgv4n.js +0 -4
  174. package/dist/chunk-1y6egkty.js +0 -2
  175. package/dist/chunk-280p4q7a.js +0 -2
  176. package/dist/chunk-2881tcqt.js +0 -2
  177. package/dist/chunk-2a775q7x.js +0 -2
  178. package/dist/chunk-2asdbd5e.js +0 -2
  179. package/dist/chunk-34yj93hh.js +0 -2
  180. package/dist/chunk-40tswfe7.js +0 -21
  181. package/dist/chunk-41de209e.js +0 -2
  182. package/dist/chunk-506mv7hb.js +0 -3
  183. package/dist/chunk-5s1ay9mv.js +0 -2
  184. package/dist/chunk-7kznee1g.js +0 -2
  185. package/dist/chunk-7mvz972c.js +0 -12
  186. package/dist/chunk-80zgyaqe.js +0 -2
  187. package/dist/chunk-84tqb1rn.js +0 -2
  188. package/dist/chunk-8azm7nha.js +0 -2
  189. package/dist/chunk-902qnyg0.js +0 -2
  190. package/dist/chunk-9n6jwcpb.js +0 -2
  191. package/dist/chunk-a6y8td0d.js +0 -2
  192. package/dist/chunk-a7kt1ts4.js +0 -2
  193. package/dist/chunk-a81y8g40.js +0 -2
  194. package/dist/chunk-aft1zc84.js +0 -2
  195. package/dist/chunk-bawq4fqy.js +0 -31
  196. package/dist/chunk-bdp2r0v4.js +0 -2
  197. package/dist/chunk-brtvm8mb.js +0 -2
  198. package/dist/chunk-bvzr9zqt.js +0 -2
  199. package/dist/chunk-cbvgtf3m.js +0 -2
  200. package/dist/chunk-cfydbaeq.js +0 -2
  201. package/dist/chunk-dq8c3h4n.js +0 -2
  202. package/dist/chunk-e36pne7n.js +0 -2
  203. package/dist/chunk-e62qfexp.js +0 -2
  204. package/dist/chunk-eq5jzaj5.js +0 -2
  205. package/dist/chunk-f9zyf9n6.js +0 -421
  206. package/dist/chunk-fb7t1nn9.js +0 -24
  207. package/dist/chunk-fr39emcz.js +0 -2
  208. package/dist/chunk-fsq13amm.js +0 -2
  209. package/dist/chunk-fxh12vqd.js +0 -2
  210. package/dist/chunk-gcc9fa33.js +0 -2
  211. package/dist/chunk-h6t2ney6.js +0 -2
  212. package/dist/chunk-hvtzw1jh.js +0 -2
  213. package/dist/chunk-j8g5cvvm.js +0 -2
  214. package/dist/chunk-jzjpyyw2.js +0 -2
  215. package/dist/chunk-k1b8x73j.js +0 -2
  216. package/dist/chunk-nw9bdk2n.js +0 -2
  217. package/dist/chunk-p4jkswz8.js +0 -2
  218. package/dist/chunk-p4r90vqf.js +0 -2
  219. package/dist/chunk-p8bgy5tt.js +0 -2
  220. package/dist/chunk-pqqe2b6m.js +0 -11
  221. package/dist/chunk-q6nwcav4.js +0 -2
  222. package/dist/chunk-qmqavdz2.js +0 -2
  223. package/dist/chunk-qpw72bty.js +0 -2
  224. package/dist/chunk-qwnh1kj6.js +0 -2
  225. package/dist/chunk-qy9m6qdn.js +0 -2
  226. package/dist/chunk-qychcdsm.js +0 -2
  227. package/dist/chunk-rj3w1ama.js +0 -2
  228. package/dist/chunk-rv39s5az.js +0 -20
  229. package/dist/chunk-sf0r963g.js +0 -2
  230. package/dist/chunk-ss820yys.js +0 -2
  231. package/dist/chunk-t4j9g2vh.js +0 -2
  232. package/dist/chunk-trh7s6k3.js +0 -130
  233. package/dist/chunk-ttemwrbx.js +0 -2
  234. package/dist/chunk-twqzn21x.js +0 -14
  235. package/dist/chunk-v14rq8b4.js +0 -3
  236. package/dist/chunk-vdxg7e1y.js +0 -4
  237. package/dist/chunk-vq513cxx.js +0 -2
  238. package/dist/chunk-vvq8xe3n.js +0 -2
  239. package/dist/chunk-w8t31bn9.js +0 -2
  240. package/dist/chunk-x1kz4d7j.js +0 -2
  241. package/dist/chunk-xaa36b0x.js +0 -3
  242. package/dist/chunk-xcsyqwxf.js +0 -25
  243. package/dist/chunk-xn9jrjzh.js +0 -2
  244. package/dist/chunk-z97bwx8m.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{re,le,cn,Rt,At,g,n,pe,d}from"./chunk-f9zyf9n6.js";import{gt,Te,na,Zs,s}from"./chunk-aet1pgw7.js";import{oe,dr,we,D,hn}from"./chunk-bsajk82t.js";import{vt,Qn,Qr,es,ts,wt,xt,St,kt,_t,Ct,Je}from"./chunk-4s8zacxg.js";import{Gr,o,R}from"./chunk-srq9fqq8.js";import{ut,Ei,Se,O,Ti,Bs,Rr,He,$i,ke}from"./chunk-bawq4fqy.js";import{Jn,Yn}from"./chunk-4b9s7wgy.js";import{xn}from"./chunk-sqn3y9qt.js";import{e,en,Wn,h}from"./chunk-kdebh22m.js";import{qe}from"./chunk-bkkpq8dx.js";import{Ee}from"./chunk-md2jn67b.js";import{U,me,he}from"./chunk-twqzn21x.js";import{c}from"./chunk-v14rq8b4.js";import{V}from"./chunk-506mv7hb.js";async function Fn(t){try{let r=await Bun.file(t).text(),i=zn(r),p=Nn(r,t),a=Un(r,i),l=Vn(r,i);return{file:t,metrics:i,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
3
- `),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(i?i[1]:"").split(`
4
- `).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 f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)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+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){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 a=qt(t,"foreach","endforeach");if(a>0)i.push({type:"error",category:"syntax",message:`Found ${a} 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 f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)i.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
- `).filter((b)=>b.length>120);if(y.length>0)i.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)i.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Un(t,r){let i=[];if(r.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.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(r.directives.total===0&&r.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Vn(t,r){let i=1;if(i+=r.directives.conditionals*0.1,i+=r.directives.loops*0.5,i+=r.directives.includes*2,i+=r.expressions*0.05,i+=r.components*1,r.scriptLines>10)i+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(i>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function qt(t,r,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function fi(t=["**/*.stx"],r){let i=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);i.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=qn(i);return{results:i,summary:a}}function qn(t){let r=t.length,i=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as Kn,readFile as Xn,readdir as Gn,stat as Kt,writeFile as Zn}from"fs/promises";import $e from"path";function Zt(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 tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function er(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let r=[];async function i(p){let a=await Gn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=$e.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await i(t),r}function or(t,r){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(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(tn.has(y))throw Error(`${r}: client ${Zt(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>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==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";i[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return i}function ir(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Xt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
2
+ import{re,ue,un,At,Pt,g,n,pe,d}from"./chunk-z35ftpqp.js";import{gt,$e,ra,eo,o}from"./chunk-krcd3039.js";import{ie,fr,xe,D,bn}from"./chunk-qwdcts9w.js";import{vt,tr,ts,ns,rs,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-f26n6y9p.js";import{Xr,i,R}from"./chunk-245sas8r.js";import{ut,Ti,ke,O,$i,zs,Pr,Ve,Ri,_e}from"./chunk-rxxajm31.js";import{Zn,Qn}from"./chunk-be2rswkw.js";import{kn}from"./chunk-fdvfzknd.js";import{e,nn,Kn,h}from"./chunk-551s7ha0.js";import{Ke}from"./chunk-304dbbsw.js";import{Te}from"./chunk-374nhgyf.js";import{W,he,ye}from"./chunk-5v7vm8cv.js";import{c}from"./chunk-mf19qxgv.js";import{U}from"./chunk-hh58k0nh.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
3
+ `),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(s?s[1]:"").split(`
4
+ `).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 f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)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+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let s=[],p=qt(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=qt(t,"foreach","endforeach");if(a>0)s.push({type:"error",category:"syntax",message:`Found ${a} 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)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)s.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
+ `).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)s.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function Un(t,r){let s=[];if(r.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)s.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)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(r.directives.total===0&&r.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function Wn(t,r){let s=1;if(s+=r.directives.conditionals*0.1,s+=r.directives.loops*0.5,s+=r.directives.includes*2,s+=r.expressions*0.05,s+=r.components*1,r.scriptLines>10)s+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(s>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function qt(t,r,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function mi(t=["**/*.stx"],r){let s=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);s.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=Vn(s);return{results:s,summary:a}}function Vn(t){let r=t.length,s=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as qn,readFile as Xn,readdir as Gn,stat as Kt,writeFile as Jn}from"fs/promises";import Se from"path";function Zt(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 en=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function er(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let r=[];async function s(p){let a=await Gn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=Se.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await s(t),r}function or(t,r){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(en.has(y))throw Error(`${r}: client ${Zt(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>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==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return s}function ir(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Xt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
6
6
 
7
- `)}function ar(t){if(!t)return null;let r=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(r))return"string";if(/^number$/.test(r))return"number";if(/^boolean$/.test(r))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(r))return"string";return"object"}function cr(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 lr(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 pr(t){let r=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),a=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,f=(y)=>{if(p[y]!=="(")return null;let m=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")m++;else if(S===")"){if(m--,m===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let m=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>m)r.push(`out += ${JSON.stringify(y.slice(m,w.index))};`);r.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),m=w.index+w[0].length}if(m<y.length)r.push(`out += ${JSON.stringify(y.slice(m))};`)};while(l=a.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let m=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?f(i):null;if(m)i=m.end,a.lastIndex=m.end;let b=m?.expression;switch(l[1]){case"if":r.push(`if (${b}) {`);break;case"elseif":r.push(`} else if (${b}) {`);break;case"else":r.push("} else {");break;case"endif":case"endforeach":r.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){r.push(`out += ${JSON.stringify(l[0]+(m?`(${b})`:""))};`);break}let[,S,C,v]=w;r.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),r.join(`
8
- `)}function at(t,r,i,p){if(t[r]!==i)return-1;let a=0,l=null;for(let f=r;f<t.length;f++){let u=t[f];if(l){if(u==="\\"){f++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)a++;else if(u===p){if(p===">"&&t[f-1]==="=")continue;if(a--,a===0)return f+1}}return-1}function Mt(t,r,i){let p=i?"([{<":"([{",a=i?")]}>":")]}",l=[],f=0,u=null,y="";for(let m=0;m<t.length;m++){let b=t[m];if(u){if(y+=b,b==="\\"){y+=t[++m]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))f++;else if(a.includes(b))f--;if(f===0&&r.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((m)=>m.trim()).filter(Boolean)}function ur(t){let r=0,i=null;for(let p=0;p<t.length;p++){let a=t[p];if(i){if(a==="\\"){p++;continue}if(a===i)i=null;continue}if(a==="'"||a==='"'||a==="`"){i=a;continue}if("([{".includes(a))r++;else if(")]}".includes(a))r--;if(r!==0||a!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Gt(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 fr(t){let r=/\bdefineProps\b/.exec(t);if(!r)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<r.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let a={},l={},f=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},m;if(t[u]==="{"){let k=at(t,u,"{","}");if(k===-1)return null;m=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;m=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(y(),t[u]==="<"){let k=at(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(y(),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(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=at(t,u,"{","}");if(k===-1)return null;for(let[j,M]of Lt(t.slice(u,k)))l[j]=M;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of Mt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let j=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(j)a[j[1]]=j[2].trim()}if(x.startsWith("{"))for(let[k,j]of Lt(x)){if(f.push(k),!j.startsWith("{")){let M=Gt(j);if(M)a[k]=M;continue}for(let[M,L]of Lt(j))if(M==="default")l[k]=L;else if(M==="type"){let E=Gt(L);if(E)a[k]=E}}else if(x.startsWith("["))for(let k of Mt(x.slice(1,-1),",",!1))f.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(m.startsWith("{")){f.length=0;for(let k of Mt(m.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let j=ur(k),L=(j===-1?k:k.slice(0,j)).split(":")[0].trim().replace(/^\.\.\./,"");if(!L)continue;if(f.push(L),j!==-1)l[L]=k.slice(j+1).trim()}}else if(f.length===0)f.push(...Object.keys(a));return{text:t.slice(p,u),propNames:f,defaults:l,declared:a,typeName:T}}function Lt(t){let r=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<r.length){let a=/\s*([A-Za-z_$][\w$]*)\s*:/y;a.lastIndex=p;let l=a.exec(r);if(!l)break;p=a.lastIndex;let f=0,u="",y=p;while(p<r.length){let b=r[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")f++;else if(b==="}"||b==="]"||b===")")f--;else if(b===","&&f===0)break;p++}let m=r.slice(y,p).trim();if(m)i.push([l[1],m]);p++}return i}function mr(t,r,i){let a=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!a)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=a[2],f=[],u=[],y={},m={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return f.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=$e.resolve($e.dirname(r),x),j=$e.relative(i,k);return`${v}${j.startsWith(".")?j:`./${j}`}${T}`})),""});let b=fr(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(m,b.declared),l=l.replace(b.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))m[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.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:f,body:l.trim(),propNames:u,defaults:y,declared:m}}function gr(t){let r=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,a,l,f,u)=>{let y=a.toLowerCase();r.add(y);let m=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${m?` data-stx-mod-${y}="${m}"`:""}`}),eventTypes:[...r].sort()}}function hr(t){let r=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,a,l,f)=>{let u=r.length;return r.push({id:u,name:a,expression:f}),` data-stx-bind-${u}=""`}),bindings:r}}function yr(t){let r=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))r.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...r].map((i)=>({name:i}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((r)=>r[1]))].sort().map((r)=>({name:r}))}function Jt(t,r){if(!r||!new Set(["string","number","boolean","object","array"]).has(r.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...r,reflect:r.reflect??r.attribute!==!1}}async function xr(t,r,i){let p=$e.isAbsolute(r.file)?r.file:$e.resolve(t,r.file),a=await Xn(p,"utf8"),l=or(a,p),f=$e.basename(p,".stx"),u=r.name||l.name||er(f),y=`${It(i.prefix||"stx")}-${It(f)}`,m=r.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!tr(m))throw Error(`${p}: invalid custom-element tag "${m}"; tags must be lowercase and contain a hyphen`);let b=r.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([M,L])=>[M,Jt(M,L)])),S=gr(ir(a)),C=hr(S.template),v=mr(a,p,$e.resolve(i.outputDir)),x=pr(C.template);for(let M of v.propNames){if(w[M])continue;let L=v.defaults[M];w[M]=Jt(M,{type:ar(v.declared[M])??cr(L),...L===void 0?{}:{default:lr(L)}})}let T=l.methods||{},k=r.methods||{},j=sr(a,p);return{file:$e.relative(t,p),sourcePath:p,name:u,tag:m,description:r.description||l.description||"",template:C.template,styles:Xt(a),shadowMode:nr(r.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:r.progressive??l.progressive??i.progressive??!0,properties:w,events:r.events||l.events||{},methods:{...T,...k,...j},eventTypes:S.eventTypes,bindings:C.bindings,slots:yr(C.template),cssProperties:br(Xt(a)),scope:v,render:x}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
7
+ `)}function ar(t){if(!t)return null;let r=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(r))return"string";if(/^number$/.test(r))return"number";if(/^boolean$/.test(r))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(r))return"string";return"object"}function cr(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 lr(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 dr(t){let r=[],s=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),a=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,f=(y)=>{if(p[y]!=="(")return null;let m=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")m++;else if(S===")"){if(m--,m===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let m=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>m)r.push(`out += ${JSON.stringify(y.slice(m,w.index))};`);r.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),m=w.index+w[0].length}if(m<y.length)r.push(`out += ${JSON.stringify(y.slice(m))};`)};while(l=a.exec(p)){u(p.slice(s,l.index)),s=l.index+l[0].length;let m=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?f(s):null;if(m)s=m.end,a.lastIndex=m.end;let b=m?.expression;switch(l[1]){case"if":r.push(`if (${b}) {`);break;case"elseif":r.push(`} else if (${b}) {`);break;case"else":r.push("} else {");break;case"endif":case"endforeach":r.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){r.push(`out += ${JSON.stringify(l[0]+(m?`(${b})`:""))};`);break}let[,S,C,v]=w;r.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(s)),r.join(`
8
+ `)}function at(t,r,s,p){if(t[r]!==s)return-1;let a=0,l=null;for(let f=r;f<t.length;f++){let u=t[f];if(l){if(u==="\\"){f++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===s)a++;else if(u===p){if(p===">"&&t[f-1]==="=")continue;if(a--,a===0)return f+1}}return-1}function Mt(t,r,s){let p=s?"([{<":"([{",a=s?")]}>":")]}",l=[],f=0,u=null,y="";for(let m=0;m<t.length;m++){let b=t[m];if(u){if(y+=b,b==="\\"){y+=t[++m]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))f++;else if(a.includes(b))f--;if(f===0&&r.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((m)=>m.trim()).filter(Boolean)}function pr(t){let r=0,s=null;for(let p=0;p<t.length;p++){let a=t[p];if(s){if(a==="\\"){p++;continue}if(a===s)s=null;continue}if(a==="'"||a==='"'||a==="`"){s=a;continue}if("([{".includes(a))r++;else if(")]}".includes(a))r--;if(r!==0||a!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Gt(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 ur(t){let r=/\bdefineProps\b/.exec(t);if(!r)return null;let s=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=s.exec(t);k&&k.index<r.index;k=s.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let a={},l={},f=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},m;if(t[u]==="{"){let k=at(t,u,"{","}");if(k===-1)return null;m=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;m=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(y(),t[u]==="<"){let k=at(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(y(),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(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=at(t,u,"{","}");if(k===-1)return null;for(let[j,M]of Lt(t.slice(u,k)))l[j]=M;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of Mt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let j=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(j)a[j[1]]=j[2].trim()}if(x.startsWith("{"))for(let[k,j]of Lt(x)){if(f.push(k),!j.startsWith("{")){let M=Gt(j);if(M)a[k]=M;continue}for(let[M,L]of Lt(j))if(M==="default")l[k]=L;else if(M==="type"){let E=Gt(L);if(E)a[k]=E}}else if(x.startsWith("["))for(let k of Mt(x.slice(1,-1),",",!1))f.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(m.startsWith("{")){f.length=0;for(let k of Mt(m.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let j=pr(k),L=(j===-1?k:k.slice(0,j)).split(":")[0].trim().replace(/^\.\.\./,"");if(!L)continue;if(f.push(L),j!==-1)l[L]=k.slice(j+1).trim()}}else if(f.length===0)f.push(...Object.keys(a));return{text:t.slice(p,u),propNames:f,defaults:l,declared:a,typeName:T}}function Lt(t){let r=t.trim().replace(/^\{/,"").replace(/\}$/,""),s=[],p=0;while(p<r.length){let a=/\s*([A-Za-z_$][\w$]*)\s*:/y;a.lastIndex=p;let l=a.exec(r);if(!l)break;p=a.lastIndex;let f=0,u="",y=p;while(p<r.length){let b=r[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")f++;else if(b==="}"||b==="]"||b===")")f--;else if(b===","&&f===0)break;p++}let m=r.slice(y,p).trim();if(m)s.push([l[1],m]);p++}return s}function mr(t,r,s){let a=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!a)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=a[2],f=[],u=[],y={},m={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return f.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Se.resolve(Se.dirname(r),x),j=Se.relative(s,k);return`${v}${j.startsWith(".")?j:`./${j}`}${T}`})),""});let b=ur(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(m,b.declared),l=l.replace(b.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))m[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.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:f,body:l.trim(),propNames:u,defaults:y,declared:m}}function gr(t){let r=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,a,l,f,u)=>{let y=a.toLowerCase();r.add(y);let m=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${m?` data-stx-mod-${y}="${m}"`:""}`}),eventTypes:[...r].sort()}}function hr(t){let r=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,a,l,f)=>{let u=r.length;return r.push({id:u,name:a,expression:f}),` data-stx-bind-${u}=""`}),bindings:r}}function yr(t){let r=new Set;for(let s of t.matchAll(/<slot\b([^>]*)>/gi))r.add(s[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...r].map((s)=>({name:s}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((r)=>r[1]))].sort().map((r)=>({name:r}))}function Jt(t,r){if(!r||!new Set(["string","number","boolean","object","array"]).has(r.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...r,reflect:r.reflect??r.attribute!==!1}}async function xr(t,r,s){let p=Se.isAbsolute(r.file)?r.file:Se.resolve(t,r.file),a=await Xn(p,"utf8"),l=or(a,p),f=Se.basename(p,".stx"),u=r.name||l.name||Yn(f),y=`${It(s.prefix||"stx")}-${It(f)}`,m=r.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!er(m))throw Error(`${p}: invalid custom-element tag "${m}"; tags must be lowercase and contain a hyphen`);let b=r.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([M,L])=>[M,Jt(M,L)])),S=gr(ir(a)),C=hr(S.template),v=mr(a,p,Se.resolve(s.outputDir)),x=dr(C.template);for(let M of v.propNames){if(w[M])continue;let L=v.defaults[M];w[M]=Jt(M,{type:ar(v.declared[M])??cr(L),...L===void 0?{}:{default:lr(L)}})}let T=l.methods||{},k=r.methods||{},j=sr(a,p);return{file:Se.relative(t,p),sourcePath:p,name:u,tag:m,description:r.description||l.description||"",template:C.template,styles:Xt(a),shadowMode:nr(r.shadowDOM??l.shadowDOM??s.shadowDOM),progressive:r.progressive??l.progressive??s.progressive??!0,properties:w,events:r.events||l.events||{},methods:{...T,...k,...j},eventTypes:S.eventTypes,bindings:C.bindings,slots:yr(C.template),cssProperties:br(Xt(a)),scope:v,render:x}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -303,7 +303,7 @@ export function defineComponent(Component, definition) {
303
303
  }
304
304
  return Component;
305
305
  }
306
- `}function wr(t){let r=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,y])=>{if(tn.has(u))throw Error(`${t.sourcePath}: ${Zt(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
306
+ `}function wr(t){let r=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),s=Object.entries(t.methods).map(([u,y])=>{if(en.has(u))throw Error(`${t.sourcePath}: ${Zt(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
307
307
  ${y}
308
308
  }`}).join(`
309
309
 
@@ -323,13 +323,13 @@ ${p.imports.length?`${p.imports.join(`
323
323
  `:""}
324
324
  /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
325
325
  export class ${t.name} extends StxElement {
326
- ${i}${f}
326
+ ${s}${f}
327
327
  }
328
328
 
329
329
  defineComponent(${t.name}, ${r});
330
330
  export default ${t.name};
331
331
  `}function ct(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 Sr(t){let r=Object.entries(t.properties).map(([l,f])=>` ${l}${f.required?"":"?"}: ${ct(f)}`).join(`
332
- `),i=Object.entries(t.properties).map(([l,f])=>` ${l}: ${ct(f)}`).join(`
332
+ `),s=Object.entries(t.properties).map(([l,f])=>` ${l}: ${ct(f)}`).join(`
333
333
  `),p=Object.entries(t.events).map(([l,f])=>` ${JSON.stringify(l)}: CustomEvent<${f.detailType||"unknown"}>`).join(`
334
334
  `),a=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
335
335
  `);return`export interface ${t.name}Props {
@@ -341,7 +341,7 @@ ${p}
341
341
  }
342
342
 
343
343
  export declare class ${t.name} extends HTMLElement {
344
- ${i}
344
+ ${s}
345
345
  ${a}
346
346
  readonly updateComplete: Promise<void>
347
347
  requestUpdate(): Promise<void>
@@ -355,12 +355,12 @@ declare global {
355
355
  }
356
356
 
357
357
  export default ${t.name}
358
- `}function Tr(t){return`declare global {
358
+ `}function kr(t){return`declare global {
359
359
  namespace JSX {
360
360
  interface IntrinsicElements {
361
- ${t.map((i)=>{let p=Object.entries(i.properties).map(([l,f])=>` ${JSON.stringify(l)}?: ${ct(f)}`).join(`
362
- `),a=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(`
363
- `);return` ${JSON.stringify(i.tag)}: {
361
+ ${t.map((s)=>{let p=Object.entries(s.properties).map(([l,f])=>` ${JSON.stringify(l)}?: ${ct(f)}`).join(`
362
+ `),a=Object.keys(s.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${s.events[l].detailType||"unknown"}>) => void`).join(`
363
+ `);return` ${JSON.stringify(s.tag)}: {
364
364
  ${p}
365
365
  ${a}
366
366
  children?: unknown
@@ -374,9 +374,9 @@ ${a}
374
374
  }
375
375
 
376
376
  export {}
377
- `}function $r(t){return{schemaVersion:"1.0.0",modules:t.map((r)=>({kind:"javascript-module",path:`./${r.tag}.js`,declarations:[{kind:"class",name:r.name,description:r.description||void 0,customElement:!0,tagName:r.tag,members:Object.entries(r.properties).map(([i,p])=>({kind:"field",name:i,description:p.description,type:{text:ct(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||It(i),reflects:p.reflect})),events:Object.entries(r.events).map(([i,p])=>({name:i,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:r.slots,cssProperties:r.cssProperties}],exports:[{kind:"js",name:r.name,declaration:{name:r.name,module:`./${r.tag}.js`}}]}))}}function Yt(t){if(!t.styles)return"";let r=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(r))return r;return`@scope (${t.tag}) {
377
+ `}function $r(t){return{schemaVersion:"1.0.0",modules:t.map((r)=>({kind:"javascript-module",path:`./${r.tag}.js`,declarations:[{kind:"class",name:r.name,description:r.description||void 0,customElement:!0,tagName:r.tag,members:Object.entries(r.properties).map(([s,p])=>({kind:"field",name:s,description:p.description,type:{text:ct(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||It(s),reflects:p.reflect})),events:Object.entries(r.events).map(([s,p])=>({name:s,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:r.slots,cssProperties:r.cssProperties}],exports:[{kind:"js",name:r.name,declaration:{name:r.name,module:`./${r.tag}.js`}}]}))}}function Yt(t){if(!t.styles)return"";let r=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(r))return r;return`@scope (${t.tag}) {
378
378
  ${r}
379
- }`}function Qt(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Er(t){let r=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),a=Object.fromEntries(t.map((f)=>[f.tag,{template:f.template,styles:f.styles,shadowMode:f.shadowMode,properties:f.properties}])),l=t.map((f)=>`export const render${f.name} = (props = {}, slots = {}) => renderComponent('${f.tag}', props, slots);`).join(`
379
+ }`}function Qt(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Rr(t){let r=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),a=Object.fromEntries(t.map((f)=>[f.tag,{template:f.template,styles:f.styles,shadowMode:f.shadowMode,properties:f.properties}])),l=t.map((f)=>`export const render${f.name} = (props = {}, slots = {}) => renderComponent('${f.tag}', props, slots);`).join(`
380
380
  `);return`const definitions = ${JSON.stringify(a,null,2)};
381
381
  const escapeHTML = (value) => String(value ?? '')
382
382
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -390,7 +390,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
390
390
  Object.assign(values, props);
391
391
  let template = definition.template
392
392
  .replace(new RegExp(${r}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
- .replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
393
+ .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
394
  .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
395
395
  const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
396
396
  if (property.attribute === false || !(name in props)) return [];
@@ -410,21 +410,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
410
410
  }
411
411
 
412
412
  ${l}
413
- `}async function gi(t){let r=$e.resolve(t.inputDir),i=$e.resolve(t.outputDir);if(!(await Kt(r).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${r}`);let a=t.components?.length?t.components:(await rr(r)).map((x)=>({file:x}));if(!a.length)throw Error(`No .stx components found in ${r}`);let l=await Promise.all(a.map((x)=>xr(r,x,t)));l.sort((x,T)=>x.tag.localeCompare(T.tag));let f=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(f.length)throw Error(`Duplicate custom-element tag: ${f[0].tag}`);let u=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await Kn(i,{recursive:!0});let y=[],m=async(x,T)=>{let k=$e.join(i,x);return await Zn(k,T.endsWith(`
413
+ `}async function hi(t){let r=Se.resolve(t.inputDir),s=Se.resolve(t.outputDir);if(!(await Kt(r).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${r}`);let a=t.components?.length?t.components:(await rr(r)).map((x)=>({file:x}));if(!a.length)throw Error(`No .stx components found in ${r}`);let l=await Promise.all(a.map((x)=>xr(r,x,t)));l.sort((x,T)=>x.tag.localeCompare(T.tag));let f=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(f.length)throw Error(`Duplicate custom-element tag: ${f[0].tag}`);let u=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await qn(s,{recursive:!0});let y=[],m=async(x,T)=>{let k=Se.join(s,x);return await Jn(k,T.endsWith(`
414
414
  `)?T:`${T}
415
415
  `,"utf8"),y.push(k),k};await m("runtime.js",vr());for(let x of l){if(await m(`${x.tag}.js`,wr(x)),t.declarations!==!1)await m(`${x.tag}.d.ts`,Sr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:Yt(x);await m(`${x.tag}.css`,t.minify?Qt(T):T)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
- `);if(await m("index.js",b),await m("ssr.js",Er(l)),t.declarations!==!1)await m("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
- `)),await m("custom-elements.d.ts",Tr(l)),await m("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
416
+ `);if(await m("index.js",b),await m("ssr.js",Rr(l)),t.declarations!==!1)await m("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
+ `)),await m("custom-elements.d.ts",kr(l)),await m("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
418
418
  `)}
419
419
  export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
420
420
  ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
421
421
  `)}`);let w;if(t.manifest!==!1)w=await m("custom-elements.json",JSON.stringify($r(l),null,2));let S;if(t.css!==!1){let x=l.filter((T)=>!T.shadowMode&&T.styles).map(Yt).join(`
422
422
 
423
- `);if(x)S=await m("bundle.css",t.minify?Qt(x):x)}let C;if(t.bundle!==!1){C=$e.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[$e.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],j=k.map((M)=>String(M).trim()).filter(Boolean).join(`
423
+ `);if(x)S=await m("bundle.css",t.minify?Qt(x):x)}let C;if(t.bundle!==!1){C=Se.join(s,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Se.join(s,"index.js")],outdir:s,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],j=k.map((M)=>String(M).trim()).filter(Boolean).join(`
424
424
  `);throw AggregateError(k,`Failed to bundle component library${j?`
425
425
  ${j}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
426
  `);throw AggregateError(x.logs,`Failed to bundle component library${T?`
427
- ${T}`:""}`)}if(y.push(C),t.sourcemap==="external")y.push(`${C}.map`)}let v=await Promise.all(y.map(async(x)=>(await Kt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:$e.join(i,`${x.tag}.js`)})),files:y,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}var{serve:Hr}=globalThis.Bun;import Ht from"fs";import et from"path";function lt(){return`
427
+ ${T}`:""}`)}if(y.push(C),t.sourcemap==="external")y.push(`${C}.map`)}let v=await Promise.all(y.map(async(x)=>(await Kt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Se.join(s,`${x.tag}.js`)})),files:y,manifest:w,bundle:C,cssBundle:S,totalBytes:v.reduce((x,T)=>x+T,0)}}var{serve:Hr}=globalThis.Bun;import Ht from"fs";import et from"path";function lt(){return`
428
428
  /* Theme selector for code blocks */
429
429
  .theme-selector {
430
430
  margin: 1rem 0;
@@ -499,17 +499,17 @@ else {
499
499
  document.addEventListener('DOMContentLoaded', changeTheme);`}function ft(t){if(Object.keys(t).length===0)return"";return`
500
500
  <div class="frontmatter">
501
501
  <h3>Frontmatter</h3>
502
- ${Object.entries(t).map(([r,i])=>`
502
+ ${Object.entries(t).map(([r,s])=>`
503
503
  <div class="frontmatter-item">
504
504
  <span class="frontmatter-label">${r}:</span>
505
- <span>${Array.isArray(i)?i.join(", "):String(i)}</span>
505
+ <span>${Array.isArray(s)?s.join(", "):String(s)}</span>
506
506
  </div>`).join("")}
507
- </div>`}import nn from"net";async function Pr(t){return new Promise((r)=>{let i=nn.createServer();i.once("error",()=>r(!1)),i.once("listening",()=>{i.close(()=>r(!0))}),i.listen(t,"0.0.0.0")})}async function Or(t){return new Promise((r)=>{let i=nn.createServer();i.once("error",()=>r(!1)),i.once("listening",()=>{i.close(()=>r(!0))}),i.listen(t,"::")})}async function Ar(t){if(!await Pr(t))return!1;return await Or(t)}async function Ve(t,r=20){t=Number(t);for(let i=0;i<r;i++){let p=t+i;if(await Ar(p))return p}throw Error(`Could not find an available port between ${t} and ${t+r-1}`)}var Dr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Mr(){try{let t=await import("./chunk-zwkc8yge.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,r={}){let i={...Dr,...r},p=await Mr();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 a=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(a&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return a}catch(a){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,a),!1}}function mt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let a=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(a){let l=a[1];try{let f=`
507
+ </div>`}import tn from"net";async function Or(t){return new Promise((r)=>{let s=tn.createServer();s.once("error",()=>r(!1)),s.once("listening",()=>{s.close(()=>r(!0))}),s.listen(t,"0.0.0.0")})}async function Ar(t){return new Promise((r)=>{let s=tn.createServer();s.once("error",()=>r(!1)),s.once("listening",()=>{s.close(()=>r(!0))}),s.listen(t,"::")})}async function Dr(t){if(!await Or(t))return!1;return await Ar(t)}async function We(t,r=20){t=Number(t);for(let s=0;s<r;s++){let p=t+s;if(await Dr(p))return p}throw Error(`Could not find an available port between ${t} and ${t+r-1}`)}var Mr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function _r(){try{let t=await import("./chunk-zwkc8yge.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,r={}){let s={...Mr,...r},p=await _r();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 a=await p.openDevWindow(t,{title:s.title,width:s.width,height:s.height,darkMode:s.darkMode,hotReload:s.hotReload,titlebarHidden:s.titlebarHidden,nativeSidebar:s.nativeSidebar,sidebarWidth:s.sidebarWidth,sidebarConfig:s.sidebarConfig});if(a&&s.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return a}catch(a){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,a),!1}}function mt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let a=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(a){let l=a[1];try{let f=`
508
508
  ${l}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
- `,y=Function(f)();if(y)return y}catch(f){console.warn("Invalid sidebarConfig:",f)}}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 a=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(a)return Function(`return ${a[1]}`)()}catch(a){console.warn("Invalid native-sidebar script configuration:",a)}return}function jt(){console.log(`
511
- 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 Lr(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`),jt()}function Ir(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ke(t,r,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),jt();let p="";process.stdin.on("data",(a)=>{if(a==="\x03"){if(i?.onQuit)i.onQuit();r(),process.exit(0)}if(p+=a,p.endsWith("\r")||p.endsWith(`
512
- `)){let l=p.trim().toLowerCase();p="",jr(l,t,r,i)}})}function jr(t,r,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ir(r);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Lr(r);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 jt();break;default:break}}async function Bt(t,r={}){let i=r.port||3000,p=r.watch!==!1,a=et.resolve(t);if(!Ht.existsSync(a))return console.error(`${e.red}Error: File not found: ${e.bright}${a}${e.reset}`),!1;if(!a.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${a}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,f=async()=>{try{let{content:w,data:S}=await Te(a,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],j=[...new Set([...x,...T])].map((M)=>`<option value="${M}"${M===v?" selected":""}>${M}</option>`).join(`
510
+ `,y=Function(f)();if(y)return y}catch(f){console.warn("Invalid sidebarConfig:",f)}}return{sections:[]}}let s=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(s)try{return JSON.parse(s[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let a=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(a)return Function(`return ${a[1]}`)()}catch(a){console.warn("Invalid native-sidebar script configuration:",a)}return}function jt(){console.log(`
511
+ 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 Lr(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`),jt()}function Ir(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,r,s){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),jt();let p="";process.stdin.on("data",(a)=>{if(a==="\x03"){if(s?.onQuit)s.onQuit();r(),process.exit(0)}if(p+=a,p.endsWith("\r")||p.endsWith(`
512
+ `)){let l=p.trim().toLowerCase();p="",jr(l,t,r,s)}})}function jr(t,r,s,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ir(r);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Lr(r);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),s(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else jt();break;default:break}}async function Bt(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=et.resolve(t);if(!Ht.existsSync(a))return console.error(`${e.red}Error: File not found: ${e.bright}${a}${e.reset}`),!1;if(!a.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${a}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,f=async()=>{try{let{content:w,data:S}=await $e(a,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],j=[...new Set([...x,...T])].map((M)=>`<option value="${M}"${M===v?" selected":""}>${M}</option>`).join(`
513
513
  `);return l=`
514
514
  <!DOCTYPE html>
515
515
  <html lang="en">
@@ -672,12 +672,12 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
672
672
  </script>
673
673
  </body>
674
674
  </html>
675
- `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await f())return!1;let y=i;try{if(y=await Ve(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 m=Hr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{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(w){return new Response(`<pre>${w}
675
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await f())return!1;let y=s;try{if(y=await We(s),y!==s)console.log(`${e.yellow}Port ${s} 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 m=Hr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{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(w){return new Response(`<pre>${w}
676
676
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
677
  ${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(`
678
678
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
679
679
  ${e.yellow}Routes:${e.reset}`);let b=et.relative(process.cwd(),a);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${b}${e.reset}`),console.log(`
680
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(m.url.toString(),()=>{if(p)Ht.watch(et.dirname(a),{recursive:!0}).close();m.stop()}),r.native)await Ze(y,{title:et.basename(a,".md")});if(p){let w=et.dirname(a);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Ht.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 f()});process.on("SIGINT",()=>{S.close(),m.stop(),process.exit(0)})}return!0}function Br(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zr}=globalThis.Bun;import Le from"fs";import fe from"path";class rn{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 r=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:r,fetch(a,l){if(l.upgrade(a,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(a)=>{if(this.clients.add(a),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);a.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(a)=>{if(this.clients.delete(a),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(a,l)=>{let f=typeof l==="string"?l:l.toString();if(f==="ping")return;try{let u=JSON.parse(f);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${r}`);return r}catch(a){if(a?.code==="EADDRINUSE"){r++;continue}throw a}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 r=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(r),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,r){this.broadcast({type:"css-update",path:t,content:r,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 Fr(t,r={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:a=10}=r;return`
680
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(m.url.toString(),()=>{if(p)Ht.watch(et.dirname(a),{recursive:!0}).close();m.stop()}),r.native)await Ze(y,{title:et.basename(a,".md")});if(p){let w=et.dirname(a);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Ht.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 f()});process.on("SIGINT",()=>{S.close(),m.stop(),process.exit(0)})}return!0}function Br(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zr}=globalThis.Bun;import Le from"fs";import fe from"path";class rn{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 r=t??this.options.wsPort,s=20;for(let p=0;p<s;p++)try{if(this.server=Bun.serve({port:r,fetch(a,l){if(l.upgrade(a,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(a)=>{if(this.clients.add(a),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);a.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(a)=>{if(this.clients.delete(a),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(a,l)=>{let f=typeof l==="string"?l:l.toString();if(f==="ping")return;try{let u=JSON.parse(f);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${r}`);return r}catch(a){if(a?.code==="EADDRINUSE"){r++;continue}throw a}throw Error(`Could not find an available port after ${s} 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 r=JSON.stringify(t),s=0;for(let p of this.clients)try{if(p.readyState===1)p.send(r),s++}catch{this.clients.delete(p)}if(this.options.verbose&&s>0)console.log(`[HMR] Broadcast ${t.type} to ${s} 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,r){this.broadcast({type:"css-update",path:t,content:r,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 Fr(t,r={}){let{showOverlay:s=!0,reconnectInterval:p=1000,maxReconnectAttempts:a=10}=r;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
@@ -689,7 +689,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(m.u
689
689
  var overlay = null;
690
690
  var wasConnected = false; // Track if we ever connected successfully
691
691
 
692
- ${i?`
692
+ ${s?`
693
693
  // Create connection status overlay
694
694
  function createOverlay() {
695
695
  overlay = document.createElement('div');
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function Ne(t,r,i={}){let p=Fr(r,i),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function ht(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function yt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function bt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var tt=null;function Tt(t){if(!tt)tt=new rn(t);return tt}function st(){if(tt)tt.stop(),tt=null}import $t from"path";var nt={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,a=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 f=await Gr(i,p);if(l.push(...f),i.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await Jn(f,i);if(x){if(i.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await we(()=>Bun.file(f).text(),"",(x)=>{throw new dr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new dr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=re.time("script-extraction",()=>{let x=y,T=le(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],j="",M=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",H=E.match(/<script\b([^>]*)>/i),q=H?H[1]:"";if(/\bserver\b/i.test(q))j=_;else M.push(E)}let L=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:j,templateContent:L,allScripts:M}}),S={__filename:f,__dirname:$t.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await we(()=>g(m,S,f),void 0,(x)=>{let T=new oe(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),i.debug)throw T});let v=await re.timeAsync("directive-processing",async()=>await s(b,S,f,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-z97bwx8m.js"),T=x(w.join(`
879
+ `}function ze(t,r,s={}){let p=Fr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function ht(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function yt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function bt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function Tt(t){if(!tt)tt=new rn(t);return tt}function st(){if(tt)tt.stop(),tt=null}import $t from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${$t.relative($t.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Xr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=re.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],j="",M=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",H=E.match(/<script\b([^>]*)>/i),q=H?H[1]:"";if(/\bserver\b/i.test(q))j=_;else M.push(E)}let L=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:j,templateContent:L,allScripts:M}}),S={__filename:f,__dirname:$t.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await re.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-q1jcf6vm.js"),T=x(w.join(`
880
880
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
881
881
  `+v.slice(k);else v+=`
882
- ${T}`}if(v=await he(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await Yn(f,v,u,i),i.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new oe(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),hn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:i.debug||V()?`<!DOCTYPE html>
882
+ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qn(f,v,u,s),s.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new ie(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),bn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:s.debug||U()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -939,12 +939,12 @@ ${T}`}if(v=await he(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await Y
939
939
  <h1>Something went wrong</h1>
940
940
  <p>An internal error occurred. Please try again later.</p>
941
941
  </body>
942
- </html>`,loader:"html"}}})}};async function kr(t,r={}){let i=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||i+1,u=fe.resolve(t);if(!Le.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Bt(u,r);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 y=c(process.cwd(),"output");Le.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ae)=>({path:ae.path,external:!0}))}},H=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!H.success)return console.error(`${e.red}Build failed:${e.reset}`,H.logs),!1;let q=H.outputs.find((be)=>be.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(q.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=fe.dirname(u);await en(S);let C=i;try{if(C=await Ve(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(a){let _=r.hmrPort||C+1;l=Tt({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-a7kt1ts4.js"),H=await _();if(T=r.stxOptions?.serverApi??H.serverApi,H?.apiRouter)x=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){v=H.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:J}=await import("./chunk-p4r90vqf.js"),be=H.broadcasting;await q(be);let ae=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ae}/ws${e.reset}`);let Re=fe.join(process.cwd(),"channels.ts");if(Le.existsSync(Re))try{let Z=await J(Re);console.log(`${e.blue}Loaded ${e.bright}${Z} broadcast channel${Z!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(Z){console.warn(`${e.yellow}Failed to load channels.ts: ${Z.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:j}=await import("./chunk-bvzr9zqt.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let L=zr({port:C,async fetch(_){return xn(_,await(async()=>{let H=new URL(_.url);if([y,fe.dirname(u),fe.join(process.cwd(),"public")].some((Z)=>j(fe.join(Z,H.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let Z=await x.handleRequest(_);if(Z.status!==404)return Z}catch{}if(v[H.pathname])try{return await v[H.pathname](_)}catch(Z){return new Response(JSON.stringify({error:Z.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await M(_);if(q)return q;if(H.pathname==="/")return(async()=>{let z=await h(m||"");if(a)z=Ne(z,f);if(r.native)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(r.titlebarHidden)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let J=fe.join(y,H.pathname);if(Le.existsSync(J)&&Le.statSync(J).isFile()){let Z=Bun.file(J),z=fe.extname(J).toLowerCase(),I="text/plain";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Fe=await Z.text(),Ye=Ie.transformSync(Fe);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}let be=fe.dirname(u),ae=fe.join(be,H.pathname);if(Le.existsSync(ae)&&Le.statSync(ae).isFile()){let Z=Bun.file(ae),z=fe.extname(ae).toLowerCase(),I="text/plain";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Fe=await Z.text(),Ye=Ie.transformSync(Fe);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}let Re=fe.join(process.cwd(),"public",H.pathname);if(Le.existsSync(Re)&&Le.statSync(Re).isFile()){let Z=Bun.file(Re),z=fe.extname(Re).toLowerCase(),I="application/octet-stream";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Fe=await Z.text(),Ye=Ie.transformSync(Fe);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
942
+ </html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=fe.resolve(t);if(!Le.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Bt(u,r);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 y=c(process.cwd(),"output");Le.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ae)=>({path:ae.path,external:!0}))}},H=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!H.success)return console.error(`${e.red}Build failed:${e.reset}`,H.logs),!1;let q=H.outputs.find((be)=>be.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(q.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=fe.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=Tt({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-ds91e0fe.js"),H=await _();if(T=r.stxOptions?.serverApi??H.serverApi,H?.apiRouter)x=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){v=H.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:J}=await import("./chunk-54zkkxmb.js"),be=H.broadcasting;await q(be);let ae=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ae}/ws${e.reset}`);let Re=fe.join(process.cwd(),"channels.ts");if(Le.existsSync(Re))try{let Z=await J(Re);console.log(`${e.blue}Loaded ${e.bright}${Z} broadcast channel${Z!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(Z){console.warn(`${e.yellow}Failed to load channels.ts: ${Z.message}${e.reset}`)}}catch(q){console.warn(`${e.yellow}Broadcasting failed to start: ${q.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:j}=await import("./chunk-rnws0dh3.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let L=zr({port:C,async fetch(_){return kn(_,await(async()=>{let H=new URL(_.url);if([y,fe.dirname(u),fe.join(process.cwd(),"public")].some((Z)=>j(fe.join(Z,H.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let Z=await x.handleRequest(_);if(Z.status!==404)return Z}catch{}if(v[H.pathname])try{return await v[H.pathname](_)}catch(Z){return new Response(JSON.stringify({error:Z.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await M(_);if(q)return q;if(H.pathname==="/")return(async()=>{let z=await h(m||"");if(a)z=ze(z,f);if(r.native)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(r.titlebarHidden)if(z.includes("<head>"))z=z.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(z.includes("<html"))z=z.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 z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let J=fe.join(y,H.pathname);if(Le.existsSync(J)&&Le.statSync(J).isFile()){let Z=Bun.file(J),z=fe.extname(J).toLowerCase(),I="text/plain";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Be=await Z.text(),Je=Ie.transformSync(Be);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}let be=fe.dirname(u),ae=fe.join(be,H.pathname);if(Le.existsSync(ae)&&Le.statSync(ae).isFile()){let Z=Bun.file(ae),z=fe.extname(ae).toLowerCase(),I="text/plain";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Be=await Z.text(),Je=Ie.transformSync(Be);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}let Re=fe.join(process.cwd(),"public",H.pathname);if(Le.existsSync(Re)&&Le.statSync(Re).isFile()){let Z=Bun.file(Re),z=fe.extname(Re).toLowerCase(),I="application/octet-stream";if(z===".ts"||z===".tsx"){let Ie=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),Be=await Z.text(),Je=Ie.transformSync(Be);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(Z,{headers:{"Content-Type":I}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
943
943
  ${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
944
  ${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(`
945
945
  ${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
946
946
  ${e.yellow}Routes:${e.reset}`);let E=fe.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
947
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(L.url.toString(),()=>{if(p)Le.watch(fe.dirname(u),{recursive:!0}).close();L.stop()}),r.native){let _=await Bun.file(u).text(),H=mt(_);await Ze(C,{title:fe.basename(u,".stx"),titlebarHidden:r.titlebarHidden===!0,nativeSidebar:!!H,sidebarConfig:H})}if(p){let _=fe.dirname(u);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let H=Le.watch(_,{recursive:!0},async(q,J)=>{if(!J||bt(J))return;if(yt(J)){console.log(`${e.yellow}File ${e.bright}${J}${e.yellow} changed, rebuilding...${e.reset}`),qe.clear(),pe();let be=await b();if(await Wn(S),a&&l)if(be)l.reload(J);else l.error("Build failed - check console for details")}else if(ht(J)){if(console.log(`${e.cyan}CSS ${e.bright}${J}${e.cyan} changed${e.reset}`),a&&l)l.updateCss(J)}});process.on("SIGINT",()=>{if(H.close(),l)st();L.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Ce from"path";var on=`
947
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(L.url.toString(),()=>{if(p)Le.watch(fe.dirname(u),{recursive:!0}).close();L.stop()}),r.native){let _=await Bun.file(u).text(),H=mt(_);await Ze(C,{title:fe.basename(u,".stx"),titlebarHidden:r.titlebarHidden===!0,nativeSidebar:!!H,sidebarConfig:H})}if(p){let _=fe.dirname(u);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let H=Le.watch(_,{recursive:!0},async(q,J)=>{if(!J||bt(J))return;if(yt(J)){console.log(`${e.yellow}File ${e.bright}${J}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe();let be=await b();if(await Kn(S),a&&l)if(be)l.reload(J);else l.error("Build failed - check console for details")}else if(ht(J)){if(console.log(`${e.cyan}CSS ${e.bright}${J}${e.cyan} changed${e.reset}`),a&&l)l.updateCss(J)}});process.on("SIGINT",()=>{if(H.close(),l)st();L.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Ce from"path";var on=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,7 +1255,7 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function an(t){if(t.length===0)return"";if(t.length===1)return t[0];let r=t.map((p)=>p.split(Ce.sep)),i=[];for(let p=0;p<r[0].length;p++){let a=r[0][p];if(r.every((l)=>l[p]===a))i.push(a);else break}return i.join(Ce.sep)}async function _r(t,r={}){let i=r.port||3000,p=r.watch!==!1;for(let v of t){let x=Ce.resolve(v);if(!Xe.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 a=c(process.cwd(),"output");Xe.mkdirSync(a,{recursive:!0});let l=an(t.map((v)=>Ce.dirname(Ce.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let f={},u=[],y=async()=>{try{for(let v of t){let x=Ce.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:j}=await Te(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),M=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,L=M?.defaultTheme||"github-dark",E=["github-dark"],_=M?.additionalThemes||[],q=[...new Set([...E,..._])].map((Re)=>`<option value="${Re}"${Re===L?" selected":""}>${Re}</option>`).join(`
1258
+ `;function an(t){if(t.length===0)return"";if(t.length===1)return t[0];let r=t.map((p)=>p.split(Ce.sep)),s=[];for(let p=0;p<r[0].length;p++){let a=r[0][p];if(r.every((l)=>l[p]===a))s.push(a);else break}return s.join(Ce.sep)}async function Er(t,r={}){let s=r.port||3000,p=r.watch!==!1;for(let v of t){let x=Ce.resolve(v);if(!Xe.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 a=c(process.cwd(),"output");Xe.mkdirSync(a,{recursive:!0});let l=an(t.map((v)=>Ce.dirname(Ce.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let f={},u=[],y=async()=>{try{for(let v of t){let x=Ce.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:j}=await $e(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:R.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),M=r.markdown?.syntaxHighlighting||R.markdown?.syntaxHighlighting,L=M?.defaultTheme||"github-dark",E=["github-dark"],_=M?.additionalThemes||[],q=[...new Set([...E,..._])].map((Re)=>`<option value="${Re}"${Re===L?" selected":""}>${Re}</option>`).join(`
1259
1259
  `),J=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
@@ -1418,26 +1418,26 @@ else {
1418
1418
  </script>
1419
1419
  </body>
1420
1420
  </html>
1421
- `,ae=`/${Ce.relative(l,x).replace(/\.md$/,"")}`;if(ae.endsWith("/index"))ae=ae.slice(0,-6)||"/";f[ae||"/"]={filePath:x,content:J,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)\//},(_)=>({path:_.path,external:!0}))}},j;try{let E=await Bun.build({entrypoints:[x],outdir:a,plugins:[k,nt],define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Ee(E.logs,x));continue}let _=E.outputs.find((H)=>H.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}j=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
- ${Ee(E,x)}`);continue}let L=`/${Ce.relative(l,x).replace(/\.stx$/,"")}`;if(L.endsWith("/index"))L=L.slice(0,-6)||"/";if(L.includes("[")){let{regex:E,params:_}=Qr(L,{page:!0});u.push({pattern:E,paramNames:_,filePath:x,routeTemplate:L,fileType:"stx"}),f[L]={filePath:x,content:j,fileType:"stx"}}else f[L||"/"]={filePath:x,content:j,fileType:"stx"}}}if(Object.keys(f).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}`,Ee(v)),!1}};if(!await y())return!1;let b=i;try{if(b=await Ve(i),b!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${b} 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:${b}/${e.reset}...`);let w=Nr({port:b,async fetch(v){let x=new URL(v.url),T=Ce.join(process.cwd(),"public",x.pathname);if(Xe.existsSync(T)&&Xe.statSync(T).isFile()){let M=Bun.file(T),L=Ce.extname(T).toLowerCase(),E="application/octet-stream";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),H=await M.text(),q=_.transformSync(H);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(L){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(M,{headers:{"Content-Type":E}})}let k=f[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=f[`${x.pathname}/`];if(!k)for(let M of u){let L=x.pathname.match(M.pattern);if(L){let E=f[M.routeTemplate];if(E){let _={};for(let J=0;J<M.paramNames.length;J++)_[M.paramNames[J]]=decodeURIComponent(L[J+1]);let H=E.content,q=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(H.includes("</head>"))H=H.replace("</head>",`${q}
1421
+ `,ae=`/${Ce.relative(l,x).replace(/\.md$/,"")}`;if(ae.endsWith("/index"))ae=ae.slice(0,-6)||"/";f[ae||"/"]={filePath:x,content:J,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)\//},(_)=>({path:_.path,external:!0}))}},j;try{let E=await Bun.build({entrypoints:[x],outdir:a,plugins:[k,nt],define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Te(E.logs,x));continue}let _=E.outputs.find((H)=>H.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}j=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${Te(E,x)}`);continue}let L=`/${Ce.relative(l,x).replace(/\.stx$/,"")}`;if(L.endsWith("/index"))L=L.slice(0,-6)||"/";if(L.includes("[")){let{regex:E,params:_}=ts(L,{page:!0});u.push({pattern:E,paramNames:_,filePath:x,routeTemplate:L,fileType:"stx"}),f[L]={filePath:x,content:j,fileType:"stx"}}else f[L||"/"]={filePath:x,content:j,fileType:"stx"}}}if(Object.keys(f).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}`,Te(v)),!1}};if(!await y())return!1;let b=s;try{if(b=await We(s),b!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${b} 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:${b}/${e.reset}...`);let w=Nr({port:b,async fetch(v){let x=new URL(v.url),T=Ce.join(process.cwd(),"public",x.pathname);if(Xe.existsSync(T)&&Xe.statSync(T).isFile()){let M=Bun.file(T),L=Ce.extname(T).toLowerCase(),E="application/octet-stream";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),H=await M.text(),q=_.transformSync(H);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(L){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(M,{headers:{"Content-Type":E}})}let k=f[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=f[`${x.pathname}/`];if(!k)for(let M of u){let L=x.pathname.match(M.pattern);if(L){let E=f[M.routeTemplate];if(E){let _={};for(let J=0;J<M.paramNames.length;J++)_[M.paramNames[J]]=decodeURIComponent(L[J+1]);let H=E.content,q=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(H.includes("</head>"))H=H.replace("</head>",`${q}
1423
1423
  </head>`);else H=q+H;k={...E,content:H}}break}}if(k)return h(k.content).then((M)=>{if(M.includes("</head>"))M=M.replace("</head>",`${on}
1424
- </head>`);return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let j=Ce.join(a,x.pathname);if(Xe.existsSync(j)&&Xe.statSync(j).isFile()){let M=Bun.file(j),L=Ce.extname(j).toLowerCase(),E="text/plain";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),H=await M.text(),q=_.transformSync(H);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(L){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(M,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&f["/"]){let M=Se(v);return h(f["/"].content).then((L)=>{if(M){let E=L.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=L.match(/<title[^>]*>([\s\S]*?)<\/title>/i),H=_?_[1]:"",q=`<!DOCTYPE html><html><head><title>${sn(H)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(q,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...O(),"Cache-Control":ut,Pragma:"no-cache",Expires:"0"}})}}return new Response(L,{headers:{"Content-Type":"text/html",...O(),"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}
1424
+ </head>`);return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let j=Ce.join(a,x.pathname);if(Xe.existsSync(j)&&Xe.statSync(j).isFile()){let M=Bun.file(j),L=Ce.extname(j).toLowerCase(),E="text/plain";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),H=await M.text(),q=_.transformSync(H);return new Response(q,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(L){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(M,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&f["/"]){let M=ke(v);return h(f["/"].content).then((L)=>{if(M){let E=L.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=L.match(/<title[^>]*>([\s\S]*?)<\/title>/i),H=_?_[1]:"",q=`<!DOCTYPE html><html><head><title>${sn(H)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(q,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...O(),"Cache-Control":ut,Pragma:"no-cache",Expires:"0"}})}}return new Response(L,{headers:{"Content-Type":"text/html",...O(),"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}
1425
1425
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1426
1426
  ${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(`
1427
1427
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1428
1428
  ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ce.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ce.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 ",j=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${j}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.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}`),qe.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function sn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import de from"fs";import Q from"path";async function ln(t){try{return cn(await Bun.file(t).text())}catch{return}}function Ft(t){let r=Bun.file(t),i=Q.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(r,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function Cr(t=".",r={}){let i=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||i+1,u=Q.resolve(t),{loadStxConfig:y}=await import("./chunk-a7kt1ts4.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-bvzr9zqt.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?Q.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=Q.join(v,x);if(!de.existsSync(T)&&!m._layerPageDirs?.some((P)=>de.existsSync(P)))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=U(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._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 j=m?._pluginPageDirs||[],M=[];for(let{dir:P,prefix:B}of j)if(de.existsSync(P)){let F=U(Q.dirname(P),{pagesDir:Q.basename(P)});for(let N of F){let ue=B==="/"?N.pattern:`${B}${N.pattern==="/"?"":N.pattern}`;M.push({route:{...N,pattern:ue},prefix:B})}if(F.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${F.length}${e.blue} routes at ${e.cyan}${B}${e.reset}`)}let L=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ti(u,r.stxOptions?.shell),_){if(E=await Bs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${Q.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let H=xt();if(H.length>0)console.log(`${e.blue}Loaded ${e.bright}${H.length}${e.blue} middleware: ${e.dim}${H.join(", ")}${e.reset}`);let q={},J=null;try{let{loadStxConfig:P}=await import("./chunk-a7kt1ts4.js"),B=await P(u);if(B?.apiRouter)J=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){q=B.apiRoutes;let F=Object.keys(q).length;if(F>0)console.log(`${e.blue}Loaded ${e.bright}${F} API route${F>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:F,loadChannels:N}=await import("./chunk-p4r90vqf.js"),ue=B.broadcasting;await F(ue);let je=ue.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${je}/ws${e.reset}`);let Ue=Q.join(process.cwd(),"channels.ts");if(de.existsSync(Ue))try{let Y=await N(Ue);console.log(`${e.blue}Loaded ${e.bright}${Y} broadcast channel${Y!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(Y){console.warn(`${e.yellow}Failed to load channels.ts: ${Y.message}${e.reset}`)}}catch(F){console.warn(`${e.yellow}Broadcasting failed to start: ${F.message}${e.reset}`)}}catch{}let be=c(u,"output");de.mkdirSync(be,{recursive:!0});let ae=new Map,Re=new Set,Z=async(P)=>{let B=es(T,P);if(!B)return null;try{let F=await Bun.build({entrypoints:[B],outdir:be,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!F.success)return null;let N=F.outputs.find((ue)=>ue.path.endsWith(".html"));if(!N)return null;return await Bun.file(N.path).text()}catch{return null}},z=new Map,I=async(P,B)=>{try{let{processDirectives:F,extractVariables:N,defaultConfig:ue,loadStxConfig:je,injectRouterScript:Ue}=await import("./chunk-a7kt1ts4.js"),{checkCache:Y,cacheTemplate:G,readFileCached:W,templateCache:K}=await import("./chunk-34yj93hh.js"),ge=await je(u),We=(ee)=>{if(!ee)return ee;if(Q.isAbsolute(ee))return ee;return Q.resolve(u,ee)},A={...ue,...ge,...r.stxOptions,autoShell:!0};if(r.debugDirectives)A.debug=!0;A.partialsDir=We(A.partialsDir),A.componentsDir=We(A.componentsDir),A.layoutsDir=We(A.layoutsDir),A.storesDir=We(A.storesDir||"stores"),A.cachePath=We(A.cachePath)??c(u,"cache");let ce=!B&&!r.profile,te=A.cache!==!1;if(te&&ce){let ee=K.get(P.filePath);if(ee)try{if((await de.promises.stat(P.filePath)).mtime.getTime()<=ee.mtime){let _e=!0;for(let ve of ee.dependencies){if(!de.existsSync(ve)){_e=!1;break}if((await de.promises.stat(ve)).mtime.getTime()>ee.mtime){_e=!1;break}}if(_e){let ve=ee.output;if(E)ve=He(ve,{preserveHead:!0});let ot=z.get(P.filePath);return{route:P,content:ve,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let De=await Y(P.filePath,A);if(De){let Me=De;if(E)Me=He(Me,{preserveHead:!0});let _e=z.get(P.filePath);return{route:P,content:Me,status:_e?.status??await ln(P.filePath),headers:_e?.headers}}}let ie=te?await W(P.filePath):await Bun.file(P.filePath).text(),xe=cn(ie),{classifyAllScripts:X}=await import("./chunk-a7kt1ts4.js"),Ae=X(ie),Be=Ae.server.map((ee)=>ee.content),ne=ie;for(let ee of Ae.server)ne=ne.replace(ee.fullTag,"");let se={__filename:P.filePath,__dirname:Q.dirname(P.filePath),__stx_options:A,params:B??{},__stx_runtime_head:{}};for(let ee of Be)try{await N(ee,se,P.filePath)}catch(De){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,De?.message||De)}let ze=new Set,Pe;if(r.profile){let ee=performance.now();Pe=await F(ne,se,P.filePath,A,ze);let De=performance.now()-ee,Me=Q.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${Me} \u2192 ${De.toFixed(2)}ms`)}else Pe=await F(ne,se,P.filePath,A,ze);if(!E)Pe=await Ue(Pe,{router:A.router});{let{interpolateScriptExpressions:ee}=await import("./chunk-z97bwx8m.js");Pe=Pe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(De,Me,_e)=>{if(!/function\s+__stx_setup_/.test(_e))return De;return`<script${Me}>${ee(_e,se)}</script>`})}if(E)Pe=He(Pe,{preserveHead:!0});if(te&&ce)await G(P.filePath,Pe,ze,A);let{extractStreamBoundaries:Hn}=await import("./chunk-7kznee1g.js"),Qe=Hn(se),rt=se.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ee=se.streamBoundaries||{},De={...A,autoShell:!1},Me=Object.keys(rt).map((ve)=>({id:ve,render:async()=>{let ot=typeof ee[ve]==="function"?await ee[ve]():void 0;return F(rt[ve],{...se,$boundary:ot},P.filePath,De,new Set)}})),_e=new Set(Me.map((ve)=>ve.id));Qe=[...(Qe||[]).filter((ve)=>!_e.has(ve.id)),...Me]}if(Qe&&Qe.length>0)Re.add(P.pattern);else Qe=void 0;let Ut=Rt(se),Wt=At(se);if(ce)z.set(P.filePath,{status:Ut,headers:Wt});return{route:P,content:Pe,status:Ut??xe,headers:Wt,boundaries:Qe}}catch(F){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,F),null}},Ie=8,Fe=async()=>{ae.clear(),L.clear();for(let P=0;P<k.length;P+=Ie){let B=k.slice(P,P+Ie),F=await Promise.all(B.map((N)=>I(N)));for(let N of F)if(N)ae.set(N.route.pattern,N)}for(let P=0;P<M.length;P+=Ie){let B=M.slice(P,P+Ie),F=await Promise.all(B.map(({route:N})=>I(N)));for(let N of F)if(N)L.set(N.route.pattern,N)}return ae.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Fe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await en(u);let Ge=i;try{if(Ge=await Ve(i),Ge!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=Tt({wsPort:P,verbose:!1}),f=l.start(P)}let Pt=(P,B)=>{let N=`<script data-stx-route-params>(function(){var p=${JSON.stringify(B).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(P.includes("</head>"))return P.replace("</head>",`${N}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${N}`);return N+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Ur({port:Ge,async fetch(P){let B=new URL(P.url),F=m?.publicDir||"public",N=Q.join(u,F,B.pathname),ue=Q.join(u,B.pathname),je=Q.join(be,B.pathname);if([N,ue,je].some((A)=>w(A,u,S)))return new Response("Not Found",{status:404});let[Ue,Y,G]=await Promise.all([de.promises.stat(N).catch(()=>null),de.promises.stat(ue).catch(()=>null),de.promises.stat(je).catch(()=>null)]);if(Ue?.isFile()&&!w(N,u,S))return Ft(N);if(Y?.isFile()&&!w(ue,u,S))return Ft(ue);if(G?.isFile()&&!w(je,u,S))return Ft(je);if(B.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(B.pathname.slice(16));if(A)try{let ce=`<${A} />`,te={...buildConfig,autoShell:!1},ie=await processDirectives(ce,{},Q.join(u,"components",`${A}.stx`),te,new Set);return new Response(ie,{headers:{"Content-Type":"text/html"}})}catch(ce){return new Response(`<div class="stx-async-error">${ce.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(B.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-xn9jrjzh.js"),ce=await A(P,{publicDir:Q.join(u,F),cacheDir:c(u,"cache","img")});if(ce)return ce}if(J)try{let A=await J.handleRequest(P);if(A.status!==404)return A}catch{}if(q[B.pathname])try{return await q[B.pathname](P)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let W=await C(P);if(W)return W;let K=Qn(B.pathname,k);if(K){let A=ae.get(K.route.pattern),ce=Re.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||ce){let te=await I(K.route,K.params);if(te)A=te}if(A){let te=A.status??200,ie=A.headers??{},xe=(K.route.filePath?gt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(xe.validate){if(!await xe.validate({params:K.params})){let Be=await Z(404);if(Be){let ne=Be;if(ne=await h(ne,u),a)ne=Ne(ne,f);return new Response(ne,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(xe.middleware){let Ae=kt(B.pathname,K.params,xe,B.search),Be=_t(Ae,null,P,{isServer:!0}),ne=await Ct(xe.middleware,Be);if(ne.redirect){let se=ne.redirect.path,ze=ne.redirect.options.redirectCode||302,Pe=new Headers(ne.responseHeaders);return Pe.set("Location",se),new Response(null,{status:ze,headers:Pe})}if(ne.abort){let{statusCode:se,message:ze}=ne.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${se}</title></head><body><h1>Error ${se}</h1><p>${ze}</p></body></html>`,{status:se,headers:{"Content-Type":"text/html"}})}if(Object.keys(ne.state).length>0){let se=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ne.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${se}</head>`)}}let X=A.content;if(E&&$i(P)){let Ae=Je(X),Be=me(X),ne=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),se=ne?Ei(ne[1].trim()):"";if(Object.keys(K.params).length>0)X=Pt(X,K.params);X=await h(X,u);let ze=m?.router?.container||"main";return X=ke(X,ze),new Response(X,{status:te,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ae.layout,"X-STX-Layout-Group":Ae.group,"X-STX-Runtime":Be?"true":"false",...se&&{"X-STX-Title":encodeURIComponent(se)},[na]:Zs(),...O(),"Cache-Control":ut}})}if(E)X=Rr(E,X);if(Object.keys(K.params).length>0)X=Pt(X,K.params);if(X=await h(X,u),a)X=Ne(X,f);if(r.native)if(X.includes("<head>"))X=X.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 X="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+X;if(r.titlebarHidden)if(X.includes("<head>"))X=X.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 X=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${X}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Ae,streamToResponse:Be}=await import("./chunk-7kznee1g.js");return Be(Ae(X,A.boundaries,{timeoutMs:30000}),{status:te,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:te,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ie}})}}if(M.length>0){let A=M.map((te)=>te.route),ce=Qn(B.pathname,A);if(ce){let te=L.get(ce.route.pattern);if(te){let ie=te.content;if(E)ie=Rr(E,ie);if(Object.keys(ce.params).length>0)ie=Pt(ie,ce.params);if(ie=await h(ie,u),a)ie=Ne(ie,f);return new Response(ie,{status:te.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:te}of j)if(te!=="/"&&B.pathname.startsWith(te)){let ie=L.get(te)||L.get(te+"/");if(ie){let xe=ie.content;if(E)xe=Rr(E,xe);if(xe=await h(xe,u),a)xe=Ne(xe,f);return new Response(xe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(B.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ge=ae.get("/");if(ge){let A=ge.content;if(A=await h(A,u),a)A=Ne(A,f);if(r.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let We=await Z(404);if(We){let A=We;if(A=await h(A,u),a)A=Ne(A,f);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let B=await Z(500);if(B)return new Response(B,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.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}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function sn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ur}=globalThis.Bun;import le from"fs";import Q from"path";async function cn(t){try{return un(await Bun.file(t).text())}catch{return}}function Ft(t){let r=Bun.file(t),s=Q.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(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=Q.resolve(t),{loadStxConfig:y}=await import("./chunk-ds91e0fe.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-rnws0dh3.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?Q.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=Q.join(v,x);if(!le.existsSync(T)&&!m._layerPageDirs?.some((P)=>le.existsSync(P)))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=W(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._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 j=m?._pluginPageDirs||[],M=[];for(let{dir:P,prefix:B}of j)if(le.existsSync(P)){let F=W(Q.dirname(P),{pagesDir:Q.basename(P)});for(let N of F){let de=B==="/"?N.pattern:`${B}${N.pattern==="/"?"":N.pattern}`;M.push({route:{...N,pattern:de},prefix:B})}if(F.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${F.length}${e.blue} routes at ${e.cyan}${B}${e.reset}`)}let L=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await $i(u,r.stxOptions?.shell),_){if(E=await zs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${Q.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let H=xt();if(H.length>0)console.log(`${e.blue}Loaded ${e.bright}${H.length}${e.blue} middleware: ${e.dim}${H.join(", ")}${e.reset}`);let q={},J=null;try{let{loadStxConfig:P}=await import("./chunk-ds91e0fe.js"),B=await P(u);if(B?.apiRouter)J=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){q=B.apiRoutes;let F=Object.keys(q).length;if(F>0)console.log(`${e.blue}Loaded ${e.bright}${F} API route${F>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:F,loadChannels:N}=await import("./chunk-54zkkxmb.js"),de=B.broadcasting;await F(de);let je=de.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${je}/ws${e.reset}`);let Ne=Q.join(process.cwd(),"channels.ts");if(le.existsSync(Ne))try{let Y=await N(Ne);console.log(`${e.blue}Loaded ${e.bright}${Y} broadcast channel${Y!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(Y){console.warn(`${e.yellow}Failed to load channels.ts: ${Y.message}${e.reset}`)}}catch(F){console.warn(`${e.yellow}Broadcasting failed to start: ${F.message}${e.reset}`)}}catch{}let be=c(u,"output");le.mkdirSync(be,{recursive:!0});let ae=new Map,Re=new Set,Z=async(P)=>{let B=ns(T,P);if(!B)return null;try{let F=await Bun.build({entrypoints:[B],outdir:be,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!F.success)return null;let N=F.outputs.find((de)=>de.path.endsWith(".html"));if(!N)return null;return await Bun.file(N.path).text()}catch{return null}},z=new Map,I=async(P,B)=>{try{let{processDirectives:F,extractVariables:N,defaultConfig:de,loadStxConfig:je,injectRouterScript:Ne}=await import("./chunk-ds91e0fe.js"),{checkCache:Y,cacheTemplate:G,readFileCached:V,templateCache:K}=await import("./chunk-c4enpsj8.js"),me=await je(u),Ue=(ee)=>{if(!ee)return ee;if(Q.isAbsolute(ee))return ee;return Q.resolve(u,ee)},A={...de,...me,...r.stxOptions,autoShell:!0};if(r.debugDirectives)A.debug=!0;A.partialsDir=Ue(A.partialsDir),A.componentsDir=Ue(A.componentsDir),A.layoutsDir=Ue(A.layoutsDir),A.storesDir=Ue(A.storesDir||"stores"),A.cachePath=Ue(A.cachePath)??c(u,"cache");let ce=!B&&!r.profile,te=A.cache!==!1;if(te&&ce){let ee=K.get(P.filePath);if(ee)try{if((await le.promises.stat(P.filePath)).mtime.getTime()<=ee.mtime){let Me=!0;for(let we of ee.dependencies){if(!le.existsSync(we)){Me=!1;break}if((await le.promises.stat(we)).mtime.getTime()>ee.mtime){Me=!1;break}}if(Me){let we=ee.output;if(E)we=Ve(we,{preserveHead:!0});let ot=z.get(P.filePath);return{route:P,content:we,status:ot?.status??await cn(P.filePath),headers:ot?.headers}}}}catch{}let Ae=await Y(P.filePath,A);if(Ae){let De=Ae;if(E)De=Ve(De,{preserveHead:!0});let Me=z.get(P.filePath);return{route:P,content:De,status:Me?.status??await cn(P.filePath),headers:Me?.headers}}}let se=te?await V(P.filePath):await Bun.file(P.filePath).text(),ve=un(se),{classifyAllScripts:X}=await import("./chunk-ds91e0fe.js"),Oe=X(se),He=Oe.server.map((ee)=>ee.content),ne=se;for(let ee of Oe.server)ne=ne.replace(ee.fullTag,"");let oe={__filename:P.filePath,__dirname:Q.dirname(P.filePath),__stx_options:A,params:B??{},__stx_runtime_head:{}};for(let ee of He)try{await N(ee,oe,P.filePath)}catch(Ae){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ae?.message||Ae)}let Fe=new Set,Ee;if(r.profile){let ee=performance.now();Ee=await F(ne,oe,P.filePath,A,Fe);let Ae=performance.now()-ee,De=Q.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${De} \u2192 ${Ae.toFixed(2)}ms`)}else Ee=await F(ne,oe,P.filePath,A,Fe);if(!E)Ee=await Ne(Ee,{router:A.router});{let{interpolateScriptExpressions:ee}=await import("./chunk-q1jcf6vm.js");Ee=Ee.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ae,De,Me)=>{if(!/function\s+__stx_setup_/.test(Me))return Ae;return`<script${De}>${ee(Me,oe)}</script>`})}if(E)Ee=Ve(Ee,{preserveHead:!0});if(te&&ce)await G(P.filePath,Ee,Fe,A);let{extractStreamBoundaries:Hn}=await import("./chunk-vewt3464.js"),Qe=Hn(oe),rt=oe.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ee=oe.streamBoundaries||{},Ae={...A,autoShell:!1},De=Object.keys(rt).map((we)=>({id:we,render:async()=>{let ot=typeof ee[we]==="function"?await ee[we]():void 0;return F(rt[we],{...oe,$boundary:ot},P.filePath,Ae,new Set)}})),Me=new Set(De.map((we)=>we.id));Qe=[...(Qe||[]).filter((we)=>!Me.has(we.id)),...De]}if(Qe&&Qe.length>0)Re.add(P.pattern);else Qe=void 0;let Ut=At(oe),Wt=Pt(oe);if(ce)z.set(P.filePath,{status:Ut,headers:Wt});return{route:P,content:Ee,status:Ut??ve,headers:Wt,boundaries:Qe}}catch(F){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,F),null}},Ie=8,Be=async()=>{ae.clear(),L.clear();for(let P=0;P<k.length;P+=Ie){let B=k.slice(P,P+Ie),F=await Promise.all(B.map((N)=>I(N)));for(let N of F)if(N)ae.set(N.route.pattern,N)}for(let P=0;P<M.length;P+=Ie){let B=M.slice(P,P+Ie),F=await Promise.all(B.map(({route:N})=>I(N)));for(let N of F)if(N)L.set(N.route.pattern,N)}return ae.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Be())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=Tt({wsPort:P,verbose:!1}),f=l.start(P)}let Et=(P,B)=>{let N=`<script data-stx-route-params>(function(){var p=${JSON.stringify(B).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(P.includes("</head>"))return P.replace("</head>",`${N}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${N}`);return N+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Ur({port:Ge,async fetch(P){let B=new URL(P.url),F=m?.publicDir||"public",N=Q.join(u,F,B.pathname),de=Q.join(u,B.pathname),je=Q.join(be,B.pathname);if([N,de,je].some((A)=>w(A,u,S)))return new Response("Not Found",{status:404});let[Ne,Y,G]=await Promise.all([le.promises.stat(N).catch(()=>null),le.promises.stat(de).catch(()=>null),le.promises.stat(je).catch(()=>null)]);if(Ne?.isFile()&&!w(N,u,S))return Ft(N);if(Y?.isFile()&&!w(de,u,S))return Ft(de);if(G?.isFile()&&!w(je,u,S))return Ft(je);if(B.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(B.pathname.slice(16));if(A)try{let ce=`<${A} />`,te={...buildConfig,autoShell:!1},se=await processDirectives(ce,{},Q.join(u,"components",`${A}.stx`),te,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(ce){return new Response(`<div class="stx-async-error">${ce.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(B.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-kqbpkg8n.js"),ce=await A(P,{publicDir:Q.join(u,F),cacheDir:c(u,"cache","img")});if(ce)return ce}if(J)try{let A=await J.handleRequest(P);if(A.status!==404)return A}catch{}if(q[B.pathname])try{return await q[B.pathname](P)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await C(P);if(V)return V;let K=tr(B.pathname,k);if(K){let A=ae.get(K.route.pattern),ce=Re.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||ce){let te=await I(K.route,K.params);if(te)A=te}if(A){let te=A.status??200,se=A.headers??{},ve=(K.route.filePath?gt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ve.validate){if(!await ve.validate({params:K.params})){let He=await Z(404);if(He){let ne=He;if(ne=await h(ne,u),a)ne=ze(ne,f);return new Response(ne,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ve.middleware){let Oe=kt(B.pathname,K.params,ve,B.search),He=_t(Oe,null,P,{isServer:!0}),ne=await Ct(ve.middleware,He);if(ne.redirect){let oe=ne.redirect.path,Fe=ne.redirect.options.redirectCode||302,Ee=new Headers(ne.responseHeaders);return Ee.set("Location",oe),new Response(null,{status:Fe,headers:Ee})}if(ne.abort){let{statusCode:oe,message:Fe}=ne.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${oe}</title></head><body><h1>Error ${oe}</h1><p>${Fe}</p></body></html>`,{status:oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ne.state).length>0){let oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ne.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${oe}</head>`)}}let X=A.content;if(E&&Ri(P)){let Oe=Ye(X),He=he(X),ne=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),oe=ne?Ti(ne[1].trim()):"";if(Object.keys(K.params).length>0)X=Et(X,K.params);X=await h(X,u);let Fe=m?.router?.container||"main";return X=_e(X,Fe),new Response(X,{status:te,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Oe.layout,"X-STX-Layout-Group":Oe.group,"X-STX-Runtime":He?"true":"false",...oe&&{"X-STX-Title":encodeURIComponent(oe)},[ra]:eo(),...O(),"Cache-Control":ut}})}if(E)X=Pr(E,X);if(Object.keys(K.params).length>0)X=Et(X,K.params);if(X=await h(X,u),a)X=ze(X,f);if(r.native)if(X.includes("<head>"))X=X.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 X="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+X;if(r.titlebarHidden)if(X.includes("<head>"))X=X.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 X=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${X}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Oe,streamToResponse:He}=await import("./chunk-vewt3464.js");return He(Oe(X,A.boundaries,{timeoutMs:30000}),{status:te,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:te,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(M.length>0){let A=M.map((te)=>te.route),ce=tr(B.pathname,A);if(ce){let te=L.get(ce.route.pattern);if(te){let se=te.content;if(E)se=Pr(E,se);if(Object.keys(ce.params).length>0)se=Et(se,ce.params);if(se=await h(se,u),a)se=ze(se,f);return new Response(se,{status:te.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:te}of j)if(te!=="/"&&B.pathname.startsWith(te)){let se=L.get(te)||L.get(te+"/");if(se){let ve=se.content;if(E)ve=Pr(E,ve);if(ve=await h(ve,u),a)ve=ze(ve,f);return new Response(ve,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(B.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let me=ae.get("/");if(me){let A=me.content;if(A=await h(A,u),a)A=ze(A,f);if(r.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ue=await Z(404);if(Ue){let A=Ue;if(A=await h(A,u),a)A=ze(A,f);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let B=await Z(500);if(B)return new Response(B,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1430
1430
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1431
1431
  ${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(`
1432
1432
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
1433
- ${e.yellow}Routes:${e.reset}`);let Dt=[...ts(k,u)];for(let{route:P}of M)Dt.push(`${P.pattern}`);if(Dt.forEach((P,B)=>{let N=B===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${N}${e.reset}${P}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Ot.url.toString(),()=>{if(l)st();Ot.stop()}),r.native){let P,B=Q.join(T,"index.stx");if(de.existsSync(B)){let N=await Bun.file(B).text();P=mt(N)}let F=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||Q.basename(u)||"stx App",width:F.width,height:F.height,darkMode:F.darkMode,hotReload:F.hotReload,titlebarHidden:F.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(Y)=>Y.startsWith("public/")||Y.startsWith("public\\"),B=(Y)=>{let G=Y.toLowerCase();return G.endsWith(".stx")||G.endsWith(".html")||G.endsWith(".md")},F=new Map,N=()=>{let Y=new Set([u,...m._layerGraph?.layers.map((G)=>G.root)??[],...m._layerGraph?.configDependencies.map((G)=>Q.dirname(G))??[]].filter((G)=>de.existsSync(G)).map((G)=>de.realpathSync(G)));for(let G of m._layerGraph?.layers??[])for(let W of Object.values(G.resources)){if(!de.existsSync(W))continue;let K=de.realpathSync(W);if(![...Y].some((ge)=>K===ge||K.startsWith(`${ge}${Q.sep}`)))Y.add(K)}for(let[G,W]of F)if(!Y.has(G))W.close(),F.delete(G);for(let G of Y)if(!F.has(G)&&de.existsSync(G))F.set(G,de.watch(G,{recursive:!0},(W,K)=>{je(G,W,K).catch((ge)=>console.error("[stx] Layer rebuild failed:",ge))}))},ue=Promise.resolve(),je=(Y,G,W)=>(ue=ue.catch(()=>{}).then(()=>Ue(Y,G,W)),ue),Ue=async(Y,G,W)=>{if(!W||bt(W))return;if(yt(W)){if(m._layerGraph){let K=await y(u);Object.assign(m,K),k.splice(0,k.length,...U(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[T,...K._layerPageDirs.slice(1)]:void 0})),N()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),a&&l)l.reload(W)}else if(B(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),qe.clear(),pe();try{let{invalidateFileCache:K,templateCache:ge}=await import("./chunk-34yj93hh.js");K(Q.resolve(Y,W)),ge.delete(Q.resolve(Y,W))}catch{}if(_&&W){if(Q.resolve(Y,W)===_||Q.basename(_)===W){let ge=await Bs(_,r.stxOptions||{});if(ge)E=ge}}if(await Fe(),await Wn(u),a&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),qe.clear(),pe();try{let{invalidateFileCache:K,templateCache:ge}=await import("./chunk-34yj93hh.js");K(Q.resolve(Y,W)),ge.delete(Q.resolve(Y,W))}catch{}if(await Fe(),a&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),a&&l)l.updateCss(W)}};N(),process.on("SIGINT",()=>{for(let Y of F.values())Y.close();if(l)st();Ot.stop(),process.exit(0)})}return!0}import zt from"fs";import it from"path";async function Wr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let p=i[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
1435
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function Vr(t){try{let r=await Bun.file(t).text(),i=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
1436
- `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,r=!1,i){let p=it.basename(t,".stx"),a=await Wr(t),l=await Vr(t),f="";if(r&&i)f=`<${i}></${i}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1433
+ ${e.yellow}Routes:${e.reset}`);let Dt=[...rs(k,u)];for(let{route:P}of M)Dt.push(`${P.pattern}`);if(Dt.forEach((P,B)=>{let N=B===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${N}${e.reset}${P}`)}),console.log(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Ot.url.toString(),()=>{if(l)st();Ot.stop()}),r.native){let P,B=Q.join(T,"index.stx");if(le.existsSync(B)){let N=await Bun.file(B).text();P=mt(N)}let F=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||Q.basename(u)||"stx App",width:F.width,height:F.height,darkMode:F.darkMode,hotReload:F.hotReload,titlebarHidden:F.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(Y)=>Y.startsWith("public/")||Y.startsWith("public\\"),B=(Y)=>{let G=Y.toLowerCase();return G.endsWith(".stx")||G.endsWith(".html")||G.endsWith(".md")},F=new Map,N=()=>{let Y=new Set([u,...m._layerGraph?.layers.map((G)=>G.root)??[],...m._layerGraph?.configDependencies.map((G)=>Q.dirname(G))??[]].filter((G)=>le.existsSync(G)).map((G)=>le.realpathSync(G)));for(let G of m._layerGraph?.layers??[])for(let V of Object.values(G.resources)){if(!le.existsSync(V))continue;let K=le.realpathSync(V);if(![...Y].some((me)=>K===me||K.startsWith(`${me}${Q.sep}`)))Y.add(K)}for(let[G,V]of F)if(!Y.has(G))V.close(),F.delete(G);for(let G of Y)if(!F.has(G)&&le.existsSync(G))F.set(G,le.watch(G,{recursive:!0},(V,K)=>{je(G,V,K).catch((me)=>console.error("[stx] Layer rebuild failed:",me))}))},de=Promise.resolve(),je=(Y,G,V)=>(de=de.catch(()=>{}).then(()=>Ne(Y,G,V)),de),Ne=async(Y,G,V)=>{if(!V||bt(V))return;if(yt(V)){if(m._layerGraph){let K=await y(u);Object.assign(m,K),k.splice(0,k.length,...W(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[T,...K._layerPageDirs.slice(1)]:void 0})),N()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(B(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:K,templateCache:me}=await import("./chunk-c4enpsj8.js");K(Q.resolve(Y,V)),me.delete(Q.resolve(Y,V))}catch{}if(_&&V){if(Q.resolve(Y,V)===_||Q.basename(_)===V){let me=await zs(_,r.stxOptions||{});if(me)E=me}}if(await Be(),await Kn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:K,templateCache:me}=await import("./chunk-c4enpsj8.js");K(Q.resolve(Y,V)),me.delete(Q.resolve(Y,V))}catch{}if(await Be(),a&&l)l.reload(V)}}else if(ht(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};N(),process.on("SIGINT",()=>{for(let Y of F.values())Y.close();if(l)st();Ot.stop(),process.exit(0)})}return!0}import zt from"fs";import it from"path";async function Wr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
1435
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function Vr(t){try{let r=await Bun.file(t).text(),s=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
1436
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,r=!1,s){let p=it.basename(t,".stx"),a=await Wr(t),l=await Vr(t),f="";if(r&&s)f=`<${s}></${s}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
1437
  `);f=`<${p}
1438
1438
  ${u}
1439
- />`}return{name:p,path:t,description:l,props:a,example:f,isWebComponent:r,tag:i}}async function dn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let r=await zt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of r){let a=it.join(t,p.name);if(p.isDirectory()){let l=await dn(a);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(a)}return i}catch(r){return console.error(`Error finding component files in ${t}:`,r),[]}}async function Kr(t,r){try{if(!await n(t))return[];let i=await dn(t),p=[],a=new Map;if(r?.components?.length)for(let l of r.components)a.set(l.file,l);for(let l of i){let f=a.get(l),u=!!f,y=f?.tag,m=await qr(l,u,y);p.push(m)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function Xr(t){try{if(!await n(t))return[];let r=await zt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of r){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let a=it.join(t,p.name),l=await Bun.file(a).text(),f=it.basename(a,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
1440
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",m=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=m.exec(l))!==null)w.add(S[1]);while((S=b.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:f,path:a,description:y,components:[...w],directives:[...v]})}return i}catch(r){return console.error("Error generating template docs:",r),[]}}async function Jr(t=[]){try{let r=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1439
+ />`}return{name:p,path:t,description:l,props:a,example:f,isWebComponent:r,tag:s}}async function ln(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let r=await zt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of r){let a=it.join(t,p.name);if(p.isDirectory()){let l=await ln(a);s.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))s.push(a)}return s}catch(r){return console.error(`Error finding component files in ${t}:`,r),[]}}async function Kr(t,r){try{if(!await n(t))return[];let s=await ln(t),p=[],a=new Map;if(r?.components?.length)for(let l of r.components)a.set(l.file,l);for(let l of s){let f=a.get(l),u=!!f,y=f?.tag,m=await qr(l,u,y);p.push(m)}return p}catch(s){return console.error("Error generating component docs:",s),[]}}async function Gr(t){try{if(!await n(t))return[];let r=await zt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of r){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let a=it.join(t,p.name),l=await Bun.file(a).text(),f=it.basename(a,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
1440
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",m=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=m.exec(l))!==null)w.add(S[1]);while((S=b.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]);s.push({name:f,path:a,description:y,components:[...w],directives:[...v]})}return s}catch(r){return console.error("Error generating template docs:",r),[]}}async function Jr(t=[]){try{let r=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1441
1441
  <p>Welcome, {{ user.name }}!</p>
1442
1442
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1443
1443
  <p>Welcome back!</p>
@@ -1457,7 +1457,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Ot.
1457
1457
  <p>Page {{ page }}</p>
1458
1458
  @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
1459
1459
  {{ This will be displayed as-is }}
1460
- @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)r.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return r}catch(r){return console.error("Error generating directive docs:",r),[]}}function Yr(t=[],r=[],i=[],p){let a=`# stx Documentation
1460
+ @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 s of t)r.push({name:s.name,description:s.description||"",hasEndTag:s.hasEndTag||!1,example:""});return r}catch(r){return console.error("Error generating directive docs:",r),[]}}function Yr(t=[],r=[],s=[],p){let a=`# stx Documentation
1461
1461
 
1462
1462
  `;if(p)a+=`${p}
1463
1463
 
@@ -1487,19 +1487,19 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Ot.
1487
1487
 
1488
1488
  `;if(l.directives&&l.directives.length>0)a+=`**Directives Used:** ${l.directives.join(", ")}
1489
1489
 
1490
- `}}if(i.length>0){a+=`## Directives
1490
+ `}}if(s.length>0){a+=`## Directives
1491
1491
 
1492
1492
  `,a+=`| Directive | Description | Has End Tag |
1493
1493
  `,a+=`| --------- | ----------- | ----------- |
1494
- `;for(let l of i)a+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1494
+ `;for(let l of s)a+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
1495
  `;a+=`
1496
- `;for(let l of i)if(l.example)a+=`### @${l.name}
1496
+ `;for(let l of s)if(l.example)a+=`### @${l.name}
1497
1497
 
1498
1498
  `,a+=`${l.description||""}
1499
1499
 
1500
1500
  `,a+=`#### Example
1501
1501
 
1502
- `,a+="```html\n",a+=l.example,a+="\n```\n\n"}return a}function Zr(t=[],r=[],i=[],p){let a=`<!DOCTYPE html>
1502
+ `,a+="```html\n",a+=l.example,a+="\n```\n\n"}return a}function Qr(t=[],r=[],s=[],p){let a=`<!DOCTYPE html>
1503
1503
  <html lang="en">
1504
1504
  <head>
1505
1505
  <meta charset="UTF-8">
@@ -1558,7 +1558,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Ot.
1558
1558
  <td>${f.required?"Yes":"No"}</td>
1559
1559
  <td>${f.default||"-"}</td>
1560
1560
  <td>${f.description||"-"}</td>
1561
- </tr>`;a+="</tbody></table>"}if(l.example)a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(r.length>0){a+="<h2>Templates</h2>";for(let l of r){if(a+=`<h3>${l.name}</h3>`,l.description)a+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)a+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)a+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(i.length>0){a+="<h2>Directives</h2>",a+=`<table>
1561
+ </tr>`;a+="</tbody></table>"}if(l.example)a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(r.length>0){a+="<h2>Templates</h2>";for(let l of r){if(a+=`<h3>${l.name}</h3>`,l.description)a+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)a+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)a+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(s.length>0){a+="<h2>Directives</h2>",a+=`<table>
1562
1562
  <thead>
1563
1563
  <tr>
1564
1564
  <th>Directive</th>
@@ -1566,27 +1566,27 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Ot.
1566
1566
  <th>Has End Tag</th>
1567
1567
  </tr>
1568
1568
  </thead>
1569
- <tbody>`;for(let l of i)a+=`<tr>
1569
+ <tbody>`;for(let l of s)a+=`<tr>
1570
1570
  <td>@${l.name}</td>
1571
1571
  <td>${l.description||"-"}</td>
1572
1572
  <td>${l.hasEndTag?"Yes":"No"}</td>
1573
- </tr>`;a+="</tbody></table>";for(let l of i)if(l.example)a+=`<h3>@${l.name}</h3>`,a+=`<p>${l.description||""}</p>`,a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return a+="</body></html>",a}function eo(t=[],r=[],i=[],p){return JSON.stringify({components:t,templates:r,directives:i,extraContent:p||""},null,2)}async function to(t){try{let{componentsDir:r,templatesDir:i,webComponentsConfig:p,customDirectives:a,config:l}=t;if(!l.enabled)return!1;let f=l.outputDir||"docs";if(await zt.promises.mkdir(f,{recursive:!0}),console.log("Generating documentation..."),r)console.log(`Components directory: ${r}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${f}`);let u=[];if(l.components!==!1&&r)console.log("Generating component documentation..."),u=await Kr(r,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),y=await Xr(i),console.log(`Found ${y.length} templates`);let m=[];if(l.directives!==!1)console.log("Generating directive documentation..."),m=await Jr(a),console.log(`Found ${m.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",C="";switch(b){case"markdown":S=Yr(u,y,m,w),C="md";break;case"html":S=Zr(u,y,m,w),C="html";break;case"json":S=eo(u,y,m,w),C="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=it.join(f,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(r){return console.error("Error generating documentation:",r),!1}}async function mi(t){let r={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||R.componentsDir,p=t.templatesDir||".";return to({componentsDir:i,templatesDir:p,webComponentsConfig:R.webComponents,customDirectives:R.customDirectives,config:r})}var un={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Ps(t,r={}){let i={...un,...r};if(t.trim()==="")return`
1574
- `;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=oo(p,i),p=co(p,i),p=so(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1573
+ </tr>`;a+="</tbody></table>";for(let l of s)if(l.example)a+=`<h3>@${l.name}</h3>`,a+=`<p>${l.description||""}</p>`,a+="<h4>Example</h4>",a+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return a+="</body></html>",a}function Zr(t=[],r=[],s=[],p){return JSON.stringify({components:t,templates:r,directives:s,extraContent:p||""},null,2)}async function to(t){try{let{componentsDir:r,templatesDir:s,webComponentsConfig:p,customDirectives:a,config:l}=t;if(!l.enabled)return!1;let f=l.outputDir||"docs";if(await zt.promises.mkdir(f,{recursive:!0}),console.log("Generating documentation..."),r)console.log(`Components directory: ${r}`);if(s)console.log(`Templates directory: ${s}`);console.log(`Output directory: ${f}`);let u=[];if(l.components!==!1&&r)console.log("Generating component documentation..."),u=await Kr(r,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&s)console.log("Generating template documentation..."),y=await Gr(s),console.log(`Found ${y.length} templates`);let m=[];if(l.directives!==!1)console.log("Generating directive documentation..."),m=await Jr(a),console.log(`Found ${m.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",C="";switch(b){case"markdown":S=Yr(u,y,m,w),C="md";break;case"html":S=Qr(u,y,m,w),C="html";break;case"json":S=Zr(u,y,m,w),C="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=it.join(f,`stx-docs.${C}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(r){return console.error("Error generating documentation:",r),!1}}async function yi(t){let r={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},s=t.componentsDir||R.componentsDir,p=t.templatesDir||".";return to({componentsDir:s,templatesDir:p,webComponentsConfig:R.webComponents,customDirectives:R.customDirectives,config:r})}var pn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Os(t,r={}){let s={...pn,...r};if(t.trim()==="")return`
1574
+ `;let p=t;if(s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=oo(p,s),p=co(p,s),p=so(p,s),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1575
1575
  `).replace(/\r/g,`
1576
1576
  `),!p.endsWith(`
1577
1577
  `))p+=`
1578
- `;return p}function hi(t,r={}){let i={...un,...r};if(t.trim()==="")return`
1578
+ `;return p}function bi(t,r={}){let s={...pn,...r};if(t.trim()==="")return`
1579
1579
  `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(a,l,f,u,y)=>{let m=u.split(`
1580
1580
  `),b=m.filter((x)=>x.trim().length>0);if(b.length===0)return a;let w=Math.min(...b.map((x)=>{let T=x.match(/^( *)/);return T?T[1].length:0})),S=m.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
- `),v=Ps(S,i).trimEnd().split(`
1581
+ `),v=Os(S,s).trimEnd().split(`
1582
1582
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
1583
  `);return`${l}\`\`\`${f}
1584
1584
  ${v}
1585
- ${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1585
+ ${l}\`\`\``}),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!p.endsWith(`
1588
1588
  `))p+=`
1589
- `;return p}function ro(t){let r=t,i=[],p="__PROTECTED_BLOCK_";return r=r.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(a)=>{let l=i.length;return i.push(a),`${p}${l}__`}),r=r.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1589
+ `;return p}function ro(t){let r=t,s=[],p="__PROTECTED_BLOCK_";return r=r.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(a)=>{let l=s.length;return s.push(a),`${p}${l}__`}),r=r.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1590
1590
  $1
1591
1591
  `),r=r.replace(/(@end\w+)/g,`
1592
1592
  $1
@@ -1597,13 +1597,13 @@ $1
1597
1597
  `),r=r.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(a,l,f,u)=>{let y=u.substring(f+a.length,Math.min(u.length,f+a.length+20)),m=a.match(/<(\w+)/)?.[1];if(m&&y.match(new RegExp(`^</${m}>`)))return a;return`
1598
1598
  ${a}`}),r=r.replace(/(>)(<\/)/g,(a,l,f,u,y)=>{let m=y.substring(Math.max(0,u-50),u),w=y.substring(u+a.length,Math.min(y.length,u+a.length+20)).match(/^(\w+)>/)?.[1],S=m.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return a;return`${l}
1599
1599
  ${f}`}),r=r.replace(/(<\/[^>]+>)(?=<|$)/g,(a,l,f,u)=>{let y=u.substring(Math.max(0,f-20),f),m=a.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${m}[^>]*>$`);if(m&&y.match(b))return a;return`${a}
1600
- `}),r=r.replace(new RegExp(`${p}(\\d+)__`,"g"),(a,l)=>i[Number.parseInt(l,10)]),r=r.replace(/\n{2,}/g,`
1600
+ `}),r=r.replace(new RegExp(`${p}(\\d+)__`,"g"),(a,l)=>s[Number.parseInt(l,10)]),r=r.replace(/\n{2,}/g,`
1601
1601
  `),r=r.split(`
1602
1602
  `).map((a)=>a.trim()).join(`
1603
1603
  `),r=r.replace(/^\n+/,"").replace(/\n+$/,""),r}function oo(t,r){let p=ro(t).split(`
1604
- `),a=[],l=0,f=!1,u=r.useTabs?"\t":" ".repeat(r.indentSize);for(let y=0;y<p.length;y++){let m=p[y],b=m.trim();if(b===""){a.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(f&&!S){a.push(m);continue}let C=b===">";if(pn(b)&&!b.startsWith("<")&&!b.startsWith("@")){a.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),T=b.startsWith("@")&&ao(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),j=b.startsWith("<!--"),M=b.startsWith("</"),L=b.startsWith("<")&&!M&&!j&&!k,E=b.includes("/>")||io(b),_=pn(b);if(M||v)l=Math.max(0,l-1);let H=x?Math.max(0,l-1):l;if(C)a.push(m);else a.push(u.repeat(H)+b);if(L&&!E&&!_&&!C||T)l++;if(w)f=!0;if(S)f=!1}return a.join(`
1605
- `)}function so(t,r){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,a)=>{let l=a.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,a)=>{if(a.trim()==="")return`@${p}`;return`@${p}(${a.trim()})`}),r.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function io(t){let r=["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 r.includes(p.toLowerCase())}return!1}function pn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ao(t){let r=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of r)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function co(t,r){if(!r.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,a)=>{if(!a.trim())return i;if(a.includes("<")||a.includes(`
1606
- `)||a.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,f=[],u;while((u=l.exec(a))!==null)f.push({name:u[1],value:u[2]});f.sort((m,b)=>{if(m.name==="id")return-1;if(b.name==="id")return 1;if(m.name==="class")return-1;if(b.name==="class")return 1;return m.name.localeCompare(b.name)});let y=f.map((m)=>m.value?`${m.name}=${m.value}`:m.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import fn from"fs";import Nt from"path";async function yi(t="index.stx",r={}){try{let i=r.force||!1,p=Nt.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 a=Nt.dirname(p);if(!fn.existsSync(a))fn.mkdirSync(a,{recursive:!0});let l;if(r.template){let f=Nt.resolve(process.cwd(),r.template);if(!await Bun.file(f).exists())throw Error(`Template file ${r.template} does not exist.`);if(!f.endsWith(".stx"))console.warn(`Warning: Template file ${r.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(f).text(),console.warn(`Using template from ${r.template}`)}else if(r.preset)l=mn(r.preset),console.warn(`Using '${r.preset}' preset template`);else l=mn("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 mn(t){switch(t){case"basic":return gn();case"component":return lo();case"layout":return po();case"blog":return uo();case"api":return fo();case"app":return mo();default:return gn()}}function gn(){return`<script>
1604
+ `),a=[],l=0,f=!1,u=r.useTabs?"\t":" ".repeat(r.indentSize);for(let y=0;y<p.length;y++){let m=p[y],b=m.trim();if(b===""){a.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(f&&!S){a.push(m);continue}let C=b===">";if(dn(b)&&!b.startsWith("<")&&!b.startsWith("@")){a.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),T=b.startsWith("@")&&ao(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),j=b.startsWith("<!--"),M=b.startsWith("</"),L=b.startsWith("<")&&!M&&!j&&!k,E=b.includes("/>")||io(b),_=dn(b);if(M||v)l=Math.max(0,l-1);let H=x?Math.max(0,l-1):l;if(C)a.push(m);else a.push(u.repeat(H)+b);if(L&&!E&&!_&&!C||T)l++;if(w)f=!0;if(S)f=!1}return a.join(`
1605
+ `)}function so(t,r){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(s,p,a)=>{let l=a.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(s,p,a)=>{if(a.trim()==="")return`@${p}`;return`@${p}(${a.trim()})`}),r.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(s,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(s,p)=>`{!! ${p.trim()} !!}`);return t}function io(t){let r=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let s=t.match(/<(\w+)/);if(s){let p=s[1];return r.includes(p.toLowerCase())}return!1}function dn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ao(t){let r=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let s of r)if(t.startsWith(`@${s}`))return!t.includes(`@end${s}`);return!1}function co(t,r){if(!r.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(s,p,a)=>{if(!a.trim())return s;if(a.includes("<")||a.includes(`
1606
+ `)||a.includes("@"))return s;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,f=[],u;while((u=l.exec(a))!==null)f.push({name:u[1],value:u[2]});f.sort((m,b)=>{if(m.name==="id")return-1;if(b.name==="id")return 1;if(m.name==="class")return-1;if(b.name==="class")return 1;return m.name.localeCompare(b.name)});let y=f.map((m)=>m.value?`${m.name}=${m.value}`:m.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import fn from"fs";import Nt from"path";async function vi(t="index.stx",r={}){try{let s=r.force||!1,p=Nt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!s)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let a=Nt.dirname(p);if(!fn.existsSync(a))fn.mkdirSync(a,{recursive:!0});let l;if(r.template){let f=Nt.resolve(process.cwd(),r.template);if(!await Bun.file(f).exists())throw Error(`Template file ${r.template} does not exist.`);if(!f.endsWith(".stx"))console.warn(`Warning: Template file ${r.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(f).text(),console.warn(`Using template from ${r.template}`)}else if(r.preset)l=mn(r.preset),console.warn(`Using '${r.preset}' preset template`);else l=mn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(s){return console.error(`Error creating file: ${s instanceof Error?s.message:String(s)}`),!1}}function mn(t){switch(t){case"basic":return gn();case"component":return lo();case"layout":return po();case"blog":return uo();case"api":return fo();case"app":return mo();default:return gn()}}function gn(){return`<script>
1607
1607
  const title = "My stx Page"
1608
1608
  const description = "A page built with stx"
1609
1609
  const features = [
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
2032
- </html>`}var bi="f9c3713";function Sc(t){return t}function kc(t){return t}function pi(t,r){let i=[],p=`${r}=`;for(let a=0;a<t.length;a++){let l=t[a];if(l.startsWith(p)){let f=l.slice(p.length);if(f)i.push(f);continue}if(l===r){let f=t[a+1];if(f!==void 0&&!f.startsWith("-"))i.push(f),a++}}return i}import Oe from"fs";import ye from"path";function $n(t){try{return Oe.statSync(t).mtimeMs}catch{return null}}function Et(t,r){let i=Math.max(0,Math.round((r-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 Ai(t,r){try{return globalThis.Bun?.resolveSync(t,r)??null}catch{return null}}function Cn(t,r="stx"){let i=ye.resolve(t);for(let p=0;p<10;p++){let a=ye.join(i,"pantry","@stacksjs",r);if(Oe.existsSync(a))return a;let l=ye.dirname(i);if(l===i)break;i=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let r=Oe.readFileSync(ye.join(t,"package.json"),"utf8"),i=JSON.parse(r)?.version;return typeof i==="string"?i:null}catch{return null}}function Mi(t,r=6){let i=ye.resolve(t),p=[],a=new Set;function l(u,y){if(y>r)return;let m;try{m=Oe.realpathSync(u)}catch{return}if(a.has(m))return;a.add(m);for(let w of Rn){let S=ye.join(u,w),C=Di(S);if(C!==null)p.push({name:w,version:C,dir:ye.relative(i,S)||S,nested:y>0})}let b;try{b=Oe.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ye.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Oe.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=ye.join(S,x.name,"node_modules");if(Oe.existsSync(T))l(T,y+1)}continue}let C=ye.join(S,"node_modules");if(Oe.existsSync(C))l(C,y+1)}}let f=ye.join(i,"node_modules");if(Oe.existsSync(f))l(f,0);return p}function _i(t){let r=[];for(let i of Rn){let p=t.filter((f)=>f.name===i);if(p.length<=1)continue;let a=[...new Set(p.map((f)=>f.version))],l=p.map((f)=>`${f.version} at ${f.dir}`).join("; ");if(a.length===1){r.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${a[0]} \u2014 duplicated but in agreement`});continue}r.push({name:`${i} copies disagree`,status:"error",detail:`${a.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 r}async function Is(t={}){let r=t.cwd?ye.resolve(t.cwd):process.cwd(),i=t.resolve??Ai,p=Date.now(),a=[],l=i("@stacksjs/stx",r);a.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 f=i("bun-plugin-stx",r);if(f)a.push({name:"bun-plugin-stx resolves to",status:"ok",detail:f});for(let y of _i(Mi(r)))a.push(y);let u=Cn(r,"stx");if(!u)a.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ye.join(u,"src/signals.ts"),m=[ye.join(u,"dist/index.js"),ye.join(u,"dist/signals.js")].find((v)=>Oe.existsSync(v))||null,b=$n(y),w=m?$n(m):null;if(b==null)a.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)a.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<b){let v=Math.round((b-w)/1000);a.push({name:"pantry dist freshness",status:"error",detail:`dist (${Et(w,p)}) is OLDER than src/signals.ts (${Et(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else a.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Et(b,p)}, dist ${Et(w,p)})`});let S=ye.join(r,"node_modules/@stacksjs/stx"),C=null;try{C=Oe.lstatSync(S)}catch{C=null}if(!C)a.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=Oe.realpathSync(S)}catch{}let x=(()=>{try{return Oe.realpathSync(u)}catch{return u}})();a.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 a.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(a.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 m=t.generateRuntime().length;a.push(m>1000?{name:"signals runtime",status:"ok",detail:`generated ${m.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${m} chars \u2014 suspiciously short`})}catch(y){a.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:a,ok:!a.some((y)=>y.status==="error")}}function Os(t){let r={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${r[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(`
2033
- `)}export{pi,fi,gi,mi,Ps,hi,yi,bi,Sc,kc,Is,Os,kr,_r,Cr};
2032
+ </html>`}var wi="f9c3713";function _c(t){return t}function Cc(t){return t}function gi(t,r){let s=[],p=`${r}=`;for(let a=0;a<t.length;a++){let l=t[a];if(l.startsWith(p)){let f=l.slice(p.length);if(f)s.push(f);continue}if(l===r){let f=t[a+1];if(f!==void 0&&!f.startsWith("-"))s.push(f),a++}}return s}import Pe from"fs";import ge from"path";function $n(t){try{return Pe.statSync(t).mtimeMs}catch{return null}}function Rt(t,r){let s=Math.max(0,Math.round((r-t)/1000));if(s<60)return`${s}s ago`;if(s<3600)return`${Math.round(s/60)}m ago`;return`${Math.round(s/3600)}h ago`}function Ai(t,r){try{return globalThis.Bun?.resolveSync(t,r)??null}catch{return null}}function Cn(t,r="stx"){let s=ge.resolve(t);for(let p=0;p<10;p++){let a=ge.join(s,"pantry","@stacksjs",r);if(Pe.existsSync(a))return a;let l=ge.dirname(s);if(l===s)break;s=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let r=Pe.readFileSync(ge.join(t,"package.json"),"utf8"),s=JSON.parse(r)?.version;return typeof s==="string"?s:null}catch{return null}}function Mi(t,r=6){let s=ge.resolve(t),p=[],a=new Set;function l(u,y){if(y>r)return;let m;try{m=Pe.realpathSync(u)}catch{return}if(a.has(m))return;a.add(m);for(let w of Rn){let S=ge.join(u,w),C=Di(S);if(C!==null)p.push({name:w,version:C,dir:ge.relative(s,S)||S,nested:y>0})}let b;try{b=Pe.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ge.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Pe.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=ge.join(S,x.name,"node_modules");if(Pe.existsSync(T))l(T,y+1)}continue}let C=ge.join(S,"node_modules");if(Pe.existsSync(C))l(C,y+1)}}let f=ge.join(s,"node_modules");if(Pe.existsSync(f))l(f,0);return p}function _i(t){let r=[];for(let s of Rn){let p=t.filter((f)=>f.name===s);if(p.length<=1)continue;let a=[...new Set(p.map((f)=>f.version))],l=p.map((f)=>`${f.version} at ${f.dir}`).join("; ");if(a.length===1){r.push({name:`${s} copies`,status:"info",detail:`${p.length} copies, all ${a[0]} \u2014 duplicated but in agreement`});continue}r.push({name:`${s} copies disagree`,status:"error",detail:`${a.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${s}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${s}/package.json' -exec grep -H '"version"' {} +`})}return r}async function Ns(t={}){let r=t.cwd?ge.resolve(t.cwd):process.cwd(),s=t.resolve??Ai,p=Date.now(),a=[],l=s("@stacksjs/stx",r);a.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 f=s("bun-plugin-stx",r);if(f)a.push({name:"bun-plugin-stx resolves to",status:"ok",detail:f});for(let y of _i(Mi(r)))a.push(y);let u=Cn(r,"stx");if(!u)a.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ge.join(u,"src/signals.ts"),m=[ge.join(u,"dist/index.js"),ge.join(u,"dist/signals.js")].find((v)=>Pe.existsSync(v))||null,b=$n(y),w=m?$n(m):null;if(b==null)a.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)a.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<b){let v=Math.round((b-w)/1000);a.push({name:"pantry dist freshness",status:"error",detail:`dist (${Rt(w,p)}) is OLDER than src/signals.ts (${Rt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else a.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Rt(b,p)}, dist ${Rt(w,p)})`});let S=ge.join(r,"node_modules/@stacksjs/stx"),C=null;try{C=Pe.lstatSync(S)}catch{C=null}if(!C)a.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=Pe.realpathSync(S)}catch{}let x=(()=>{try{return Pe.realpathSync(u)}catch{return u}})();a.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 a.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(a.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 m=t.generateRuntime().length;a.push(m>1000?{name:"signals runtime",status:"ok",detail:`generated ${m.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${m} chars \u2014 suspiciously short`})}catch(y){a.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:a,ok:!a.some((y)=>y.status==="error")}}function Ds(t){let r={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},s=["stx runtime resolution:"];for(let p of t.checks)if(s.push(` ${r[p.status]} ${p.name}: ${p.detail}`),p.fix)s.push(` \u2192 ${p.fix}`);return s.push(""),s.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),s.join(`
2033
+ `)}export{gi,mi,hi,yi,Os,bi,vi,wi,_c,Cc,Ns,Ds,Cr,Er,Tr};