@stacksjs/stx 0.2.644 → 0.2.647

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 (265) hide show
  1. package/dist/builtins/attrs.js +6 -6
  2. package/dist/builtins/escape.d.ts +0 -11
  3. package/dist/builtins/escape.js +2 -1
  4. package/dist/builtins/safe-image.js +1 -3
  5. package/dist/builtins/stx-image.js +1 -3
  6. package/dist/builtins/stx-link.d.ts +3 -0
  7. package/dist/builtins/stx-link.js +1 -3
  8. package/dist/{chunk-1m5cjrpw.js → chunk-04kg16qs.js} +4 -4
  9. package/dist/chunk-0jq3w712.js +65 -0
  10. package/dist/chunk-0ky1j84b.js +2 -0
  11. package/dist/chunk-0m08316b.js +2 -0
  12. package/dist/{chunk-qf210sfx.js → chunk-0z5cc7qn.js} +8 -8
  13. package/dist/{chunk-0ergsswn.js → chunk-120ze5ms.js} +3 -3
  14. package/dist/chunk-1c5p7ede.js +2 -0
  15. package/dist/chunk-1q6yvbdx.js +2 -0
  16. package/dist/chunk-1x4qn6fy.js +2 -0
  17. package/dist/chunk-20f1veqy.js +3 -0
  18. package/dist/chunk-2a4szpje.js +3 -0
  19. package/dist/chunk-2c3w367n.js +2 -0
  20. package/dist/chunk-2cxav9xe.js +2 -0
  21. package/dist/chunk-2f17h17f.js +2 -0
  22. package/dist/{chunk-ktvr45qg.js → chunk-2qbvsvwc.js} +2 -2
  23. package/dist/chunk-2v4s7xtx.js +2 -0
  24. package/dist/chunk-31714f76.js +2 -0
  25. package/dist/chunk-354jmw2k.js +3 -0
  26. package/dist/chunk-3e7haxwt.js +2 -0
  27. package/dist/{chunk-afsf6sp0.js → chunk-3ghbxena.js} +14 -14
  28. package/dist/chunk-40y6mb8t.js +2 -0
  29. package/dist/chunk-42rghbqe.js +12 -0
  30. package/dist/chunk-4fz2eq7g.js +2 -0
  31. package/dist/{chunk-1t0m4pwg.js → chunk-4yf1w261.js} +2 -2
  32. package/dist/chunk-4yt8tg4j.js +2 -0
  33. package/dist/chunk-52gp2xxk.js +2 -0
  34. package/dist/chunk-55x799st.js +49 -0
  35. package/dist/chunk-5e20mvke.js +2 -0
  36. package/dist/chunk-5fzh8n52.js +2 -0
  37. package/dist/chunk-5gtpswnm.js +2 -0
  38. package/dist/{chunk-a0ygyftk.js → chunk-5t4qtxgr.js} +2 -2
  39. package/dist/chunk-5yg3tkth.js +2 -0
  40. package/dist/chunk-67kj14at.js +2 -0
  41. package/dist/{chunk-gqz26wza.js → chunk-6ajahb2x.js} +3 -3
  42. package/dist/chunk-6vzktvyw.js +2 -0
  43. package/dist/chunk-70pmthc3.js +2 -0
  44. package/dist/chunk-74pej67a.js +18 -0
  45. package/dist/{chunk-g1ae3haw.js → chunk-7rta163c.js} +2 -2
  46. package/dist/chunk-7s32fe6k.js +3 -0
  47. package/dist/chunk-84djpte6.js +3 -0
  48. package/dist/chunk-864qtx7y.js +2 -0
  49. package/dist/chunk-8ttg2d3m.js +2 -0
  50. package/dist/{chunk-9yk5rasj.js → chunk-9am6dsb1.js} +3 -3
  51. package/dist/{chunk-5e063mgs.js → chunk-9p6efb17.js} +1 -1
  52. package/dist/chunk-9qeg5trh.js +2 -0
  53. package/dist/chunk-9szxxgv5.js +2 -0
  54. package/dist/{chunk-bsts9pr5.js → chunk-9y2ncrnq.js} +2 -2
  55. package/dist/chunk-9z9jtwct.js +33 -0
  56. package/dist/{chunk-y255yybn.js → chunk-a3d0g4mr.js} +2 -2
  57. package/dist/{chunk-9939fjh4.js → chunk-a8j91pqz.js} +11 -11
  58. package/dist/{chunk-hshcbe3p.js → chunk-aah6csjm.js} +11 -11
  59. package/dist/{chunk-cw8mx4qf.js → chunk-ajv5xmjx.js} +169 -169
  60. package/dist/chunk-apgb7r22.js +2 -0
  61. package/dist/{chunk-c858mepd.js → chunk-aprhqxky.js} +5 -5
  62. package/dist/{chunk-29sq7kqw.js → chunk-ar22s1e1.js} +2 -2
  63. package/dist/chunk-asqnaddf.js +3 -0
  64. package/dist/chunk-aze7k3a5.js +2 -0
  65. package/dist/chunk-b07djygp.js +18 -0
  66. package/dist/chunk-b0vhe6d4.js +4 -0
  67. package/dist/chunk-b4fd2dtk.js +2 -0
  68. package/dist/chunk-bk96wjaz.js +61 -0
  69. package/dist/chunk-c7fs96n6.js +4 -0
  70. package/dist/chunk-c9k40352.js +2 -0
  71. package/dist/{chunk-ahyq08mp.js → chunk-ce6zddpf.js} +3 -3
  72. package/dist/{chunk-cpxtmmvv.js → chunk-cj2xj1v6.js} +39 -40
  73. package/dist/chunk-cs0dd5w8.js +2 -0
  74. package/dist/chunk-cwd65649.js +2 -0
  75. package/dist/{chunk-2s3sxt48.js → chunk-da7x7y7j.js} +1 -1
  76. package/dist/{chunk-wjq1wqn6.js → chunk-dgb4z4kw.js} +2 -2
  77. package/dist/chunk-dpjnjs09.js +888 -0
  78. package/dist/chunk-e7sg0fa0.js +2 -0
  79. package/dist/chunk-edz1h5f9.js +2 -0
  80. package/dist/chunk-egg54kd0.js +12 -0
  81. package/dist/chunk-ek2adv0n.js +2 -0
  82. package/dist/chunk-emaexvgz.js +2 -0
  83. package/dist/{chunk-pp6ycfay.js → chunk-ewcrsyr7.js} +2 -2
  84. package/dist/chunk-fcn71bq1.js +2 -0
  85. package/dist/{chunk-dcwhp21g.js → chunk-fg3jw17w.js} +48 -48
  86. package/dist/chunk-fygp3cs9.js +2 -0
  87. package/dist/chunk-g2jmwh7p.js +2 -0
  88. package/dist/chunk-g8r0km7g.js +106 -0
  89. package/dist/{chunk-gmxrckgj.js → chunk-gc9ftf7r.js} +3 -3
  90. package/dist/chunk-ggwm8w5m.js +2 -0
  91. package/dist/chunk-h5zr710w.js +2 -0
  92. package/dist/chunk-hgy4c6mm.js +11 -0
  93. package/dist/chunk-hvtzw1jh.js +2 -0
  94. package/dist/{chunk-4n24jbfs.js → chunk-hvzzhkhr.js} +2 -2
  95. package/dist/chunk-j0v970k3.js +2 -0
  96. package/dist/chunk-jk41jwsc.js +2 -0
  97. package/dist/{chunk-6mnwvn9v.js → chunk-jkvr7e91.js} +2 -2
  98. package/dist/{chunk-639ngkgb.js → chunk-jsb4pvj1.js} +2 -2
  99. package/dist/{chunk-pf5s5gjp.js → chunk-jx3wpgv0.js} +2 -2
  100. package/dist/{chunk-fztvkacg.js → chunk-jxda11cg.js} +2 -2
  101. package/dist/chunk-jyth1zjy.js +127 -0
  102. package/dist/chunk-k2pa44rf.js +2 -0
  103. package/dist/{chunk-kad2cp0z.js → chunk-k79x96ra.js} +37 -37
  104. package/dist/{chunk-qy11cp1v.js → chunk-kgfgb971.js} +4 -4
  105. package/dist/chunk-ma7d95f0.js +31 -0
  106. package/dist/chunk-mmm6mm16.js +3 -0
  107. package/dist/{chunk-88p10v0w.js → chunk-mmwedr93.js} +5 -5
  108. package/dist/{chunk-dyg6sadv.js → chunk-mrrrngzd.js} +1 -1
  109. package/dist/{chunk-w41kp60h.js → chunk-msr25dhc.js} +4 -4
  110. package/dist/chunk-myq3hrww.js +6 -0
  111. package/dist/{chunk-fwdptew6.js → chunk-n38yb274.js} +6 -6
  112. package/dist/chunk-n4cvg2sw.js +2 -0
  113. package/dist/chunk-nph4d1ff.js +42 -0
  114. package/dist/{chunk-aztp8r80.js → chunk-nrvwejdw.js} +5 -5
  115. package/dist/{chunk-17x6e5mm.js → chunk-p08x0z86.js} +7 -7
  116. package/dist/chunk-p22w6mwr.js +2 -0
  117. package/dist/{chunk-xsmvcnmx.js → chunk-pdc9s7bg.js} +2 -2
  118. package/dist/chunk-pfk9ffbz.js +3 -0
  119. package/dist/{chunk-pvfx0dgz.js → chunk-prf164ct.js} +2 -2
  120. package/dist/chunk-pw9bhdaz.js +4 -0
  121. package/dist/chunk-qn63btbf.js +2 -0
  122. package/dist/{chunk-eyy6zmdk.js → chunk-qv6axke4.js} +2 -2
  123. package/dist/{chunk-60azcvwr.js → chunk-r3e6x87d.js} +3 -3
  124. package/dist/chunk-rb5xdcen.js +25 -0
  125. package/dist/{chunk-45xhjrha.js → chunk-rcadtv3x.js} +1 -1
  126. package/dist/{chunk-j00v4m56.js → chunk-rjh2jwxx.js} +9 -9
  127. package/dist/chunk-rwrbdpdk.js +2 -0
  128. package/dist/chunk-sf0wsq74.js +2 -0
  129. package/dist/chunk-shkysa02.js +20 -0
  130. package/dist/chunk-shpc1ttk.js +2 -0
  131. package/dist/{chunk-48yja477.js → chunk-t2pzy3x1.js} +3 -3
  132. package/dist/chunk-t6yjxhn8.js +2 -0
  133. package/dist/chunk-tkkvvt26.js +2 -0
  134. package/dist/{chunk-b4j5bpec.js → chunk-tre98h62.js} +2 -2
  135. package/dist/chunk-vac56rgd.js +12 -0
  136. package/dist/chunk-vdxjy7j2.js +4 -0
  137. package/dist/{chunk-gsp3627d.js → chunk-vgt9f7ac.js} +4 -4
  138. package/dist/{chunk-vq4sh8aq.js → chunk-vmwdt8fr.js} +5 -5
  139. package/dist/chunk-vn3yx05b.js +2 -0
  140. package/dist/{chunk-fqg0espy.js → chunk-vqc4h16r.js} +2 -2
  141. package/dist/chunk-w1v1d7rq.js +406 -0
  142. package/dist/chunk-w2q32x72.js +2 -0
  143. package/dist/chunk-weqc0ssb.js +2 -0
  144. package/dist/{chunk-kjspmegt.js → chunk-wpmrz872.js} +2 -2
  145. package/dist/chunk-wq712sw1.js +2 -0
  146. package/dist/chunk-wzgn9fv7.js +20 -0
  147. package/dist/{chunk-s775b8ra.js → chunk-x8k64g1e.js} +2 -2
  148. package/dist/chunk-xaa36b0x.js +3 -0
  149. package/dist/chunk-xnjf1zbn.js +21 -0
  150. package/dist/chunk-xyjn0rvj.js +3 -0
  151. package/dist/chunk-y3vget29.js +2 -0
  152. package/dist/chunk-y9x4pyp2.js +2 -0
  153. package/dist/chunk-yfrvbnc6.js +1312 -0
  154. package/dist/{chunk-drrczm0b.js → chunk-ym41ybz2.js} +6 -6
  155. package/dist/chunk-z8p6tk5z.js +2 -0
  156. package/dist/{chunk-gbxzqvez.js → chunk-zevx9866.js} +2 -2
  157. package/dist/chunk-zhf01af3.js +3 -0
  158. package/dist/{chunk-6avpd901.js → chunk-zqtbtqbq.js} +2 -2
  159. package/dist/chunk-ztbzktzg.js +2 -0
  160. package/dist/cli.js +62 -62
  161. package/dist/craft-entry.js +2 -2
  162. package/dist/craft.js +2 -2
  163. package/dist/expressions.d.ts +6 -21
  164. package/dist/expressions.js +12 -41
  165. package/dist/forms-validation.d.ts +0 -16
  166. package/dist/forms-validation.js +4 -2
  167. package/dist/forms.js +8 -6
  168. package/dist/i18n.js +6 -4
  169. package/dist/interpolation-context.js +69 -28
  170. package/dist/loops.js +70 -90
  171. package/dist/mustache-span.d.ts +21 -0
  172. package/dist/mustache-span.js +35 -0
  173. package/dist/native-build.d.ts +5 -0
  174. package/dist/native-build.js +11 -27
  175. package/dist/process.js +4 -3
  176. package/dist/pwa.js +3 -3
  177. package/dist/server-bindings.js +12 -6
  178. package/dist/ssg.js +28 -28
  179. package/dist/utils.js +1 -2
  180. package/package.json +5 -5
  181. package/dist/chunk-12677ap2.js +0 -31
  182. package/dist/chunk-162gprh9.js +0 -2
  183. package/dist/chunk-1p6yd17s.js +0 -2
  184. package/dist/chunk-29gd2kkk.js +0 -20
  185. package/dist/chunk-3hkp5hym.js +0 -2
  186. package/dist/chunk-3jrssj8g.js +0 -2
  187. package/dist/chunk-444pz8yk.js +0 -2
  188. package/dist/chunk-47shfmkf.js +0 -3
  189. package/dist/chunk-4b5f28te.js +0 -2
  190. package/dist/chunk-4dpq1bnh.js +0 -2
  191. package/dist/chunk-4mm9ttc7.js +0 -2
  192. package/dist/chunk-5c511mj0.js +0 -2
  193. package/dist/chunk-5kbkx0np.js +0 -3
  194. package/dist/chunk-5wyp57g3.js +0 -4
  195. package/dist/chunk-6bdr0x43.js +0 -18
  196. package/dist/chunk-6vmvra0f.js +0 -65
  197. package/dist/chunk-70et0fbw.js +0 -12
  198. package/dist/chunk-7mkw98cr.js +0 -3
  199. package/dist/chunk-7qgsgfnt.js +0 -2
  200. package/dist/chunk-87kza2ez.js +0 -2
  201. package/dist/chunk-8bk1ghb7.js +0 -127
  202. package/dist/chunk-8cqx63aw.js +0 -3
  203. package/dist/chunk-8k5eac6p.js +0 -2
  204. package/dist/chunk-9nvrkpee.js +0 -2
  205. package/dist/chunk-9ny6xzw0.js +0 -2
  206. package/dist/chunk-9r538d93.js +0 -2
  207. package/dist/chunk-9xaztqhw.js +0 -2
  208. package/dist/chunk-b2teprjf.js +0 -2
  209. package/dist/chunk-bnfjwgtm.js +0 -20
  210. package/dist/chunk-br7xk2hb.js +0 -2
  211. package/dist/chunk-c8p5jwdq.js +0 -2
  212. package/dist/chunk-cd76dwdn.js +0 -2
  213. package/dist/chunk-degxqdbb.js +0 -2
  214. package/dist/chunk-dr4325et.js +0 -2
  215. package/dist/chunk-e7bd4vxb.js +0 -2
  216. package/dist/chunk-eh7qq39j.js +0 -2
  217. package/dist/chunk-ek5vrw4r.js +0 -2
  218. package/dist/chunk-erweevv2.js +0 -2
  219. package/dist/chunk-fdxyj3pk.js +0 -2
  220. package/dist/chunk-ft3r2rzs.js +0 -2
  221. package/dist/chunk-fywp8fcr.js +0 -2
  222. package/dist/chunk-g14mwhqz.js +0 -2
  223. package/dist/chunk-g6s0xdgb.js +0 -4
  224. package/dist/chunk-grg366m9.js +0 -2852
  225. package/dist/chunk-h3brvxbf.js +0 -3
  226. package/dist/chunk-hbk20w21.js +0 -2
  227. package/dist/chunk-hrdnz5q9.js +0 -2
  228. package/dist/chunk-hvk5zkpm.js +0 -4
  229. package/dist/chunk-j0jz4mfm.js +0 -2
  230. package/dist/chunk-j37720vw.js +0 -2
  231. package/dist/chunk-j6fxzkn5.js +0 -2
  232. package/dist/chunk-ja3m0h9h.js +0 -12
  233. package/dist/chunk-jmdrhpy7.js +0 -2
  234. package/dist/chunk-jshv1ye7.js +0 -2
  235. package/dist/chunk-jtk2p5p0.js +0 -2
  236. package/dist/chunk-k46gqnmk.js +0 -2
  237. package/dist/chunk-ktjvqwp4.js +0 -2
  238. package/dist/chunk-kv5mn1qr.js +0 -6
  239. package/dist/chunk-kxbw0e2f.js +0 -3
  240. package/dist/chunk-ky043mkv.js +0 -2
  241. package/dist/chunk-m2bnyrft.js +0 -2
  242. package/dist/chunk-m92q2jyt.js +0 -40
  243. package/dist/chunk-mbqqc20a.js +0 -2
  244. package/dist/chunk-mqmxhggf.js +0 -2
  245. package/dist/chunk-myq0m4h4.js +0 -2
  246. package/dist/chunk-nkgzwyad.js +0 -2
  247. package/dist/chunk-ns4pc13z.js +0 -2
  248. package/dist/chunk-nv9syzs0.js +0 -2
  249. package/dist/chunk-pn719qwa.js +0 -2
  250. package/dist/chunk-qmh6f1bt.js +0 -24
  251. package/dist/chunk-r00nn2qs.js +0 -4
  252. package/dist/chunk-re2mry1d.js +0 -2
  253. package/dist/chunk-s0tbc9t1.js +0 -33
  254. package/dist/chunk-s7e9ztgq.js +0 -2
  255. package/dist/chunk-t6awky15.js +0 -11
  256. package/dist/chunk-tcq0me7c.js +0 -2
  257. package/dist/chunk-vse0hhn9.js +0 -2
  258. package/dist/chunk-vvgs62za.js +0 -2
  259. package/dist/chunk-wj4rf7sb.js +0 -2
  260. package/dist/chunk-x901zq4q.js +0 -2
  261. package/dist/chunk-xe8qmf1d.js +0 -2
  262. package/dist/chunk-xqtzk9wr.js +0 -2
  263. package/dist/chunk-y51ndrdb.js +0 -2
  264. package/dist/chunk-yn2d8x8m.js +0 -3
  265. package/dist/chunk-zrngcg6r.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{J,b,xn,Sn,e,Bt,_n,f,Ye,Ft,Ze,Qe,oe,j,ye,Q,u,Ae,Li,Fs,n,r,ie,br,o,P,be}from"./chunk-grg366m9.js";import{q,jn,ae,O,Wt}from"./chunk-m92q2jyt.js";import{pt,Vn,Ir,Or,Nr,ft,gt,mt,ht,yt,bt,De}from"./chunk-gsp3627d.js";import{He,Io,ce,T,Oo,Gr,Zn,ke,No,le}from"./chunk-12677ap2.js";import{Kt}from"./chunk-h3brvxbf.js";import{fe}from"./chunk-bsts9pr5.js";import{a}from"./chunk-8cqx63aw.js";import{D}from"./chunk-7mkw98cr.js";async function Wn(t){try{let s=await Bun.file(t).text(),i=Xn(s),d=Jn(s,t),c=Yn(s,i),l=Qn(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Xn(t){let s=t.split(`
3
- `),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(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 m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+p+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,R=0;for(let C of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,S=Math.max(S,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function Jn(t,s){let i=[],d=Jt(t,"if","endif");if(d>0)i.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Jt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let y=p.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
5
- `).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function Yn(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function Qn(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:d,recommendations:c}}function Jt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function vo(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await Wn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Re from"path";function rn(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 on=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(d){let c=await rr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Re.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function dr(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=m.exec(l)){let h=p[1];if(on.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}return i}function pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
2
+ import{te,ie,cn,Rt,At,f,n,de,m}from"./chunk-w1v1d7rq.js";import{ft,Ce,ta,Ys,s}from"./chunk-dpjnjs09.js";import{ne,ur,be,D,hn}from"./chunk-bk96wjaz.js";import{bt,Zn,Zr,Qr,es,vt,wt,xt,St,kt,_t,Ke}from"./chunk-vgt9f7ac.js";import{qr,i,R}from"./chunk-yfrvbnc6.js";import{lt,Ci,we,O,Ei,js,$r,Fe,Ti,xe}from"./chunk-ma7d95f0.js";import{Xn,Jn}from"./chunk-xyjn0rvj.js";import{xn}from"./chunk-pfk9ffbz.js";import{e,en,Wn,h}from"./chunk-74pej67a.js";import{Ue}from"./chunk-55x799st.js";import{_e}from"./chunk-9y2ncrnq.js";import{V,ge,me}from"./chunk-vac56rgd.js";import{c}from"./chunk-zhf01af3.js";import{H}from"./chunk-354jmw2k.js";async function Fn(t){try{let r=await Bun.file(t).text(),o=zn(r),d=Nn(r,t),a=Un(r,o),l=Vn(r,o);return{file:t,metrics:o,issues:d,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
+ `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(o?o[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 u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=u+p+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+g*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let o=[],d=qt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=qt(t,"foreach","endforeach");if(a>0)o.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)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let b=p.filter((w)=>!w.includes("alt="));if(b.length>0)o.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)o.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)o.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Un(t,r){let o=[];if(r.complexity>7)o.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)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.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)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Vn(t,r){let o=1;if(o+=r.directives.conditionals*0.1,o+=r.directives.loops*0.5,o+=r.directives.includes*2,o+=r.expressions*0.05,o+=r.components*1,r.scriptLines>10)o+=r.scriptLines*0.1;let d;if(r.expressions===0&&r.directives.total===0)d="high";else if(r.expressions<5&&r.directives.total<3)d="medium";else d="low";let a=[];if(o>10)a.push("Consider optimizing template complexity");if(d==="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(o*100)/100,complexityScore:r.complexity,cacheability:d,recommendations:a}}function qt(t,r,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),a=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function pi(t=["**/*.stx"],r){let o=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let u=await Fn(l);o.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let a=qn(o);return{results:o,summary:a}}function qn(t){let r=t.length,o=t.reduce((g,b)=>g+b.metrics.lines,0),d=r>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/r:0,a=t.reduce((g,b)=>g+b.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let u=r>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/r:0,p=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),y=[];if(d>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:o,avgComplexity:Math.round(d*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:p,recommendations:y}}import{mkdir as Kn,readFile as Gn,readdir as Yn,stat as Kt,writeFile as Qn}from"fs/promises";import Te 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 o(d){let a=await Yn(d,{withFileTypes:!0});a.sort((l,u)=>l.name.localeCompare(u.name));for(let l of a){let u=Te.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await o(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(u)}}return await o(t),r}function or(t,r){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of d){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 u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,p;while(p=u.exec(l)){let y=p[1];if(tn.has(y))throw Error(`${r}: client ${Zt(y)}`);let g=u.lastIndex,b=1,w="",S=!1,C=g;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=p[0].includes("async")?"async ":"";o[y]=`${v}${y}(${p[2]}) {${l.slice(g,C-1)}}`,u.lastIndex=C}}return o}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 ur(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function fr(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 mr(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 gr(t){let s=[],i=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(d[h]!=="(")return null;let g=0,y="";for(let w=h;w<d.length;w++){let S=d[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:d.slice(h+1,w),end:w+1}}}return null},p=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(d)){p(d.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,R,v]=w;s.push(R?`for (const [${R}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return p(d.slice(i)),s.join(`
8
- `)}function ut(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function _t(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function hr(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Zt(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 yr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=ut(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let R="";if(h(),t[p]==="<"){let k=ut(t,p,"<",">");if(k===-1)return null;R=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=ut(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=ut(t,p,"{","}");if(k===-1)return null;for(let[B,_]of Lt(t.slice(p,k)))l[B]=_;p=k}if(h(),t[p]===",")p++,h();if(t[p]===")")p++}if(t[p]===";")p++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of _t(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of Lt(x)){if(m.push(k),!B.startsWith("{")){let _=Zt(B);if(_)c[k]=_;continue}for(let[_,I]of Lt(B))if(_==="default")l[k]=I;else if(_==="type"){let E=Zt(I);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of _t(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of _t(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=hr(k),I=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),B!==-1)l[I]=k.slice(B+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(d,p),propNames:m,defaults:l,declared:c,typeName:C}}function Lt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],d=0;while(d<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=d;let l=c.exec(s);if(!l)break;d=c.lastIndex;let m=0,p="",h=d;while(d<s.length){let y=s[d];if(p){if(y==="\\")d++;else if(y===p)p=""}else if(y==="'"||y==='"'||y==="`")p=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;d++}let g=s.slice(h,d).trim();if(g)i.push([l[1],g]);d++}return i}function xr(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],p=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Re.resolve(Re.dirname(s),x),B=Re.relative(i,k);return`${v}${B.startsWith(".")?B:`./${B}`}${C}`})),""});let y=yr(l);if(y)p.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let R=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!p.includes(S))p.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:p,defaults:h,declared:g}}function vr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,c,l,m,p)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${p}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function wr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,c,l,m)=>{let p=s.length;return s.push({id:p,name:c,expression:m}),` data-stx-bind-${p}=""`}),bindings:s}}function Sr(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function kr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function Tr(t,s,i){let d=Re.isAbsolute(s.file)?s.file:Re.resolve(t,s.file),c=await nr(d,"utf8"),l=lr(c,d),m=Re.basename(d,".stx"),p=s.name||l.name||sr(m),h=`${It(i.prefix||"stx")}-${It(m)}`,g=s.tag||l.tag||h;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!ir(g))throw Error(`${d}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([_,I])=>[_,en(_,I)])),S=vr(pr(c)),R=wr(S.template),v=xr(c,d,Re.resolve(i.outputDir)),x=gr(R.template);for(let _ of v.propNames){if(w[_])continue;let I=v.defaults[_];w[_]=en(_,{type:ur(v.declared[_])??fr(I),...I===void 0?{}:{default:mr(I)}})}let C=l.methods||{},k=s.methods||{},B=dr(c,d);return{file:Re.relative(t,d),sourcePath:d,name:p,tag:g,description:s.description||l.description||"",template:R.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...B},eventTypes:S.eventTypes,bindings:R.bindings,slots:Sr(R.template),cssProperties:kr(Qt(c)),scope:v,render:x}}function $r(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=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=[],o=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),a=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(y)=>{if(d[y]!=="(")return null;let g=0,b="";for(let w=y;w<d.length;w++){let S=d[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:d.slice(y+1,w),end:w+1}}}return null},p=(y)=>{if(y==="")return;let g=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>g)r.push(`out += ${JSON.stringify(y.slice(g,w.index))};`);r.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<y.length)r.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=a.exec(d)){p(d.slice(o,l.index)),o=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(o):null;if(g)o=g.end,a.lastIndex=g.end;let b=g?.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]+(g?`(${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 p(d.slice(o)),r.join(`
8
+ `)}function at(t,r,o,d){if(t[r]!==o)return-1;let a=0,l=null;for(let u=r;u<t.length;u++){let p=t[u];if(l){if(p==="\\"){u++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===o)a++;else if(p===d){if(d===">"&&t[u-1]==="=")continue;if(a--,a===0)return u+1}}return-1}function Mt(t,r,o){let d=o?"([{<":"([{",a=o?")]}>":")]}",l=[],u=0,p=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(p){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===p)p=null;continue}if(b==="'"||b==='"'||b==="`"){p=b,y+=b;continue}if(d.includes(b))u++;else if(a.includes(b))u--;if(u===0&&r.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function pr(t){let r=0,o=null;for(let d=0;d<t.length;d++){let a=t[d];if(o){if(a==="\\"){d++;continue}if(a===o)o=null;continue}if(a==="'"||a==='"'||a==="`"){o=a;continue}if("([{".includes(a))r++;else if(")]}".includes(a))r--;if(r!==0||a!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}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 o=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=o.exec(t);k&&k.index<r.index;k=o.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let a={},l={},u=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),y=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=at(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(y(),t[p]!=="=")return null;p++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(b);if(b)p+=b[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let C="";if(y(),t[p]==="<"){let k=at(t,p,"<",">");if(k===-1)return null;C=t.slice(p+1,k-1).trim(),p=k}if(y(),t[p]!=="(")return null;let v=at(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(y(),t[p]===",")p++,y();if(t[p]==="{"){let k=at(t,p,"{","}");if(k===-1)return null;for(let[j,M]of Lt(t.slice(p,k)))l[j]=M;p=k}if(y(),t[p]===",")p++,y();if(t[p]===")")p++}if(t[p]===";")p++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of 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(u.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))u.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){u.length=0;for(let k of Mt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let j=pr(k),L=(j===-1?k:k.slice(0,j)).split(":")[0].trim().replace(/^\.\.\./,"");if(!L)continue;if(u.push(L),j!==-1)l[L]=k.slice(j+1).trim()}}else if(u.length===0)u.push(...Object.keys(a));return{text:t.slice(d,p),propNames:u,defaults:l,declared:a,typeName:T}}function Lt(t){let r=t.trim().replace(/^\{/,"").replace(/\}$/,""),o=[],d=0;while(d<r.length){let a=/\s*([A-Za-z_$][\w$]*)\s*:/y;a.lastIndex=d;let l=a.exec(r);if(!l)break;d=a.lastIndex;let u=0,p="",y=d;while(d<r.length){let b=r[d];if(p){if(b==="\\")d++;else if(b===p)p=""}else if(b==="'"||b==='"'||b==="`")p=b;else if(b==="{"||b==="["||b==="(")u++;else if(b==="}"||b==="]"||b===")")u--;else if(b===","&&u===0)break;d++}let g=r.slice(y,d).trim();if(g)o.push([l[1],g]);d++}return o}function mr(t,r,o){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],u=[],p=[],y={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return u.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Te.resolve(Te.dirname(r),x),j=Te.relative(o,k);return`${v}${j.startsWith(".")?j:`./${j}`}${T}`})),""});let b=fr(l);if(b)p.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(g,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))g[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(!p.includes(S))p.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:p,defaults:y,declared:g}}function gr(t){let r=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,a,l,u,p)=>{let y=a.toLowerCase();r.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${p}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...r].sort()}}function hr(t){let r=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,a,l,u)=>{let p=r.length;return r.push({id:p,name:a,expression:u}),` data-stx-bind-${p}=""`}),bindings:r}}function yr(t){let r=new Set;for(let o of t.matchAll(/<slot\b([^>]*)>/gi))r.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...r].map((o)=>({name:o}))}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,o){let d=Te.isAbsolute(r.file)?r.file:Te.resolve(t,r.file),a=await Gn(d,"utf8"),l=or(a,d),u=Te.basename(d,".stx"),p=r.name||l.name||er(u),y=`${It(o.prefix||"stx")}-${It(u)}`,g=r.tag||l.tag||y;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!tr(g))throw Error(`${d}: invalid custom-element tag "${g}"; 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,d,Te.resolve(o.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,d);return{file:Te.relative(t,d),sourcePath:d,name:p,tag:g,description:r.description||l.description||"",template:C.template,styles:Xt(a),shadowMode:nr(r.shadowDOM??l.shadowDOM??o.shadowDOM),progressive:r.progressive??l.progressive??o.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;')
@@ -212,7 +212,7 @@ export class StxElement extends HTMLElementBase {
212
212
  ? this.render(RENDER_HELPERS)
213
213
  : definition.template
214
214
  .replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
215
- .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
215
+ .replace(new RegExp(${r}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
216
216
  if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
217
217
  root.innerHTML = html;
218
218
  this._applyBindings();
@@ -303,19 +303,19 @@ export function defineComponent(Component, definition) {
303
303
  }
304
304
  return Component;
305
305
  }
306
- `}function Cr(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([p,h])=>{if(on.has(p))throw Error(`${t.sourcePath}: ${rn(p)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${p}($event) {
307
- ${h}
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),o=Object.entries(t.methods).map(([p,y])=>{if(tn.has(p))throw Error(`${t.sourcePath}: ${Zt(p)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${p}($event) {
307
+ ${y}
308
308
  }`}).join(`
309
309
 
310
- `),d=t.scope,c=[...new Set([...Object.keys(t.properties),...d.propNames])].map((p)=>d.defaults[p]===void 0?p:`${p} = ${d.defaults[p]}`).join(", "),l=(p)=>p.split(`
311
- `).map((h)=>h.trim()===""?h:` ${h}`).join(`
312
- `),m="";if(t.render.trim()!==""||d.body!==""||c!==""){let p=[c?`const { ${c} } = this._props();`:"",d.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
313
- `),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
310
+ `),d=t.scope,a=[...new Set([...Object.keys(t.properties),...d.propNames])].map((p)=>d.defaults[p]===void 0?p:`${p} = ${d.defaults[p]}`).join(", "),l=(p)=>p.split(`
311
+ `).map((y)=>y.trim()===""?y:` ${y}`).join(`
312
+ `),u="";if(t.render.trim()!==""||d.body!==""||a!==""){let p=[a?`const { ${a} } = this._props();`:"",d.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
313
+ `),y;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
314
314
  ${p}
315
- }`),y=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(y+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
315
+ }`),b=g.indexOf("{"),w=g.lastIndexOf("}");y=g.slice(b+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}u=`
316
316
  render(__helpers) {
317
317
  const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
318
- ${l(h.trim())}
318
+ ${l(y.trim())}
319
319
  }
320
320
  `}return`import { StxElement, defineComponent } from './runtime.js';
321
321
  ${d.imports.length?`${d.imports.join(`
@@ -323,17 +323,17 @@ ${d.imports.length?`${d.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}${m}
326
+ ${o}${u}
327
327
  }
328
328
 
329
- defineComponent(${t.name}, ${s});
329
+ defineComponent(${t.name}, ${r});
330
330
  export default ${t.name};
331
- `}function xt(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 Rr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${xt(m)}`).join(`
332
- `),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${xt(m)}`).join(`
333
- `),d=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
334
- `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
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 Tr(t){let r=Object.entries(t.properties).map(([l,u])=>` ${l}${u.required?"":"?"}: ${ct(u)}`).join(`
332
+ `),o=Object.entries(t.properties).map(([l,u])=>` ${l}: ${ct(u)}`).join(`
333
+ `),d=Object.entries(t.events).map(([l,u])=>` ${JSON.stringify(l)}: CustomEvent<${u.detailType||"unknown"}>`).join(`
334
+ `),a=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
335
335
  `);return`export interface ${t.name}Props {
336
- ${s}
336
+ ${r}
337
337
  }
338
338
 
339
339
  export interface ${t.name}EventMap {
@@ -341,8 +341,8 @@ ${d}
341
341
  }
342
342
 
343
343
  export declare class ${t.name} extends HTMLElement {
344
- ${i}
345
- ${c}
344
+ ${o}
345
+ ${a}
346
346
  readonly updateComplete: Promise<void>
347
347
  requestUpdate(): Promise<void>
348
348
  emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
@@ -355,14 +355,14 @@ declare global {
355
355
  }
356
356
 
357
357
  export default ${t.name}
358
- `}function Er(t){return`declare global {
358
+ `}function Cr(t){return`declare global {
359
359
  namespace JSX {
360
360
  interface IntrinsicElements {
361
- ${t.map((i)=>{let d=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${xt(m)}`).join(`
362
- `),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
363
- `);return` ${JSON.stringify(i.tag)}: {
361
+ ${t.map((o)=>{let d=Object.entries(o.properties).map(([l,u])=>` ${JSON.stringify(l)}?: ${ct(u)}`).join(`
362
+ `),a=Object.keys(o.events).map((l)=>` ${`on${l.split(/[-:]/).map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join("")}`}?: (event: CustomEvent<${o.events[l].detailType||"unknown"}>) => void`).join(`
363
+ `);return` ${JSON.stringify(o.tag)}: {
364
364
  ${d}
365
- ${c}
365
+ ${a}
366
366
  children?: unknown
367
367
  slot?: string
368
368
  class?: string
@@ -374,10 +374,10 @@ ${c}
374
374
  }
375
375
 
376
376
  export {}
377
- `}function Pr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,d])=>({kind:"field",name:i,description:d.description,type:{text:xt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||It(i),reflects:d.reflect})),events:Object.entries(s.events).map(([i,d])=>({name:i,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
378
- ${s}
379
- }`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Ar(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
380
- `);return`const definitions = ${JSON.stringify(c,null,2)};
377
+ `}function Rr(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(([o,d])=>({kind:"field",name:o,description:d.description,type:{text:ct(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||It(o),reflects:d.reflect})),events:Object.entries(r.events).map(([o,d])=>({name:o,description:d.description,type:{text:`CustomEvent<${d.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
+ ${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*!!\\}"),o=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),a=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),l=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
380
+ `);return`const definitions = ${JSON.stringify(a,null,2)};
381
381
  const escapeHTML = (value) => String(value ?? '')
382
382
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
383
383
  .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
@@ -389,8 +389,8 @@ export function renderComponent(tag, props = {}, slots = {}) {
389
389
  const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
390
390
  Object.assign(values, props);
391
391
  let template = definition.template
392
- .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
- .replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
392
+ .replace(new RegExp(${r}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
+ .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
394
  .replace(new RegExp(${d}, '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 wo(t){let s=Re.resolve(t.inputDir),i=Re.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Tr(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let p=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Re.join(i,x);return await or(k,C.endsWith(`
414
- `)?C:`${C}
415
- `,"utf8"),h.push(k),k};await g("runtime.js",$r());for(let x of l){if(await g(`${x.tag}.js`,Cr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Rr(x));if(t.css!==!1&&x.styles){let C=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(C):C)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
- `);if(await g("index.js",y),await g("ssr.js",Ar(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
- `)),await g("custom-elements.d.ts",Er(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
413
+ `}async function fi(t){let r=Te.resolve(t.inputDir),o=Te.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 u=l.filter((x,T)=>l.findIndex((k)=>k.tag===x.tag)!==T);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let p=l.filter((x,T)=>l.findIndex((k)=>k.name===x.name)!==T);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await Kn(o,{recursive:!0});let y=[],g=async(x,T)=>{let k=Te.join(o,x);return await Qn(k,T.endsWith(`
414
+ `)?T:`${T}
415
+ `,"utf8"),y.push(k),k};await g("runtime.js",vr());for(let x of l){if(await g(`${x.tag}.js`,wr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Tr(x));if(t.css!==!1&&x.styles){let T=x.shadowMode?x.styles:Yt(x);await g(`${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 g("index.js",b),await g("ssr.js",Er(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
+ `)),await g("custom-elements.d.ts",Cr(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
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
- `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Pr(l),null,2));let S;if(t.css!==!1){let x=l.filter((C)=>!C.shadowMode&&C.styles).map(tn).join(`
421
+ `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Rr(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 g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Re.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Re.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],B=k.map((_)=>String(_).trim()).filter(Boolean).join(`
424
- `);throw AggregateError(k,`Failed to bundle component library${B?`
425
- ${B}`:""}`)}if(!x.success){let C=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
- `);throw AggregateError(x.logs,`Failed to bundle component library${C?`
427
- ${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Re.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}var{serve:Vr}=globalThis.Bun;import Ht from"fs";import ot from"path";function vt(){return`
423
+ `);if(x)S=await g("bundle.css",t.minify?Qt(x):x)}let C;if(t.bundle!==!1){C=Te.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Te.join(o,"index.js")],outdir:o,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
+ `);throw AggregateError(k,`Failed to bundle component library${j?`
425
+ ${j}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
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:Te.join(o,`${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 dt(){return`
428
428
  /* Theme selector for code blocks */
429
429
  .theme-selector {
430
430
  margin: 1rem 0;
@@ -474,13 +474,13 @@ ${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await
474
474
 
475
475
  body.dark-mode a {
476
476
  color: #58a6ff;
477
- }`}function wt(t){return`
477
+ }`}function pt(t){return`
478
478
  <div class="theme-selector">
479
479
  Theme:
480
480
  <select id="themeSelector" onchange="changeTheme()">
481
481
  ${t}
482
482
  </select>
483
- </div>`}function St(){return`
483
+ </div>`}function ut(){return`
484
484
  function changeTheme() {
485
485
  const theme = document.getElementById('themeSelector').value;
486
486
 
@@ -496,27 +496,27 @@ else {
496
496
  }
497
497
 
498
498
  // Initialize theme on page load
499
- document.addEventListener('DOMContentLoaded', changeTheme);`}function kt(t){if(Object.keys(t).length===0)return"";return`
499
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function mt(t){if(Object.keys(t).length===0)return"";return`
500
500
  <div class="frontmatter">
501
501
  <h3>Frontmatter</h3>
502
- ${Object.entries(t).map(([s,i])=>`
502
+ ${Object.entries(t).map(([r,o])=>`
503
503
  <div class="frontmatter-item">
504
- <span class="frontmatter-label">${s}:</span>
505
- <span>${Array.isArray(i)?i.join(", "):String(i)}</span>
504
+ <span class="frontmatter-label">${r}:</span>
505
+ <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
506
506
  </div>`).join("")}
507
- </div>`}import sn from"net";async function Dr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Mr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function _r(t){if(!await Dr(t))return!1;return await Mr(t)}async function Xe(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await _r(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Lr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function jr(){try{let t=await import("./chunk-kad2cp0z.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function rt(t,s={}){let i={...Lr,...s},d=await jr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await d.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
507
+ </div>`}import nn from"net";async function Pr(t){return new Promise((r)=>{let o=nn.createServer();o.once("error",()=>r(!1)),o.once("listening",()=>{o.close(()=>r(!0))}),o.listen(t,"0.0.0.0")})}async function Or(t){return new Promise((r)=>{let o=nn.createServer();o.once("error",()=>r(!1)),o.once("listening",()=>{o.close(()=>r(!0))}),o.listen(t,"::")})}async function Ar(t){if(!await Pr(t))return!1;return await Or(t)}async function qe(t,r=20){t=Number(t);for(let o=0;o<r;o++){let d=t+o;if(await Ar(d))return d}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-k79x96ra.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,r={}){let o={...Dr,...r},d=await Mr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let a=await d.openDevWindow(t,{title:o.title,width:o.width,height:o.height,darkMode:o.darkMode,hotReload:o.hotReload,titlebarHidden:o.titlebarHidden,nativeSidebar:o.nativeSidebar,sidebarWidth:o.sidebarWidth,sidebarConfig:o.sidebarConfig});if(a&&o.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 gt(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 u=`
508
508
  ${l}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
- `,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let c=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function 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 Hr(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 Ur(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ge(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),jt();let d="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(d+=c,d.endsWith("\r")||d.endsWith(`
512
- `)){let l=d.trim().toLowerCase();d="",Wr(l,t,s,i)}})}function Wr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Ur(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Hr(s);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else jt();break;default:break}}async function zt(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=ot.resolve(t);if(!Ht.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await be(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],B=[...new Set([...x,...C])].map((_)=>`<option value="${_}"${_===v?" selected":""}>${_}</option>`).join(`
510
+ `,y=Function(u)();if(y)return y}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let o=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(o)try{return JSON.parse(o[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let a=d[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 Xe(t,r,o){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),jt();let d="";process.stdin.on("data",(a)=>{if(a==="\x03"){if(o?.onQuit)o.onQuit();r(),process.exit(0)}if(d+=a,d.endsWith("\r")||d.endsWith(`
512
+ `)){let l=d.trim().toLowerCase();d="",jr(l,t,r,o)}})}function jr(t,r,o,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Ir(r);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Lr(r);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),o(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else jt();break;default:break}}async function Bt(t,r={}){let o=r.port||3000,d=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,u=async()=>{try{let{content:w,data:S}=await Ce(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">
516
516
  <head>
517
517
  <meta charset="UTF-8">
518
518
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
519
- <title>${qr(S.title||ot.basename(c))}</title>
519
+ <title>${Br(S.title||et.basename(a))}</title>
520
520
  <!-- Syntax highlighting styles -->
521
521
  <style id="syntax-theme">
522
522
  :root {
@@ -658,38 +658,38 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
658
658
  min-width: 100px;
659
659
  color: #555;
660
660
  }
661
- ${vt()}
661
+ ${dt()}
662
662
  </style>
663
663
  </head>
664
664
  <body>
665
- ${kt(S)}
666
- ${wt(B)}
665
+ ${mt(S)}
666
+ ${pt(j)}
667
667
 
668
668
  ${w}
669
669
 
670
670
  <script>
671
- ${St()}
671
+ ${ut()}
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 m())return!1;let h=i;try{if(h=await Xe(i),h!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${h} 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:${h}/${e.reset}...`);let g=Vr({port:h,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 u())return!1;let y=o;try{if(y=await qe(o),y!==o)console.log(`${e.yellow}Port ${o} 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 g=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
- ${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
679
- ${e.yellow}Routes:${e.reset}`);let y=ot.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
680
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(g.url.toString(),()=>{if(d)Ht.watch(ot.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await rt(h,{title:ot.basename(c,".md")});if(d){let w=ot.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Ht.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function qr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Xr}=globalThis.Bun;import Be from"fs";import ve from"path";class an{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let d=0;d<i;d++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let p=JSON.parse(m);if(p.type==="console"&&Array.isArray(p.args)){let h=p.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${y}[browser]${p.level!=="log"?` ${p.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let d of this.clients)try{if(d.readyState===1)d.send(s),i++}catch{this.clients.delete(d)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Kr(t,s={}){let{showOverlay:i=!0,reconnectInterval:d=1000,maxReconnectAttempts:c=10}=s;return`
678
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
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`),Xe(g.url.toString(),()=>{if(d)Ht.watch(et.dirname(a),{recursive:!0}).close();g.stop()}),r.native)await Ze(y,{title:et.basename(a,".md")});if(d){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 u()});process.on("SIGINT",()=>{S.close(),g.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,o=20;for(let d=0;d<o;d++)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 u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let p=JSON.parse(u);if(p.type==="console"&&Array.isArray(p.args)){let y=p.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${b}[browser]${p.level!=="log"?` ${p.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 ${o} 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),o=0;for(let d of this.clients)try{if(d.readyState===1)d.send(r),o++}catch{this.clients.delete(d)}if(this.options.verbose&&o>0)console.log(`[HMR] Broadcast ${t.type} to ${o} 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:o=!0,reconnectInterval:d=1000,maxReconnectAttempts:a=10}=r;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
684
684
  var wsUrl = 'ws://' + window.location.hostname + ':${t}';
685
685
  var reconnectAttempts = 0;
686
- var maxAttempts = ${c};
686
+ var maxAttempts = ${a};
687
687
  var reconnectInterval = ${d};
688
688
  var socket = null;
689
689
  var overlay = null;
690
690
  var wasConnected = false; // Track if we ever connected successfully
691
691
 
692
- ${i?`
692
+ ${o?`
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 Ve(t,s,i={}){let d=Kr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function lt(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await br(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await xn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ae(()=>Bun.file(m).text(),"",(x)=>{throw new jn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new jn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=J.time("script-extraction",()=>{let x=h,C=oe(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",_=[];for(let E of k){let L=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=E.match(/<script\b([^>]*)>/i),K=F?F[1]:"";if(/\bserver\b/i.test(K))B=L;else _.push(E)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:I,allScripts:_}}),S={__filename:m,__dirname:Pt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ae(()=>u(g,S,m),void 0,(x)=>{let C=new q(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(O.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await J.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-hrdnz5q9.js"),C=x(w.join(`
880
- `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
879
+ `}function Ne(t,r,o={}){let d=Fr(r,o),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+d+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}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((d)=>r.endsWith(d))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var tt=null;function $t(t){if(!tt)tt=new rn(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Ct from"path";var nt={name:"bun-plugin-stx",async setup(t){let o={...await i(),...t.config?.stx},d=new Set,a=o.webComponents?.enabled?`./${Ct.relative(Ct.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let u=await qr(o,d);if(l.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let p=new Set;if(o.cache&&o.cachePath){let x=await Xn(u,o);if(x){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:x,loader:"html"}}}let y=await be(()=>Bun.file(u).text(),"",(x)=>{throw new ur(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new ur(`stx file is empty: ${u}`,u);let{scriptContent:g,templateContent:b,allScripts:w}=te.time("script-extraction",()=>{let x=y,T=ie(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]||"",B=E.match(/<script\b([^>]*)>/i),q=B?B[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:u,__dirname:Ct.dirname(u),__stx:{webComponentsPath:a,builtComponents:l}};await be(()=>f(g,S,u),void 0,(x)=>{let T=new ne(`Script execution failed in ${u}: ${x.message}`,u,void 0,void 0,g.substring(0,100));if(D.log(T,{filePath:u,scriptContent:g}),o.debug)throw T});let v=await te.timeAsync("directive-processing",async()=>await s(b,S,u,o,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-p22w6mwr.js"),T=x(w.join(`
880
+ `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
881
881
  `+v.slice(k);else v+=`
882
- ${C}`}if(v=await Q(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await Sn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new q(`Plugin processing failed: ${String(p)}`,m);if(O.log(h,{filePath:m,buildConfig:t.config}),Wt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
882
+ ${T}`}if(v=await me(v),p.forEach((x)=>d.add(x)),o.cache&&o.cachePath){if(await Jn(u,v,p,o),o.debug)console.log(`Cached template ${u} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let y=p instanceof Error?p:new ne(`Plugin processing failed: ${String(p)}`,u);if(D.log(y,{filePath:u,buildConfig:t.config}),hn.logDetailedError(y,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:o.debug||H()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -902,16 +902,16 @@ ${C}`}if(v=await Q(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await Sn
902
902
 
903
903
  <div class="error-details">
904
904
  <h3>Error Details</h3>
905
- <p><strong>File:</strong> <span class="file-path">${b(m)}</span></p>
906
- <p><strong>Error:</strong> ${b(h.message)}</p>
907
- ${y?`<p><strong>Line:</strong> ${b(String(y))}</p>`:""}
908
- ${w?`<p><strong>Context:</strong> ${b(String(w))}</p>`:""}
905
+ <p><strong>File:</strong> <span class="file-path">${m(u)}</span></p>
906
+ <p><strong>Error:</strong> ${m(y.message)}</p>
907
+ ${b?`<p><strong>Line:</strong> ${m(String(b))}</p>`:""}
908
+ ${w?`<p><strong>Context:</strong> ${m(String(w))}</p>`:""}
909
909
  </div>
910
910
 
911
- ${h.stack?`
911
+ ${y.stack?`
912
912
  <div class="error-details">
913
913
  <h3>Stack Trace</h3>
914
- <pre class="error-code">${b(h.stack)}</pre>
914
+ <pre class="error-code">${m(y.stack)}</pre>
915
915
  </div>`:""}
916
916
 
917
917
  <div class="help-section">
@@ -920,7 +920,7 @@ ${C}`}if(v=await Q(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await Sn
920
920
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
921
921
  <li>Verify that all variables used in the template are properly defined</li>
922
922
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
923
- <li>Run <code>stx debug ${b(Pt.basename(m))}</code> for detailed analysis</li>
923
+ <li>Run <code>stx debug ${m(Ct.basename(u))}</code> for detailed analysis</li>
924
924
  <li>Enable debug mode in your stx config for more detailed error messages</li>
925
925
  </ul>
926
926
  </div>
@@ -939,12 +939,12 @@ ${C}`}if(v=await Q(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await Sn
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 qn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=ve.resolve(t);if(!Be.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Be.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(me)=>({path:me.path,external:!0}))}},F=await Bun.build({entrypoints:[p],outdir:h,plugins:[L,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let K=F.outputs.find((Te)=>Te.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=ve.dirname(p);await Bt(S);let R=i;try{if(R=await Xe(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||R+1;l=Et({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,C;try{let{loadStxConfig:L}=await import("./chunk-ek5vrw4r.js"),F=await L();if(C=s.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Z}=await import("./chunk-b2teprjf.js"),Te=F.broadcasting;await K(Te);let me=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${me}/ws${e.reset}`);let Pe=ve.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Z(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-jtk2p5p0.js"),_=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Xr({port:R,async fetch(L){return Kt(L,await(async()=>{let F=new URL(L.url);if([h,ve.dirname(p),ve.join(process.cwd(),"public")].some((ne)=>B(ve.join(ne,F.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(L);if(ne.status!==404)return ne}catch{}if(v[F.pathname])try{return await v[F.pathname](L)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await _(L);if(K)return K;if(F.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Ve(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Z=ve.join(h,F.pathname);if(Be.existsSync(Z)&&Be.statSync(Z).isFile()){let ne=Bun.file(Z),U=ve.extname(Z).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let Te=ve.dirname(p),me=ve.join(Te,F.pathname);if(Be.existsSync(me)&&Be.statSync(me).isFile()){let ne=Bun.file(me),U=ve.extname(me).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let Pe=ve.join(process.cwd(),"public",F.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),U=ve.extname(Pe).toLowerCase(),H="application/octet-stream";if(U===".ts"||U===".tsx"){let Fe=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
943
- ${L.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
942
+ </html>`,loader:"html"}}})}};async function Sr(t,r={}){let o=r.port||3000,d=r.watch!==!1,a=r.hotReload!==!1&&d,l=null,u=r.hmrPort||o+1,p=fe.resolve(t);if(!Le.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return Bt(p,r);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Le.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let _={name:"public-assets",setup(ve){ve.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ce)=>({path:ce.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let q=B.outputs.find((ve)=>ve.path.endsWith(".html"));if(!q)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=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(p);await en(S);let C=o;try{if(C=await qe(o),C!==o)console.log(`${e.yellow}Port ${o} 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=$t({wsPort:_,verbose:!1}),u=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-1q6yvbdx.js"),B=await _();if(T=r.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let q=Object.keys(v).length;if(q>0)console.log(`${e.blue}Loaded ${e.bright}${q} API route${q>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:q,loadChannels:J}=await import("./chunk-j0v970k3.js"),ve=B.broadcasting;await q(ve);let ce=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ce}/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-8ttg2d3m.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:${u}${e.reset}`);let L=zr({port:C,async fetch(_){return xn(_,await(async()=>{let B=new URL(_.url);if([y,fe.dirname(p),fe.join(process.cwd(),"public")].some((Z)=>j(fe.join(Z,B.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[B.pathname])try{return await v[B.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(B.pathname==="/")return(async()=>{let N=await h(g||"");if(a)N=Ne(N,u);if(r.native)if(N.includes("<head>"))N=N.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(N.includes("<html"))N=N.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 N="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+N;if(r.titlebarHidden)if(N.includes("<head>"))N=N.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(N.includes("<html"))N=N.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 N=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${N}`;return N})().then((N)=>new Response(N,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let J=fe.join(y,B.pathname);if(Le.existsSync(J)&&Le.statSync(J).isFile()){let Z=Bun.file(J),N=fe.extname(J).toLowerCase(),I="text/plain";if(N===".ts"||N===".tsx"){let Ie=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Be=await Z.text(),Ye=Ie.transformSync(Be);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){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 ve=fe.dirname(p),ce=fe.join(ve,B.pathname);if(Le.existsSync(ce)&&Le.statSync(ce).isFile()){let Z=Bun.file(ce),N=fe.extname(ce).toLowerCase(),I="text/plain";if(N===".ts"||N===".tsx"){let Ie=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Be=await Z.text(),Ye=Ie.transformSync(Be);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){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",B.pathname);if(Le.existsSync(Re)&&Le.statSync(Re).isFile()){let Z=Bun.file(Re),N=fe.extname(Re).toLowerCase(),I="application/octet-stream";if(N===".ts"||N===".tsx"){let Ie=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Be=await Z.text(),Ye=Ie.transformSync(Be);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){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
+ ${_.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
- ${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
946
- ${e.yellow}Routes:${e.reset}`);let E=ve.relative(process.cwd(),p);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`),Ge(I.url.toString(),()=>{if(d)Be.watch(ve.dirname(p),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(p).text(),F=Tt(L);await rt(R,{title:ve.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(d){let L=ve.dirname(p);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let F=Be.watch(L,{recursive:!0},async(K,Z)=>{if(!Z||Rt(Z))return;if(Ct(Z)){console.log(`${e.yellow}File ${e.bright}${Z}${e.yellow} changed, rebuilding...${e.reset}`),Ae.clear(),ie();let Te=await y();if(await _n(S),c&&l)if(Te)l.reload(Z);else l.error("Build failed - check console for details")}else if($t(Z)){if(console.log(`${e.cyan}CSS ${e.bright}${Z}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Z)}});process.on("SIGINT",()=>{if(F.close(),l)lt();I.stop(),process.exit(0)})}return!0}var{serve:Jr}=globalThis.Bun;import Je from"fs";import Ee from"path";var cn=`
945
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
946
+ ${e.yellow}Routes:${e.reset}`);let E=fe.relative(process.cwd(),p);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`),Xe(L.url.toString(),()=>{if(d)Le.watch(fe.dirname(p),{recursive:!0}).close();L.stop()}),r.native){let _=await Bun.file(p).text(),B=gt(_);await Ze(C,{title:fe.basename(p,".stx"),titlebarHidden:r.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(d){let _=fe.dirname(p);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let B=Le.watch(_,{recursive:!0},async(q,J)=>{if(!J||Tt(J))return;if(yt(J)){console.log(`${e.yellow}File ${e.bright}${J}${e.yellow} changed, rebuilding...${e.reset}`),Ue.clear(),de();let ve=await b();if(await Wn(S),a&&l)if(ve)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(B.close(),l)st();L.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Ge from"fs";import $e from"path";var on=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,14 +1255,14 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function dn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Ee.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Ee.sep)}async function Gn(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Ee.resolve(v);if(!Je.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Je.mkdirSync(c,{recursive:!0});let l=dn(t.map((v)=>Ee.dirname(Ee.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Ee.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await be(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),_=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,I=_?.defaultTheme||"github-dark",E=["github-dark"],L=_?.additionalThemes||[],K=[...new Set([...E,...L])].map((Pe)=>`<option value="${Pe}"${Pe===I?" selected":""}>${Pe}</option>`).join(`
1259
- `),Z=`
1258
+ `;function an(t){if(t.length===0)return"";if(t.length===1)return t[0];let r=t.map((d)=>d.split($e.sep)),o=[];for(let d=0;d<r[0].length;d++){let a=r[0][d];if(r.every((l)=>l[d]===a))o.push(a);else break}return o.join($e.sep)}async function kr(t,r={}){let o=r.port||3000,d=r.watch!==!1;for(let v of t){let x=$e.resolve(v);if(!Ge.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");Ge.mkdirSync(a,{recursive:!0});let l=an(t.map((v)=>$e.dirname($e.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},p=[],y=async()=>{try{for(let v of t){let x=$e.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:j}=await Ce(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
+ `),J=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
1262
1262
  <head>
1263
1263
  <meta charset="UTF-8">
1264
1264
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
- <title>${ln(B.title||Ee.basename(x))}</title>
1265
+ <title>${sn(j.title||$e.basename(x))}</title>
1266
1266
  <!-- Syntax highlighting styles -->
1267
1267
  <style id="syntax-theme">
1268
1268
  :root {
@@ -1404,40 +1404,40 @@ else {
1404
1404
  min-width: 100px;
1405
1405
  color: #555;
1406
1406
  }
1407
- ${vt()}
1407
+ ${dt()}
1408
1408
  </style>
1409
1409
  </head>
1410
1410
  <body>
1411
- ${kt(B)}
1412
- ${wt(K)}
1411
+ ${mt(j)}
1412
+ ${pt(q)}
1413
1413
 
1414
1414
  ${k}
1415
1415
 
1416
1416
  <script>
1417
- ${St()}
1417
+ ${ut()}
1418
1418
  </script>
1419
1419
  </body>
1420
1420
  </html>
1421
- `,me=`/${Ee.relative(l,x).replace(/\.md$/,"")}`;if(me.endsWith("/index"))me=me.slice(0,-6)||"/";m[me||"/"]={filePath:x,content:Z,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(L)=>({path:L.path,external:!0}))}},B;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,it],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,fe(E.logs,x));continue}let L=E.outputs.find((F)=>F.path.endsWith(".html"));if(!L){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(L.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
- ${fe(E,x)}`);continue}let I=`/${Ee.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:E,params:L}=Ir(I,{page:!0});p.push({pattern:E,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:B,fileType:"stx"}}else m[I||"/"]={filePath:x,content:B,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,fe(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Xe(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=Jr({port:y,async fetch(v){let x=new URL(v.url),C=Ee.join(process.cwd(),"public",x.pathname);if(Je.existsSync(C)&&Je.statSync(C).isFile()){let _=Bun.file(C),I=Ee.extname(C).toLowerCase(),E="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),F=await _.text(),K=L.transformSync(F);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let _ of p){let I=x.pathname.match(_.pattern);if(I){let E=m[_.routeTemplate];if(E){let L={};for(let Z=0;Z<_.paramNames.length;Z++)L[_.paramNames[Z]]=decodeURIComponent(I[Z+1]);let F=E.content,K=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${K}
1423
- </head>`);else F=K+F;k={...E,content:F}}break}}if(k)return f(k.content).then((_)=>{if(_.includes("</head>"))_=_.replace("</head>",`${cn}
1424
- </head>`);return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let B=Ee.join(c,x.pathname);if(Je.existsSync(B)&&Je.statSync(B).isFile()){let _=Bun.file(B),I=Ee.extname(B).toLowerCase(),E="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),F=await _.text(),K=L.transformSync(F);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let _=ce(v);return f(m["/"].content).then((I)=>{if(_){let E=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),F=L?L[1]:"",K=`<!DOCTYPE html><html><head><title>${ln(F)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":He,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1421
+ `,ce=`/${$e.relative(l,x).replace(/\.md$/,"")}`;if(ce.endsWith("/index"))ce=ce.slice(0,-6)||"/";u[ce||"/"]={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}:`,_e(E.logs,x));continue}let _=E.outputs.find((B)=>B.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
+ ${_e(E,x)}`);continue}let L=`/${$e.relative(l,x).replace(/\.stx$/,"")}`;if(L.endsWith("/index"))L=L.slice(0,-6)||"/";if(L.includes("[")){let{regex:E,params:_}=Zr(L,{page:!0});p.push({pattern:E,paramNames:_,filePath:x,routeTemplate:L,fileType:"stx"}),u[L]={filePath:x,content:j,fileType:"stx"}}else u[L||"/"]={filePath:x,content:j,fileType:"stx"}}}if(Object.keys(u).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}`,_e(v)),!1}};if(!await y())return!1;let b=o;try{if(b=await qe(o),b!==o)console.log(`${e.yellow}Port ${o} 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=$e.join(process.cwd(),"public",x.pathname);if(Ge.existsSync(T)&&Ge.statSync(T).isFile()){let M=Bun.file(T),L=$e.extname(T).toLowerCase(),E="application/octet-stream";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),B=await M.text(),q=_.transformSync(B);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=u[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=u[`${x.pathname}/`];if(!k)for(let M of p){let L=x.pathname.match(M.pattern);if(L){let E=u[M.routeTemplate];if(E){let _={};for(let J=0;J<M.paramNames.length;J++)_[M.paramNames[J]]=decodeURIComponent(L[J+1]);let B=E.content,q=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${q}
1423
+ </head>`);else B=q+B;k={...E,content:B}}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=$e.join(a,x.pathname);if(Ge.existsSync(j)&&Ge.statSync(j).isFile()){let M=Bun.file(j),L=$e.extname(j).toLowerCase(),E="text/plain";if(L===".ts"||L===".tsx"){let _=new Bun.Transpiler({loader:L===".tsx"?"tsx":"ts"}),B=await M.text(),q=_.transformSync(B);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!=="/"&&u["/"]){let M=we(v);return h(u["/"].content).then((L)=>{if(M){let E=L.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=L.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=_?_[1]:"",q=`<!DOCTYPE html><html><head><title>${sn(B)}</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":lt,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
- ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
1428
- ${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",B=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${B}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(w.url.toString(),()=>{if(d)Je.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Je.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),Ae.clear(),ie(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Yr}=globalThis.Bun;import he from"fs";import te from"path";async function pn(t){try{return Ft(await Bun.file(t).text())}catch{return}}function Nt(t){let s=Bun.file(t),i=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function Kn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-ek5vrw4r.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-jtk2p5p0.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!he.existsSync(C)&&!g._layerPageDirs?.some((A)=>he.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=j(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],_=[];for(let{dir:A,prefix:z}of B)if(he.existsSync(A)){let N=j(te.dirname(A),{pagesDir:te.basename(A)});for(let W of N){let xe=z==="/"?W.pattern:`${z}${W.pattern==="/"?"":W.pattern}`;_.push({route:{...W,pattern:xe},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let I=new Map,E=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await Oo(p,s.stxOptions?.shell),L){if(E=await Gr(L,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}ft(),await mt(p);let F=gt();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let K={},Z=null;try{let{loadStxConfig:A}=await import("./chunk-ek5vrw4r.js"),z=await A(p);if(z?.apiRouter)Z=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){K=z.apiRoutes;let N=Object.keys(K).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:W}=await import("./chunk-b2teprjf.js"),xe=z.broadcasting;await N(xe);let ze=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(he.existsSync(qe))try{let ee=await W(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let Te=a(p,"output");he.mkdirSync(Te,{recursive:!0});let me=new Map,Pe=new Set,ne=async(A)=>{let z=Or(C,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:Te,plugins:[it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let W=N.outputs.find((xe)=>xe.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:W,defaultConfig:xe,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-ek5vrw4r.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:V,templateCache:X}=await import("./chunk-k46gqnmk.js"),we=await ze(p),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(p,re)},M={...xe,...we,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Ke(M.partialsDir),M.componentsDir=Ke(M.componentsDir),M.layoutsDir=Ke(M.layoutsDir),M.storesDir=Ke(M.storesDir||"stores"),M.cachePath=Ke(M.cachePath)??a(p,"cache");let ge=!z&&!s.profile,se=M.cache!==!1;if(se&&ge){let re=X.get(A.filePath);if(re)try{if((await he.promises.stat(A.filePath)).mtime.getTime()<=re.mtime){let je=!0;for(let Ce of re.dependencies){if(!he.existsSync(Ce)){je=!1;break}if((await he.promises.stat(Ce)).mtime.getTime()>re.mtime){je=!1;break}}if(je){let Ce=re.output;if(E)Ce=ke(Ce,{preserveHead:!0});let ct=U.get(A.filePath);return{route:A,content:Ce,status:ct?.status??await pn(A.filePath),headers:ct?.headers}}}}catch{}let Le=await ee(A.filePath,M);if(Le){let Ie=Le;if(E)Ie=ke(Ie,{preserveHead:!0});let je=U.get(A.filePath);return{route:A,content:Ie,status:je?.status??await pn(A.filePath),headers:je?.headers}}}let ue=se?await V(A.filePath):await Bun.file(A.filePath).text(),$e=Ft(ue),{classifyAllScripts:G}=await import("./chunk-ek5vrw4r.js"),_e=G(ue),Ne=_e.server.map((re)=>re.content),de=ue;for(let re of _e.server)de=de.replace(re.fullTag,"");let pe={__filename:A.filePath,__dirname:te.dirname(A.filePath),__stx_options:M,params:z??{},__stx_runtime_head:{}};for(let re of Ne)try{await W(re,pe,A.filePath)}catch(Le){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Le?.message||Le)}let We=new Set,Oe;if(s.profile){let re=performance.now();Oe=await N(de,pe,A.filePath,M,We);let Le=performance.now()-re,Ie=te.relative(p,A.filePath)||A.filePath;console.log(`[stx:profile] ${Ie} \u2192 ${Le.toFixed(2)}ms`)}else Oe=await N(de,pe,A.filePath,M,We);if(!E)Oe=await qe(Oe,{router:M.router});{let{interpolateScriptExpressions:re}=await import("./chunk-hrdnz5q9.js");Oe=Oe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Le,Ie,je)=>{if(!/function\s+__stx_setup_/.test(je))return Le;return`<script${Ie}>${re(je,pe)}</script>`})}if(E)Oe=ke(Oe,{preserveHead:!0});if(se&&ge)await Y(A.filePath,Oe,We,M);let{extractStreamBoundaries:Nn}=await import("./chunk-x901zq4q.js"),nt=Nn(pe),at=pe.__streamTemplates;if(at&&typeof at==="object"&&Object.keys(at).length>0){let re=pe.streamBoundaries||{},Le={...M,autoShell:!1},Ie=Object.keys(at).map((Ce)=>({id:Ce,render:async()=>{let ct=typeof re[Ce]==="function"?await re[Ce]():void 0;return N(at[Ce],{...pe,$boundary:ct},A.filePath,Le,new Set)}})),je=new Set(Ie.map((Ce)=>Ce.id));nt=[...(nt||[]).filter((Ce)=>!je.has(Ce.id)),...Ie]}if(nt&&nt.length>0)Pe.add(A.pattern);else nt=void 0;let qt=Ze(pe),Xt=Qe(pe);if(ge)U.set(A.filePath,{status:qt,headers:Xt});return{route:A,content:Oe,status:qt??$e,headers:Xt,boundaries:nt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Fe=8,Ue=async()=>{me.clear(),I.clear();for(let A=0;A<k.length;A+=Fe){let z=k.slice(A,A+Fe),N=await Promise.all(z.map((W)=>H(W)));for(let W of N)if(W)me.set(W.route.pattern,W)}for(let A=0;A<_.length;A+=Fe){let z=_.slice(A,A+Fe),N=await Promise.all(z.map(({route:W})=>H(W)));for(let W of N)if(W)I.set(W.route.pattern,W)}return me.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Bt(p);let et=i;try{if(et=await Xe(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||et+1;l=Et({wsPort:A,verbose:!1}),m=l.start(A)}let At=(A,z)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${W}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Yr({port:et,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",W=te.join(p,N,z.pathname),xe=te.join(p,z.pathname),ze=te.join(Te,z.pathname);if([W,xe,ze].some((M)=>w(M,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Y]=await Promise.all([he.promises.stat(W).catch(()=>null),he.promises.stat(xe).catch(()=>null),he.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(W,p,S))return Nt(W);if(ee?.isFile()&&!w(xe,p,S))return Nt(xe);if(Y?.isFile()&&!w(ze,p,S))return Nt(ze);if(z.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(z.pathname.slice(16));if(M)try{let ge=`<${M} />`,se={...buildConfig,autoShell:!1},ue=await processDirectives(ge,{},te.join(p,"components",`${M}.stx`),se,new Set);return new Response(ue,{headers:{"Content-Type":"text/html"}})}catch(ge){return new Response(`<div class="stx-async-error">${ge.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-ns4pc13z.js"),ge=await M(A,{publicDir:te.join(p,N),cacheDir:a(p,"cache","img")});if(ge)return ge}if(Z)try{let M=await Z.handleRequest(A);if(M.status!==404)return M}catch{}if(K[z.pathname])try{return await K[z.pathname](A)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(A);if(V)return V;let X=Vn(z.pathname,k);if(X){let M=me.get(X.route.pattern),ge=Pe.has(X.route.pattern);if(X.route.isDynamic&&Object.keys(X.params).length>0||ge){let se=await H(X.route,X.params);if(se)M=se}if(M){let se=M.status??200,ue=M.headers??{},$e=(X.route.filePath?Ye(await Bun.file(X.route.filePath).text().catch(()=>"")):null)??{};if($e.validate){if(!await $e.validate({params:X.params})){let Ne=await ne(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if($e.middleware){let _e=ht(z.pathname,X.params,$e,z.search),Ne=yt(_e,null,A,{isServer:!0}),de=await bt($e.middleware,Ne);if(de.redirect){let pe=de.redirect.path,We=de.redirect.options.redirectCode||302,Oe=new Headers(de.responseHeaders);return Oe.set("Location",pe),new Response(null,{status:We,headers:Oe})}if(de.abort){let{statusCode:pe,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${pe}</title></head><body><h1>Error ${pe}</h1><p>${We}</p></body></html>`,{status:pe,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let pe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${pe}</head>`)}}let G=M.content;if(E&&No(A)){let _e=De(G),Ne=ye(G),de=G.match(/<title[^>]*>([\s\S]*?)<\/title>/i),pe=de?Io(de[1].trim()):"";if(Object.keys(X.params).length>0)G=At(G,X.params);G=await f(G,p);let We=g?.router?.container||"main";return G=le(G,We),new Response(G,{status:se,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":_e.layout,"X-STX-Layout-Group":_e.group,"X-STX-Runtime":Ne?"true":"false",...pe&&{"X-STX-Title":encodeURIComponent(pe)},[Li]:Fs(),...T(),"Cache-Control":He}})}if(E)G=Zn(E,G);if(Object.keys(X.params).length>0)G=At(G,X.params);if(G=await f(G,p),c)G=Ve(G,m);if(s.native)if(G.includes("<head>"))G=G.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 G="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+G;if(s.titlebarHidden)if(G.includes("<head>"))G=G.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 G=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${G}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:_e,streamToResponse:Ne}=await import("./chunk-x901zq4q.js");return Ne(_e(G,M.boundaries,{timeoutMs:30000}),{status:se,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(G,{status:se,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ue}})}}if(_.length>0){let M=_.map((se)=>se.route),ge=Vn(z.pathname,M);if(ge){let se=I.get(ge.route.pattern);if(se){let ue=se.content;if(E)ue=Zn(E,ue);if(Object.keys(ge.params).length>0)ue=At(ue,ge.params);if(ue=await f(ue,p),c)ue=Ve(ue,m);return new Response(ue,{status:se.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:se}of B)if(se!=="/"&&z.pathname.startsWith(se)){let ue=I.get(se)||I.get(se+"/");if(ue){let $e=ue.content;if(E)$e=Zn(E,$e);if($e=await f($e,p),c)$e=Ve($e,m);return new Response($e,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(pt(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let we=me.get("/");if(we){let M=we.content;if(M=await f(M,p),c)M=Ve(M,m);if(s.native)if(M.includes("<head>"))M=M.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ke=await ne(404);if(Ke){let M=Ke;if(M=await f(M,p),c)M=Ve(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await ne(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
1430
- ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1427
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1428
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),C=Object.entries(u).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:$e.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:$e.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`),Xe(w.url.toString(),()=>{if(d)Ge.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ge.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}`),Ue.clear(),de(),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 pe 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),o=Q.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":d[o]||"application/octet-stream",...l}})}async function _r(t=".",r={}){let o=r.port||3000,d=r.watch!==!1,a=r.hotReload!==!1&&d,l=null,u=r.hmrPort||o+1,p=Q.resolve(t),{loadStxConfig:y}=await import("./chunk-1q6yvbdx.js"),g=await y(p),{createServerApi:b,isServerApiSource:w}=await import("./chunk-8ttg2d3m.js"),S=r.stxOptions?.serverApi??g.serverApi,C=await b(p,S),v=g.root&&g.root!=="."?Q.join(p,g.root):p,x=r.pagesDir||g.pagesDir||"pages",T=Q.join(v,x);if(!pe.existsSync(T)&&!g._layerPageDirs?.some((P)=>pe.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=V(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let j=g?._pluginPageDirs||[],M=[];for(let{dir:P,prefix:F}of j)if(pe.existsSync(P)){let z=V(Q.dirname(P),{pagesDir:Q.basename(P)});for(let U of z){let ue=F==="/"?U.pattern:`${F}${U.pattern==="/"?"":U.pattern}`;M.push({route:{...U,pattern:ue},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let L=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ei(p,r.stxOptions?.shell),_){if(E=await js(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${Q.relative(p,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}vt(),await xt(p);let B=wt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let q={},J=null;try{let{loadStxConfig:P}=await import("./chunk-1q6yvbdx.js"),F=await P(p);if(F?.apiRouter)J=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){q=F.apiRoutes;let z=Object.keys(q).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:U}=await import("./chunk-j0v970k3.js"),ue=F.broadcasting;await z(ue);let je=ue.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${je}/ws${e.reset}`);let We=Q.join(process.cwd(),"channels.ts");if(pe.existsSync(We))try{let Y=await U(We);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(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let ve=c(p,"output");pe.mkdirSync(ve,{recursive:!0});let ce=new Map,Re=new Set,Z=async(P)=>{let F=Qr(T,P);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:ve,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!z.success)return null;let U=z.outputs.find((ue)=>ue.path.endsWith(".html"));if(!U)return null;return await Bun.file(U.path).text()}catch{return null}},N=new Map,I=async(P,F)=>{try{let{processDirectives:z,extractVariables:U,defaultConfig:ue,loadStxConfig:je,injectRouterScript:We}=await import("./chunk-1q6yvbdx.js"),{checkCache:Y,cacheTemplate:G,readFileCached:W,templateCache:K}=await import("./chunk-31714f76.js"),he=await je(p),Ve=(ee)=>{if(!ee)return ee;if(Q.isAbsolute(ee))return ee;return Q.resolve(p,ee)},A={...ue,...he,...r.stxOptions,autoShell:!0};if(r.debugDirectives)A.debug=!0;A.partialsDir=Ve(A.partialsDir),A.componentsDir=Ve(A.componentsDir),A.layoutsDir=Ve(A.layoutsDir),A.storesDir=Ve(A.storesDir||"stores"),A.cachePath=Ve(A.cachePath)??c(p,"cache");let le=!F&&!r.profile,re=A.cache!==!1;if(re&&le){let ee=K.get(P.filePath);if(ee)try{if((await pe.promises.stat(P.filePath)).mtime.getTime()<=ee.mtime){let Me=!0;for(let ke of ee.dependencies){if(!pe.existsSync(ke)){Me=!1;break}if((await pe.promises.stat(ke)).mtime.getTime()>ee.mtime){Me=!1;break}}if(Me){let ke=ee.output;if(E)ke=Fe(ke,{preserveHead:!0});let ot=N.get(P.filePath);return{route:P,content:ke,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ae=await Y(P.filePath,A);if(Ae){let De=Ae;if(E)De=Fe(De,{preserveHead:!0});let Me=N.get(P.filePath);return{route:P,content:De,status:Me?.status??await ln(P.filePath),headers:Me?.headers}}}let ae=re?await W(P.filePath):await Bun.file(P.filePath).text(),Se=cn(ae),{classifyAllScripts:X}=await import("./chunk-1q6yvbdx.js"),Oe=X(ae),He=Oe.server.map((ee)=>ee.content),oe=ae;for(let ee of Oe.server)oe=oe.replace(ee.fullTag,"");let se={__filename:P.filePath,__dirname:Q.dirname(P.filePath),__stx_options:A,params:F??{},__stx_runtime_head:{}};for(let ee of He)try{await U(ee,se,P.filePath)}catch(Ae){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ae?.message||Ae)}let ze=new Set,Ee;if(r.profile){let ee=performance.now();Ee=await z(oe,se,P.filePath,A,ze);let Ae=performance.now()-ee,De=Q.relative(p,P.filePath)||P.filePath;console.log(`[stx:profile] ${De} \u2192 ${Ae.toFixed(2)}ms`)}else Ee=await z(oe,se,P.filePath,A,ze);if(!E)Ee=await We(Ee,{router:A.router});{let{interpolateScriptExpressions:ee}=await import("./chunk-p22w6mwr.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,se)}</script>`})}if(E)Ee=Fe(Ee,{preserveHead:!0});if(re&&le)await G(P.filePath,Ee,ze,A);let{extractStreamBoundaries:Hn}=await import("./chunk-apgb7r22.js"),Qe=Hn(se),rt=se.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ee=se.streamBoundaries||{},Ae={...A,autoShell:!1},De=Object.keys(rt).map((ke)=>({id:ke,render:async()=>{let ot=typeof ee[ke]==="function"?await ee[ke]():void 0;return z(rt[ke],{...se,$boundary:ot},P.filePath,Ae,new Set)}})),Me=new Set(De.map((ke)=>ke.id));Qe=[...(Qe||[]).filter((ke)=>!Me.has(ke.id)),...De]}if(Qe&&Qe.length>0)Re.add(P.pattern);else Qe=void 0;let Ut=Rt(se),Wt=At(se);if(le)N.set(P.filePath,{status:Ut,headers:Wt});return{route:P,content:Ee,status:Ut??Se,headers:Wt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Ie=8,Be=async()=>{ce.clear(),L.clear();for(let P=0;P<k.length;P+=Ie){let F=k.slice(P,P+Ie),z=await Promise.all(F.map((U)=>I(U)));for(let U of z)if(U)ce.set(U.route.pattern,U)}for(let P=0;P<M.length;P+=Ie){let F=M.slice(P,P+Ie),z=await Promise.all(F.map(({route:U})=>I(U)));for(let U of z)if(U)L.set(U.route.pattern,U)}return ce.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 en(p);let Je=o;try{if(Je=await qe(o),Je!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Je} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Je+1;l=$t({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,F)=>{let U=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${U}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${U}`);return U+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Ur({port:Je,async fetch(P){let F=new URL(P.url),z=g?.publicDir||"public",U=Q.join(p,z,F.pathname),ue=Q.join(p,F.pathname),je=Q.join(ve,F.pathname);if([U,ue,je].some((A)=>w(A,p,S)))return new Response("Not Found",{status:404});let[We,Y,G]=await Promise.all([pe.promises.stat(U).catch(()=>null),pe.promises.stat(ue).catch(()=>null),pe.promises.stat(je).catch(()=>null)]);if(We?.isFile()&&!w(U,p,S))return Ft(U);if(Y?.isFile()&&!w(ue,p,S))return Ft(ue);if(G?.isFile()&&!w(je,p,S))return Ft(je);if(F.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(F.pathname.slice(16));if(A)try{let le=`<${A} />`,re={...buildConfig,autoShell:!1},ae=await processDirectives(le,{},Q.join(p,"components",`${A}.stx`),re,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(le){return new Response(`<div class="stx-async-error">${le.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-2v4s7xtx.js"),le=await A(P,{publicDir:Q.join(p,z),cacheDir:c(p,"cache","img")});if(le)return le}if(J)try{let A=await J.handleRequest(P);if(A.status!==404)return A}catch{}if(q[F.pathname])try{return await q[F.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=Zn(F.pathname,k);if(K){let A=ce.get(K.route.pattern),le=Re.has(K.route.pattern);if(K.route.isDynamic&&Object.keys(K.params).length>0||le){let re=await I(K.route,K.params);if(re)A=re}if(A){let re=A.status??200,ae=A.headers??{},Se=(K.route.filePath?ft(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(Se.validate){if(!await Se.validate({params:K.params})){let He=await Z(404);if(He){let oe=He;if(oe=await h(oe,p),a)oe=Ne(oe,u);return new Response(oe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Se.middleware){let Oe=St(F.pathname,K.params,Se,F.search),He=kt(Oe,null,P,{isServer:!0}),oe=await _t(Se.middleware,He);if(oe.redirect){let se=oe.redirect.path,ze=oe.redirect.options.redirectCode||302,Ee=new Headers(oe.responseHeaders);return Ee.set("Location",se),new Response(null,{status:ze,headers:Ee})}if(oe.abort){let{statusCode:se,message:ze}=oe.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(oe.state).length>0){let se=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(oe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${se}</head>`)}}let X=A.content;if(E&&Ti(P)){let Oe=Ke(X),He=ge(X),oe=X.match(/<title[^>]*>([\s\S]*?)<\/title>/i),se=oe?Ci(oe[1].trim()):"";if(Object.keys(K.params).length>0)X=Pt(X,K.params);X=await h(X,p);let ze=g?.router?.container||"main";return X=xe(X,ze),new Response(X,{status:re,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",...se&&{"X-STX-Title":encodeURIComponent(se)},[ta]:Ys(),...O(),"Cache-Control":lt}})}if(E)X=$r(E,X);if(Object.keys(K.params).length>0)X=Pt(X,K.params);if(X=await h(X,p),a)X=Ne(X,u);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-apgb7r22.js");return He(Oe(X,A.boundaries,{timeoutMs:30000}),{status:re,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(X,{status:re,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(M.length>0){let A=M.map((re)=>re.route),le=Zn(F.pathname,A);if(le){let re=L.get(le.route.pattern);if(re){let ae=re.content;if(E)ae=$r(E,ae);if(Object.keys(le.params).length>0)ae=Pt(ae,le.params);if(ae=await h(ae,p),a)ae=Ne(ae,u);return new Response(ae,{status:re.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:re}of j)if(re!=="/"&&F.pathname.startsWith(re)){let ae=L.get(re)||L.get(re+"/");if(ae){let Se=ae.content;if(E)Se=$r(E,Se);if(Se=await h(Se,p),a)Se=Ne(Se,u);return new Response(Se,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(bt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let he=ce.get("/");if(he){let A=he.content;if(A=await h(A,p),a)A=Ne(A,u);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 Ve=await Z(404);if(Ve){let A=Ve;if(A=await h(A,p),a)A=Ne(A,u);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let F=await Z(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
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
- ${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
- ${e.yellow}Routes:${e.reset}`);let Mt=[...Nr(k,p)];for(let{route:A}of _)Mt.push(`${A.pattern}`);if(Mt.forEach((A,z)=>{let W=z===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${W}${e.reset}${A}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(Dt.url.toString(),()=>{if(l)lt();Dt.stop()}),s.native){let A,z=te.join(C,"index.stx");if(he.existsSync(z)){let W=await Bun.file(z).text();A=Tt(W)}let N=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),z=(ee)=>{let Y=ee.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},N=new Map,W=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Y)=>Y.root)??[],...g._layerGraph?.configDependencies.map((Y)=>te.dirname(Y))??[]].filter((Y)=>he.existsSync(Y)).map((Y)=>he.realpathSync(Y)));for(let Y of g._layerGraph?.layers??[])for(let V of Object.values(Y.resources)){if(!he.existsSync(V))continue;let X=he.realpathSync(V);if(![...ee].some((we)=>X===we||X.startsWith(`${we}${te.sep}`)))ee.add(X)}for(let[Y,V]of N)if(!ee.has(Y))V.close(),N.delete(Y);for(let Y of ee)if(!N.has(Y)&&he.existsSync(Y))N.set(Y,he.watch(Y,{recursive:!0},(V,X)=>{ze(Y,V,X).catch((we)=>console.error("[stx] Layer rebuild failed:",we))}))},xe=Promise.resolve(),ze=(ee,Y,V)=>(xe=xe.catch(()=>{}).then(()=>qe(ee,Y,V)),xe),qe=async(ee,Y,V)=>{if(!V||Rt(V))return;if(Ct(V)){if(g._layerGraph){let X=await h(p);Object.assign(g,X),k.splice(0,k.length,...j(v,{pagesDir:x,pagesDirs:X._layerPageDirs?[C,...X._layerPageDirs.slice(1)]:void 0})),W()}if(A(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),c&&l)l.reload(V)}else if(z(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ae.clear(),ie();try{let{invalidateFileCache:X,templateCache:we}=await import("./chunk-k46gqnmk.js");X(te.resolve(ee,V)),we.delete(te.resolve(ee,V))}catch{}if(L&&V){if(te.resolve(ee,V)===L||te.basename(L)===V){let we=await Gr(L,s.stxOptions||{});if(we)E=we}}if(await Ue(),await _n(p),c&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ae.clear(),ie();try{let{invalidateFileCache:X,templateCache:we}=await import("./chunk-k46gqnmk.js");X(te.resolve(ee,V)),we.delete(te.resolve(ee,V))}catch{}if(await Ue(),c&&l)l.reload(V)}}else if($t(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),c&&l)l.updateCss(V)}};W(),process.on("SIGINT",()=>{for(let ee of N.values())ee.close();if(l)lt();Dt.stop(),process.exit(0)})}return!0}import Ut from"fs";import dt from"path";async function Qr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=p.split(`
1435
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=R.join(" ").trim(),c.push(g)}if(c.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Zr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
1436
- `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function eo(t,s=!1,i){let d=dt.basename(t,".stx"),c=await Qr(t),l=await Zr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let p=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
1437
- `);m=`<${d}
1432
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${Je}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1433
+ ${e.yellow}Routes:${e.reset}`);let Dt=[...es(k,p)];for(let{route:P}of M)Dt.push(`${P.pattern}`);if(Dt.forEach((P,F)=>{let U=F===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${U}${e.reset}${P}`)}),console.log(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Xe(Ot.url.toString(),()=>{if(l)st();Ot.stop()}),r.native){let P,F=Q.join(T,"index.stx");if(pe.existsSync(F)){let U=await Bun.file(F).text();P=gt(U)}let z=g?.app?.window??{};await Ze(Je,{title:g?.app?.head?.title||Q.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(Y)=>Y.startsWith("public/")||Y.startsWith("public\\"),F=(Y)=>{let G=Y.toLowerCase();return G.endsWith(".stx")||G.endsWith(".html")||G.endsWith(".md")},z=new Map,U=()=>{let Y=new Set([p,...g._layerGraph?.layers.map((G)=>G.root)??[],...g._layerGraph?.configDependencies.map((G)=>Q.dirname(G))??[]].filter((G)=>pe.existsSync(G)).map((G)=>pe.realpathSync(G)));for(let G of g._layerGraph?.layers??[])for(let W of Object.values(G.resources)){if(!pe.existsSync(W))continue;let K=pe.realpathSync(W);if(![...Y].some((he)=>K===he||K.startsWith(`${he}${Q.sep}`)))Y.add(K)}for(let[G,W]of z)if(!Y.has(G))W.close(),z.delete(G);for(let G of Y)if(!z.has(G)&&pe.existsSync(G))z.set(G,pe.watch(G,{recursive:!0},(W,K)=>{je(G,W,K).catch((he)=>console.error("[stx] Layer rebuild failed:",he))}))},ue=Promise.resolve(),je=(Y,G,W)=>(ue=ue.catch(()=>{}).then(()=>We(Y,G,W)),ue),We=async(Y,G,W)=>{if(!W||Tt(W))return;if(yt(W)){if(g._layerGraph){let K=await y(p);Object.assign(g,K),k.splice(0,k.length,...V(v,{pagesDir:x,pagesDirs:K._layerPageDirs?[T,...K._layerPageDirs.slice(1)]:void 0})),U()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),a&&l)l.reload(W)}else if(F(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ue.clear(),de();try{let{invalidateFileCache:K,templateCache:he}=await import("./chunk-31714f76.js");K(Q.resolve(Y,W)),he.delete(Q.resolve(Y,W))}catch{}if(_&&W){if(Q.resolve(Y,W)===_||Q.basename(_)===W){let he=await js(_,r.stxOptions||{});if(he)E=he}}if(await Be(),await Wn(p),a&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ue.clear(),de();try{let{invalidateFileCache:K,templateCache:he}=await import("./chunk-31714f76.js");K(Q.resolve(Y,W)),he.delete(Q.resolve(Y,W))}catch{}if(await Be(),a&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),a&&l)l.updateCss(W)}};U(),process.on("SIGINT",()=>{for(let Y of z.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 o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let p=u[1],y=u[2]||u[3]||u[4];if(!y)continue;let g={name:y},b=p.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let C=p.split(`
1435
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=C.join(" ").trim(),a.push(g)}if(a.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){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(),o=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
1436
+ `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,r=!1,o){let d=it.basename(t,".stx"),a=await Wr(t),l=await Vr(t),u="";if(r&&o)u=`<${o}></${o}>`;else{let p=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
+ `);u=`<${d}
1438
1438
  ${p}
1439
- />`}return{name:d,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function un(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Ut.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){let c=dt.join(t,d.name);if(d.isDirectory()){let l=await un(c);i.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function to(t,s){try{if(!await r(t))return[];let i=await un(t),d=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),p=!!m,h=m?.tag,g=await eo(l,p,h);d.push(g)}return d}catch(i){return console.error("Error generating component docs:",i),[]}}async function no(t){try{if(!await r(t))return[];let s=await Ut.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let c=dt.join(t,d.name),l=await Bun.file(c).text(),m=dt.basename(c,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=p?p[1].split(`
1440
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=R.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function ro(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1439
+ />`}return{name:d,path:t,description:l,props:a,example:u,isWebComponent:r,tag:o}}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}),o=[];for(let d of r){let a=it.join(t,d.name);if(d.isDirectory()){let l=await dn(a);o.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))o.push(a)}return o}catch(r){return console.error(`Error finding component files in ${t}:`,r),[]}}async function Xr(t,r){try{if(!await n(t))return[];let o=await dn(t),d=[],a=new Map;if(r?.components?.length)for(let l of r.components)a.set(l.file,l);for(let l of o){let u=a.get(l),p=!!u,y=u?.tag,g=await Kr(l,p,y);d.push(g)}return d}catch(o){return console.error("Error generating component docs:",o),[]}}async function Gr(t){try{if(!await n(t))return[];let r=await zt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of r){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let a=it.join(t,d.name),l=await Bun.file(a).text(),u=it.basename(a,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=p?p[1].split(`
1440
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@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=g.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]);o.push({name:u,path:a,description:y,components:[...w],directives:[...v]})}return o}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,49 +1457,49 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(Dt.
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)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function oo(t=[],s=[],i=[],d){let c=`# 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 o of t)r.push({name:o.name,description:o.description||"",hasEndTag:o.hasEndTag||!1,example:""});return r}catch(r){return console.error("Error generating directive docs:",r),[]}}function Yr(t=[],r=[],o=[],d){let a=`# stx Documentation
1461
1461
 
1462
- `;if(d)c+=`${d}
1462
+ `;if(d)a+=`${d}
1463
1463
 
1464
- `;if(t.length>0){c+=`## Components
1464
+ `;if(t.length>0){a+=`## Components
1465
1465
 
1466
- `;for(let l of t){if(c+=`### ${l.name}
1466
+ `;for(let l of t){if(a+=`### ${l.name}
1467
1467
 
1468
- `,l.description)c+=`${l.description}
1468
+ `,l.description)a+=`${l.description}
1469
1469
 
1470
- `;if(l.isWebComponent)c+=`**Web Component Tag:** \`${l.tag}\`
1470
+ `;if(l.isWebComponent)a+=`**Web Component Tag:** \`${l.tag}\`
1471
1471
 
1472
- `;if(l.props.length>0){c+=`#### Properties
1472
+ `;if(l.props.length>0){a+=`#### Properties
1473
1473
 
1474
- `,c+=`| Name | Type | Required | Default | Description |
1475
- `,c+=`| ---- | ---- | -------- | ------- | ----------- |
1476
- `;for(let m of l.props)c+=`| ${m.name} | ${m.type||"any"} | ${m.required?"Yes":"No"} | ${m.default||"-"} | ${m.description||"-"} |
1477
- `;c+=`
1478
- `}if(l.example)c+=`#### Example
1474
+ `,a+=`| Name | Type | Required | Default | Description |
1475
+ `,a+=`| ---- | ---- | -------- | ------- | ----------- |
1476
+ `;for(let u of l.props)a+=`| ${u.name} | ${u.type||"any"} | ${u.required?"Yes":"No"} | ${u.default||"-"} | ${u.description||"-"} |
1477
+ `;a+=`
1478
+ `}if(l.example)a+=`#### Example
1479
1479
 
1480
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
1480
+ `,a+="```html\n",a+=l.example,a+="\n```\n\n"}}if(r.length>0){a+=`## Templates
1481
1481
 
1482
- `;for(let l of s){if(c+=`### ${l.name}
1482
+ `;for(let l of r){if(a+=`### ${l.name}
1483
1483
 
1484
- `,l.description)c+=`${l.description}
1484
+ `,l.description)a+=`${l.description}
1485
1485
 
1486
- `;if(l.components&&l.components.length>0)c+=`**Components Used:** ${l.components.join(", ")}
1486
+ `;if(l.components&&l.components.length>0)a+=`**Components Used:** ${l.components.join(", ")}
1487
1487
 
1488
- `;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
1488
+ `;if(l.directives&&l.directives.length>0)a+=`**Directives Used:** ${l.directives.join(", ")}
1489
1489
 
1490
- `}}if(i.length>0){c+=`## Directives
1490
+ `}}if(o.length>0){a+=`## Directives
1491
1491
 
1492
- `,c+=`| Directive | Description | Has End Tag |
1493
- `,c+=`| --------- | ----------- | ----------- |
1494
- `;for(let l of i)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
- `;c+=`
1496
- `;for(let l of i)if(l.example)c+=`### @${l.name}
1492
+ `,a+=`| Directive | Description | Has End Tag |
1493
+ `,a+=`| --------- | ----------- | ----------- |
1494
+ `;for(let l of o)a+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
+ `;a+=`
1496
+ `;for(let l of o)if(l.example)a+=`### @${l.name}
1497
1497
 
1498
- `,c+=`${l.description||""}
1498
+ `,a+=`${l.description||""}
1499
1499
 
1500
- `,c+=`#### Example
1500
+ `,a+=`#### Example
1501
1501
 
1502
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function so(t=[],s=[],i=[],d){let c=`<!DOCTYPE html>
1502
+ `,a+="```html\n",a+=l.example,a+="\n```\n\n"}return a}function eo(t=[],r=[],o=[],d){let a=`<!DOCTYPE html>
1503
1503
  <html lang="en">
1504
1504
  <head>
1505
1505
  <meta charset="UTF-8">
@@ -1542,7 +1542,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(Dt.
1542
1542
  </head>
1543
1543
  <body>
1544
1544
  <h1>stx Documentation</h1>
1545
- `;if(d)c+=`<div>${d}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
1545
+ `;if(d)a+=`<div>${d}</div>`;if(t.length>0){a+="<h2>Components</h2>";for(let l of t){if(a+=`<h3>${l.name}</h3>`,l.description)a+=`<p>${l.description}</p>`;if(l.isWebComponent)a+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){a+="<h4>Properties</h4>",a+=`<table>
1546
1546
  <thead>
1547
1547
  <tr>
1548
1548
  <th>Name</th>
@@ -1552,13 +1552,13 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(Dt.
1552
1552
  <th>Description</th>
1553
1553
  </tr>
1554
1554
  </thead>
1555
- <tbody>`;for(let m of l.props)c+=`<tr>
1556
- <td>${m.name}</td>
1557
- <td>${m.type||"any"}</td>
1558
- <td>${m.required?"Yes":"No"}</td>
1559
- <td>${m.default||"-"}</td>
1560
- <td>${m.description||"-"}</td>
1561
- </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(i.length>0){c+="<h2>Directives</h2>",c+=`<table>
1555
+ <tbody>`;for(let u of l.props)a+=`<tr>
1556
+ <td>${u.name}</td>
1557
+ <td>${u.type||"any"}</td>
1558
+ <td>${u.required?"Yes":"No"}</td>
1559
+ <td>${u.default||"-"}</td>
1560
+ <td>${u.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(o.length>0){a+="<h2>Directives</h2>",a+=`<table>
1562
1562
  <thead>
1563
1563
  <tr>
1564
1564
  <th>Directive</th>
@@ -1566,44 +1566,44 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ge(Dt.
1566
1566
  <th>Has End Tag</th>
1567
1567
  </tr>
1568
1568
  </thead>
1569
- <tbody>`;for(let l of i)c+=`<tr>
1569
+ <tbody>`;for(let l of o)a+=`<tr>
1570
1570
  <td>@${l.name}</td>
1571
1571
  <td>${l.description||"-"}</td>
1572
1572
  <td>${l.hasEndTag?"Yes":"No"}</td>
1573
- </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function io(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ao(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Ut.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await to(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await no(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ro(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=oo(p,h,g,w),R="md";break;case"html":S=so(p,h,g,w),R="html";break;case"json":S=io(p,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=dt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function xo(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return ao({componentsDir:i,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Br(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1574
- `;let d=t;if(i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=po(d,i),d=go(d,i),d=uo(d,i),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1573
+ </tr>`;a+="</tbody></table>";for(let l of o)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 to(t=[],r=[],o=[],d){return JSON.stringify({components:t,templates:r,directives:o,extraContent:d||""},null,2)}async function no(t){try{let{componentsDir:r,templatesDir:o,webComponentsConfig:d,customDirectives:a,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await zt.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),r)console.log(`Components directory: ${r}`);if(o)console.log(`Templates directory: ${o}`);console.log(`Output directory: ${u}`);let p=[];if(l.components!==!1&&r)console.log("Generating component documentation..."),p=await Xr(r,d),console.log(`Found ${p.length} components`);let y=[];if(l.templates!==!1&&o)console.log("Generating template documentation..."),y=await Gr(o),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Jr(a),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",C="";switch(b){case"markdown":S=Yr(p,y,g,w),C="md";break;case"html":S=eo(p,y,g,w),C="html";break;case"json":S=to(p,y,g,w),C="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=it.join(u,`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 gi(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},o=t.componentsDir||R.componentsDir,d=t.templatesDir||".";return no({componentsDir:o,templatesDir:d,webComponentsConfig:R.webComponents,customDirectives:R.customDirectives,config:r})}var un={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function As(t,r={}){let o={...un,...r};if(t.trim()==="")return`
1574
+ `;let d=t;if(o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=so(d,o),d=lo(d,o),d=io(d,o),o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
1575
1575
  `).replace(/\r/g,`
1576
1576
  `),!d.endsWith(`
1577
1577
  `))d+=`
1578
- `;return d}function So(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1579
- `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,p,h)=>{let g=p.split(`
1580
- `),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let C=x.match(/^( *)/);return C?C[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
- `),v=Br(S,i).trimEnd().split(`
1578
+ `;return d}function mi(t,r={}){let o={...un,...r};if(t.trim()==="")return`
1579
+ `;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(a,l,u,p,y)=>{let g=p.split(`
1580
+ `),b=g.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=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
+ `),v=As(S,o).trimEnd().split(`
1582
1582
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
- `);return`${l}\`\`\`${m}
1583
+ `);return`${l}\`\`\`${u}
1584
1584
  ${v}
1585
- ${l}\`\`\``}),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replace(/\r\n/g,`
1585
+ ${l}\`\`\``}),o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!d.endsWith(`
1588
1588
  `))d+=`
1589
- `;return d}function lo(t){let s=t,i=[],d="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${d}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1589
+ `;return d}function oo(t){let r=t,o=[],d="__PROTECTED_BLOCK_";return r=r.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(a)=>{let l=o.length;return o.push(a),`${d}${l}__`}),r=r.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1590
1590
  $1
1591
- `),s=s.replace(/(@end\w+)/g,`
1591
+ `),r=r.replace(/(@end\w+)/g,`
1592
1592
  $1
1593
- `),s=s.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1593
+ `),r=r.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1594
1594
  $1
1595
- `),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1595
+ `),r=r.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1596
1596
  $1
1597
- `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,p)=>{let h=p.substring(m+c.length,Math.min(p.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
1598
- ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,p,h)=>{let g=h.substring(Math.max(0,p-50),p),w=h.substring(p+c.length,Math.min(h.length,p+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1599
- ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,p)=>{let h=p.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
1600
- `}),s=s.replace(new RegExp(`${d}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1601
- `),s=s.split(`
1602
- `).map((c)=>c.trim()).join(`
1603
- `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function po(t,s){let d=lo(t).split(`
1604
- `),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let R=y===">";if(fn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&mo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),B=y.startsWith("<!--"),_=y.startsWith("</"),I=y.startsWith("<")&&!_&&!B&&!k,E=y.includes("/>")||fo(y),L=fn(y);if(_||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(p.repeat(F)+y);if(I&&!E&&!L&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
- `)}function uo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,d,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,d,c)=>{if(c.trim()==="")return`@${d}`;return`@${d}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,d)=>`{!! ${d.trim()} !!}`);return t}function fo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let d=i[1];return s.includes(d.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function mo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function go(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,d,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1606
- `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],p;while((p=l.exec(c))!==null)m.push({name:p[1],value:p[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${h?` ${h}`:""}>`})}import gn from"fs";import Vt from"path";async function ko(t="index.stx",s={}){try{let i=s.force||!1,d=Vt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(d);if(!gn.existsSync(c))gn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=hn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=hn("basic");return await Bun.write(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function hn(t){switch(t){case"basic":return yn();case"component":return ho();case"layout":return yo();case"blog":return To();case"api":return $o();case"app":return Ro();default:return yn()}}function yn(){return`<script>
1597
+ `),r=r.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(a,l,u,p)=>{let y=p.substring(u+a.length,Math.min(p.length,u+a.length+20)),g=a.match(/<(\w+)/)?.[1];if(g&&y.match(new RegExp(`^</${g}>`)))return a;return`
1598
+ ${a}`}),r=r.replace(/(>)(<\/)/g,(a,l,u,p,y)=>{let g=y.substring(Math.max(0,p-50),p),w=y.substring(p+a.length,Math.min(y.length,p+a.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return a;return`${l}
1599
+ ${u}`}),r=r.replace(/(<\/[^>]+>)(?=<|$)/g,(a,l,u,p)=>{let y=p.substring(Math.max(0,u-20),u),g=a.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&y.match(b))return a;return`${a}
1600
+ `}),r=r.replace(new RegExp(`${d}(\\d+)__`,"g"),(a,l)=>o[Number.parseInt(l,10)]),r=r.replace(/\n{2,}/g,`
1601
+ `),r=r.split(`
1602
+ `).map((a)=>a.trim()).join(`
1603
+ `),r=r.replace(/^\n+/,"").replace(/\n+$/,""),r}function so(t,r){let d=oo(t).split(`
1604
+ `),a=[],l=0,u=!1,p=r.useTabs?"\t":" ".repeat(r.indentSize);for(let y=0;y<d.length;y++){let g=d[y],b=g.trim();if(b===""){a.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(u&&!S){a.push(g);continue}let C=b===">";if(pn(b)&&!b.startsWith("<")&&!b.startsWith("@")){a.push(p.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),T=b.startsWith("@")&&co(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),j=b.startsWith("<!--"),M=b.startsWith("</"),L=b.startsWith("<")&&!M&&!j&&!k,E=b.includes("/>")||ao(b),_=pn(b);if(M||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(C)a.push(g);else a.push(p.repeat(B)+b);if(L&&!E&&!_&&!C||T)l++;if(w)u=!0;if(S)u=!1}return a.join(`
1605
+ `)}function io(t,r){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,d,a)=>{let l=a.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,d,a)=>{if(a.trim()==="")return`@${d}`;return`@${d}(${a.trim()})`}),r.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,d)=>`{!! ${d.trim()} !!}`);return t}function ao(t){let r=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let o=t.match(/<(\w+)/);if(o){let d=o[1];return r.includes(d.toLowerCase())}return!1}function pn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function co(t){let r=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let o of r)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function lo(t,r){if(!r.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,d,a)=>{if(!a.trim())return o;if(a.includes("<")||a.includes(`
1606
+ `)||a.includes("@"))return o;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],p;while((p=l.exec(a))!==null)u.push({name:p[1],value:p[2]});u.sort((g,b)=>{if(g.name==="id")return-1;if(b.name==="id")return 1;if(g.name==="class")return-1;if(b.name==="class")return 1;return g.name.localeCompare(b.name)});let y=u.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${d}${y?` ${y}`:""}>`})}import fn from"fs";import Nt from"path";async function hi(t="index.stx",r={}){try{let o=r.force||!1,d=Nt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!o)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let a=Nt.dirname(d);if(!fn.existsSync(a))fn.mkdirSync(a,{recursive:!0});let l;if(r.template){let u=Nt.resolve(process.cwd(),r.template);if(!await Bun.file(u).exists())throw Error(`Template file ${r.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${r.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).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(d,l),console.warn(`Created new stx file: ${t}`),!0}catch(o){return console.error(`Error creating file: ${o instanceof Error?o.message:String(o)}`),!1}}function mn(t){switch(t){case"basic":return gn();case"component":return po();case"layout":return uo();case"blog":return fo();case"api":return mo();case"app":return go();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 = [
@@ -1628,7 +1628,7 @@ const features = [
1628
1628
  </div>
1629
1629
  @endforeach
1630
1630
  </main>
1631
- @endsection`}function ho(){return`{{-- Component: Card --}}
1631
+ @endsection`}function po(){return`{{-- Component: Card --}}
1632
1632
  {{-- Props: title, variant, collapsible --}}
1633
1633
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1634
1634
  <script>
@@ -1673,7 +1673,7 @@ const features = [
1673
1673
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
1674
1674
  .card__body { padding: 1rem; }
1675
1675
  .card.collapsed .card__body { display: none; }
1676
- </style>`}function yo(){return`<!DOCTYPE html>
1676
+ </style>`}function uo(){return`<!DOCTYPE html>
1677
1677
  <html lang="en">
1678
1678
  <head>
1679
1679
  <meta charset="UTF-8">
@@ -1724,7 +1724,7 @@ const features = [
1724
1724
 
1725
1725
  @yield('scripts')
1726
1726
  </body>
1727
- </html>`}function To(){return`<script>
1727
+ </html>`}function fo(){return`<script>
1728
1728
  // Article metadata
1729
1729
  const title = "My Blog Post"
1730
1730
  const author = "Your Name"
@@ -1769,7 +1769,7 @@ const features = [
1769
1769
  <p>Wrap up your thoughts here.</p>
1770
1770
  </div>
1771
1771
  </article>
1772
- @endsection`}function $o(){return`<script>
1772
+ @endsection`}function mo(){return`<script>
1773
1773
  // API endpoint configuration
1774
1774
  const endpoint = "/api/data"
1775
1775
  const method = "GET"
@@ -1804,7 +1804,7 @@ const features = [
1804
1804
  }
1805
1805
  @else
1806
1806
  {{ JSON.stringify(data, null, 2) }}
1807
- @endif`}function Ro(){return`<!DOCTYPE html>
1807
+ @endif`}function go(){return`<!DOCTYPE html>
1808
1808
  <html lang="en">
1809
1809
  <head>
1810
1810
  <meta charset="UTF-8">
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
2032
- </html>`}var Co="f9c3713";function ha(t){return t}function ya(t){return t}function bo(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}import Me from"fs";import Se from"path";function Rn(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Ot(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ai(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function En(t,s="stx"){let i=Se.resolve(t);for(let d=0;d<10;d++){let c=Se.join(i,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Se.dirname(i);if(l===i)break;i=l}return null}var Pn=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=Me.readFileSync(Se.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Mi(t,s=6){let i=Se.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=Me.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of Pn){let S=Se.join(p,w),R=Di(S);if(R!==null)d.push({name:w,version:R,dir:Se.relative(i,S)||S,nested:h>0})}let y;try{y=Me.readdirSync(p,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Se.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=Se.join(S,x.name,"node_modules");if(Me.existsSync(C))l(C,h+1)}continue}let R=Se.join(S,"node_modules");if(Me.existsSync(R))l(R,h+1)}}let m=Se.join(i,"node_modules");if(Me.existsSync(m))l(m,0);return d}function _i(t){let s=[];for(let i of Pn){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function Fr(t={}){let s=t.cwd?Se.resolve(t.cwd):process.cwd(),i=t.resolve??Ai,d=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of _i(Mi(s)))c.push(h);let p=En(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Se.join(p,"src/signals.ts"),g=[Se.join(p,"dist/index.js"),Se.join(p,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,y=Rn(h),w=g?Rn(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Ot(w,d)}) is OLDER than src/signals.ts (${Ot(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Ot(y,d)}, dist ${Ot(w,d)})`});let S=Se.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=Me.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(p)}catch{return p}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function zr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
2033
- `)}export{bo,vo,wo,xo,Br,So,ko,Co,ha,ya,Fr,zr,qn,Gn,Kn};
2032
+ </html>`}var yi="f9c3713";function xc(t){return t}function Sc(t){return t}function di(t,r){let o=[],d=`${r}=`;for(let a=0;a<t.length;a++){let l=t[a];if(l.startsWith(d)){let u=l.slice(d.length);if(u)o.push(u);continue}if(l===r){let u=t[a+1];if(u!==void 0&&!u.startsWith("-"))o.push(u),a++}}return o}import Pe from"fs";import ye from"path";function $n(t){try{return Pe.statSync(t).mtimeMs}catch{return null}}function Et(t,r){let o=Math.max(0,Math.round((r-t)/1000));if(o<60)return`${o}s ago`;if(o<3600)return`${Math.round(o/60)}m ago`;return`${Math.round(o/3600)}h ago`}function Ai(t,r){try{return globalThis.Bun?.resolveSync(t,r)??null}catch{return null}}function Cn(t,r="stx"){let o=ye.resolve(t);for(let d=0;d<10;d++){let a=ye.join(o,"pantry","@stacksjs",r);if(Pe.existsSync(a))return a;let l=ye.dirname(o);if(l===o)break;o=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let r=Pe.readFileSync(ye.join(t,"package.json"),"utf8"),o=JSON.parse(r)?.version;return typeof o==="string"?o:null}catch{return null}}function Mi(t,r=6){let o=ye.resolve(t),d=[],a=new Set;function l(p,y){if(y>r)return;let g;try{g=Pe.realpathSync(p)}catch{return}if(a.has(g))return;a.add(g);for(let w of Rn){let S=ye.join(p,w),C=Di(S);if(C!==null)d.push({name:w,version:C,dir:ye.relative(o,S)||S,nested:y>0})}let b;try{b=Pe.readdirSync(p,{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(p,w.name);if(w.name.startsWith("@")){let v;try{v=Pe.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=ye.join(S,x.name,"node_modules");if(Pe.existsSync(T))l(T,y+1)}continue}let C=ye.join(S,"node_modules");if(Pe.existsSync(C))l(C,y+1)}}let u=ye.join(o,"node_modules");if(Pe.existsSync(u))l(u,0);return d}function _i(t){let r=[];for(let o of Rn){let d=t.filter((u)=>u.name===o);if(d.length<=1)continue;let a=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(a.length===1){r.push({name:`${o} copies`,status:"info",detail:`${d.length} copies, all ${a[0]} \u2014 duplicated but in agreement`});continue}r.push({name:`${o} 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 ${o}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${o}/package.json' -exec grep -H '"version"' {} +`})}return r}async function Ps(t={}){let r=t.cwd?ye.resolve(t.cwd):process.cwd(),o=t.resolve??Ai,d=Date.now(),a=[],l=o("@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 u=o("bun-plugin-stx",r);if(u)a.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let y of _i(Mi(r)))a.push(y);let p=Cn(r,"stx");if(!p)a.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ye.join(p,"src/signals.ts"),g=[ye.join(p,"dist/index.js"),ye.join(p,"dist/signals.js")].find((v)=>Pe.existsSync(v))||null,b=$n(y),w=g?$n(g):null;if(b==null)a.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} 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 ${p} && 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,d)}) is OLDER than src/signals.ts (${Et(b,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else a.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Et(b,d)}, dist ${Et(w,d)})`});let S=ye.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(p)}catch{return p}})();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 g=t.generateRuntime().length;a.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(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 Is(t){let r={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let d of t.checks)if(o.push(` ${r[d.status]} ${d.name}: ${d.detail}`),d.fix)o.push(` \u2192 ${d.fix}`);return o.push(""),o.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),o.join(`
2033
+ `)}export{di,pi,fi,gi,As,mi,hi,yi,xc,Sc,Ps,Is,Sr,kr,_r};