@stacksjs/stx 0.2.414 → 0.2.416

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 (204) hide show
  1. package/dist/builtins/image-delivery.js +19 -11
  2. package/dist/chunk-02k2v1mb.js +2 -0
  3. package/dist/chunk-0dh1rgg8.js +2 -0
  4. package/dist/{chunk-eed4fwps.js → chunk-0es4h5v1.js} +2 -2
  5. package/dist/chunk-0hrqt5c2.js +2 -0
  6. package/dist/chunk-0vtk2rpr.js +2 -0
  7. package/dist/{chunk-mp6hy8g4.js → chunk-1ctvgd7v.js} +1 -1
  8. package/dist/chunk-1rd3jzrq.js +2 -0
  9. package/dist/{chunk-h0atqq82.js → chunk-26j2q9rq.js} +7 -7
  10. package/dist/chunk-2py27bzq.js +2 -0
  11. package/dist/{chunk-px7fvbj6.js → chunk-2qa7hjp2.js} +2 -2
  12. package/dist/chunk-35e6zj5x.js +2 -0
  13. package/dist/{chunk-g578mcb0.js → chunk-388rx71h.js} +6 -6
  14. package/dist/chunk-3ch40ebr.js +2 -0
  15. package/dist/{chunk-bay9s6rs.js → chunk-3g8zzdgs.js} +5 -5
  16. package/dist/{chunk-md8rqn48.js → chunk-3t0yaexe.js} +5 -5
  17. package/dist/{chunk-b84h16er.js → chunk-3wrmz1j9.js} +6 -6
  18. package/dist/{chunk-ak1cgcah.js → chunk-41k0th97.js} +4 -4
  19. package/dist/chunk-49cpqjx2.js +2 -0
  20. package/dist/chunk-4k1nkp9r.js +2 -0
  21. package/dist/chunk-50vq8k55.js +2 -0
  22. package/dist/chunk-56pkjk55.js +2 -0
  23. package/dist/chunk-5hnh00ry.js +2 -0
  24. package/dist/chunk-5j52h3e3.js +2 -0
  25. package/dist/chunk-5y1mekxe.js +2 -0
  26. package/dist/chunk-5zryk911.js +2 -0
  27. package/dist/{chunk-h6zsqb9r.js → chunk-6agy2x1f.js} +2 -2
  28. package/dist/chunk-72w28vm8.js +2 -0
  29. package/dist/{chunk-3kthfs03.js → chunk-7mbpjv9e.js} +2 -2
  30. package/dist/chunk-7s7k94as.js +2 -0
  31. package/dist/{chunk-9g27ybyr.js → chunk-7tabykst.js} +2 -2
  32. package/dist/chunk-7wb6jf17.js +2 -0
  33. package/dist/{chunk-e57rhf65.js → chunk-7zjvsacw.js} +2 -2
  34. package/dist/{chunk-fh1qrp68.js → chunk-89xcpdsp.js} +5 -5
  35. package/dist/chunk-8cbkqckh.js +2 -0
  36. package/dist/chunk-8ycy1b0e.js +2 -0
  37. package/dist/chunk-8ygks6dx.js +3 -0
  38. package/dist/{chunk-rs4v4fha.js → chunk-95165j9c.js} +2 -2
  39. package/dist/{chunk-pqxzp1bb.js → chunk-9fyss0yk.js} +2 -2
  40. package/dist/{chunk-q4c06e8x.js → chunk-9rnh52t2.js} +10 -10
  41. package/dist/{chunk-169n1vpx.js → chunk-9t2xx2y4.js} +3 -3
  42. package/dist/{chunk-6sgswrqw.js → chunk-a47yp92z.js} +5 -5
  43. package/dist/{chunk-765e1s44.js → chunk-ae7j3n39.js} +6 -6
  44. package/dist/chunk-aqrnpgn7.js +2 -0
  45. package/dist/{chunk-dvgv8nry.js → chunk-at0ar6t3.js} +3 -3
  46. package/dist/chunk-b9rebdtq.js +2 -0
  47. package/dist/{chunk-7gkv67ky.js → chunk-bfjzfrw3.js} +2 -2
  48. package/dist/{chunk-z0g9jvv0.js → chunk-c4bkj1xw.js} +6 -6
  49. package/dist/chunk-c4thhfx9.js +2 -0
  50. package/dist/{chunk-6hc5vz20.js → chunk-cn9hgyh5.js} +2 -2
  51. package/dist/{chunk-pgzvyrv6.js → chunk-cq408jrm.js} +3 -3
  52. package/dist/chunk-cw6kqb63.js +2 -0
  53. package/dist/chunk-d3vtgnep.js +2 -0
  54. package/dist/chunk-d4ynv4z2.js +2 -0
  55. package/dist/chunk-d7xrewxq.js +2 -0
  56. package/dist/{chunk-q9bdh4s5.js → chunk-dd5fa7d6.js} +2 -2
  57. package/dist/{chunk-shr559s7.js → chunk-ddk6fx5b.js} +2 -2
  58. package/dist/{chunk-8nhshfz6.js → chunk-de2pv6ys.js} +2 -2
  59. package/dist/{chunk-69mc2np8.js → chunk-dg1n3g1d.js} +172 -172
  60. package/dist/chunk-ecr598p7.js +2 -0
  61. package/dist/chunk-eev80mpy.js +2 -0
  62. package/dist/chunk-ef5vz9w5.js +2 -0
  63. package/dist/chunk-f5qd84w8.js +2 -0
  64. package/dist/{chunk-gawrg4gb.js → chunk-fctjn68q.js} +6 -6
  65. package/dist/{chunk-amd6ey3t.js → chunk-fkhxz1dx.js} +5 -5
  66. package/dist/chunk-g69tnqga.js +2 -0
  67. package/dist/chunk-gacycmb0.js +2 -0
  68. package/dist/chunk-ggywfyzm.js +2 -0
  69. package/dist/chunk-gp1bhn7t.js +2 -0
  70. package/dist/{chunk-vgvtnwxa.js → chunk-gq97zh73.js} +3 -3
  71. package/dist/chunk-gr3r9xdh.js +2 -0
  72. package/dist/{chunk-ngc2wke4.js → chunk-gxrewzhv.js} +2 -2
  73. package/dist/{chunk-scezfp0w.js → chunk-gyv1t0f0.js} +5 -5
  74. package/dist/{chunk-340a824p.js → chunk-h8wegkb5.js} +1 -1
  75. package/dist/{chunk-v091jft4.js → chunk-hec0bvvf.js} +1 -1
  76. package/dist/chunk-hg1eq72d.js +2 -0
  77. package/dist/chunk-hvyqs5tf.js +2 -0
  78. package/dist/{chunk-y5310237.js → chunk-j8rxdbe5.js} +2 -2
  79. package/dist/{chunk-5qns2sdz.js → chunk-jr4dwkvc.js} +2 -2
  80. package/dist/chunk-kbysqxmd.js +2 -0
  81. package/dist/chunk-kmnsrvrp.js +2 -0
  82. package/dist/chunk-m6fvj7g1.js +2 -0
  83. package/dist/{chunk-j03revz2.js → chunk-m9xdkzm6.js} +3 -3
  84. package/dist/chunk-mgw2cvb7.js +2 -0
  85. package/dist/chunk-mvwt1c8f.js +2 -0
  86. package/dist/{chunk-daz5aqcf.js → chunk-n5k88y07.js} +3 -3
  87. package/dist/{chunk-r3f9jcf7.js → chunk-nj8edn4m.js} +3 -3
  88. package/dist/chunk-nvh31cxn.js +2 -0
  89. package/dist/{chunk-fr2txj8q.js → chunk-p1tb8kxq.js} +4 -4
  90. package/dist/chunk-p34gbb4z.js +2 -0
  91. package/dist/chunk-peyt18ce.js +2 -0
  92. package/dist/{chunk-d44b9ktb.js → chunk-ppse812s.js} +1 -1
  93. package/dist/{chunk-752hw7cd.js → chunk-qff4qkx5.js} +3 -3
  94. package/dist/chunk-qpx8kvd8.js +2 -0
  95. package/dist/{chunk-f46qsp4m.js → chunk-qzkebqm3.js} +2 -2
  96. package/dist/chunk-rb272g9d.js +3 -0
  97. package/dist/{chunk-m4sk62wb.js → chunk-rfdqrv5v.js} +4 -4
  98. package/dist/{chunk-9vrja6vp.js → chunk-rg6csnkw.js} +1 -1
  99. package/dist/chunk-rh1dyfsn.js +2 -0
  100. package/dist/{chunk-czxt605c.js → chunk-rhw7pqhy.js} +4 -4
  101. package/dist/{chunk-thyt8ed8.js → chunk-rp4khnan.js} +3 -3
  102. package/dist/{chunk-s5xezjps.js → chunk-rqc4jx2v.js} +1 -1
  103. package/dist/chunk-rspc8gn8.js +2 -0
  104. package/dist/{chunk-2gr351s0.js → chunk-rv5bk83t.js} +2 -2
  105. package/dist/chunk-rvs61c88.js +2 -0
  106. package/dist/chunk-sf1vhfrb.js +2 -0
  107. package/dist/{chunk-yvx1ap9b.js → chunk-sh5c60a2.js} +2 -2
  108. package/dist/{chunk-ym95v4nc.js → chunk-std6xw3y.js} +2 -2
  109. package/dist/{chunk-pbh4smw3.js → chunk-t9axxwy9.js} +4 -4
  110. package/dist/{chunk-ynvdvbat.js → chunk-tc274fcv.js} +4 -4
  111. package/dist/{chunk-9pt8fd2n.js → chunk-tfhjbjq5.js} +3 -3
  112. package/dist/chunk-ty7t3gp4.js +3 -0
  113. package/dist/{chunk-6h38kkjf.js → chunk-v096a6fw.js} +6 -6
  114. package/dist/chunk-vc9wa97m.js +2 -0
  115. package/dist/{chunk-y1cmjvk3.js → chunk-vvp4cmfq.js} +5 -5
  116. package/dist/{chunk-t4hzprsm.js → chunk-vvs75dse.js} +2 -2
  117. package/dist/{chunk-qet5gc6s.js → chunk-wjag92ch.js} +73 -73
  118. package/dist/chunk-wjzqz3yr.js +2 -0
  119. package/dist/{chunk-xtdw3692.js → chunk-wpe72ann.js} +5 -5
  120. package/dist/{chunk-ej9j6k1q.js → chunk-x0mq57pe.js} +2 -2
  121. package/dist/chunk-x7j0krz8.js +2 -0
  122. package/dist/chunk-xkv0evbf.js +2 -0
  123. package/dist/{chunk-x0q32ees.js → chunk-y5cqkmkf.js} +2 -2
  124. package/dist/{chunk-mepdnezf.js → chunk-y6rahx7t.js} +5 -5
  125. package/dist/{chunk-yazk54jr.js → chunk-yk63jd7v.js} +1 -1
  126. package/dist/chunk-yt452b4a.js +2 -0
  127. package/dist/{chunk-sd47dzs0.js → chunk-yt6h8c6g.js} +11 -11
  128. package/dist/chunk-yxfx44fv.js +2 -0
  129. package/dist/{chunk-ce1sejr3.js → chunk-yzv8n6qw.js} +2 -2
  130. package/dist/{chunk-v4vaqxrf.js → chunk-zcctf7tx.js} +3 -3
  131. package/dist/{chunk-ft4p6d28.js → chunk-znbay168.js} +2 -2
  132. package/dist/{chunk-xfp7k0v8.js → chunk-zyxp0nb3.js} +7 -7
  133. package/dist/cli.js +20 -20
  134. package/dist/craft-entry.js +2 -2
  135. package/dist/craft.js +2 -2
  136. package/dist/dev-server/serve-app.js +3 -0
  137. package/dist/dev-server/serve-multi.js +1 -1
  138. package/dist/document-shell.js +15 -3
  139. package/dist/native/components/primitives.d.ts +2 -0
  140. package/dist/production-server.js +4 -4
  141. package/dist/pwa.js +3 -3
  142. package/dist/ssg.js +15 -15
  143. package/package.json +5 -5
  144. package/dist/chunk-020xyn9q.js +0 -3
  145. package/dist/chunk-04jhmfbz.js +0 -2
  146. package/dist/chunk-10957mcb.js +0 -2
  147. package/dist/chunk-1098mas0.js +0 -2
  148. package/dist/chunk-1b6t12hd.js +0 -2
  149. package/dist/chunk-1chw8xsw.js +0 -2
  150. package/dist/chunk-2ce7f416.js +0 -2
  151. package/dist/chunk-2mkcjw08.js +0 -2
  152. package/dist/chunk-2v8wztd5.js +0 -2
  153. package/dist/chunk-39g1134q.js +0 -2
  154. package/dist/chunk-3c74vag1.js +0 -2
  155. package/dist/chunk-3qn1wcdg.js +0 -2
  156. package/dist/chunk-3s2vnqcf.js +0 -2
  157. package/dist/chunk-48bwk47q.js +0 -2
  158. package/dist/chunk-4bjravgk.js +0 -2
  159. package/dist/chunk-4jjme6a5.js +0 -2
  160. package/dist/chunk-5g3y8kym.js +0 -2
  161. package/dist/chunk-5gsxpaqk.js +0 -2
  162. package/dist/chunk-6cfa3g0r.js +0 -2
  163. package/dist/chunk-6y8hnymb.js +0 -2
  164. package/dist/chunk-7z2ra0yf.js +0 -2
  165. package/dist/chunk-866n724v.js +0 -2
  166. package/dist/chunk-92ps1xpk.js +0 -2
  167. package/dist/chunk-9xrbve19.js +0 -2
  168. package/dist/chunk-afhxw2t8.js +0 -2
  169. package/dist/chunk-apg16xcn.js +0 -2
  170. package/dist/chunk-b52s5z0c.js +0 -2
  171. package/dist/chunk-bmt7w2pk.js +0 -2
  172. package/dist/chunk-btmhj5t7.js +0 -2
  173. package/dist/chunk-dgdm3hy3.js +0 -2
  174. package/dist/chunk-dx7n22ed.js +0 -2
  175. package/dist/chunk-f6az0xj5.js +0 -2
  176. package/dist/chunk-fjs0a8h7.js +0 -2
  177. package/dist/chunk-fyzajkrx.js +0 -2
  178. package/dist/chunk-fzapbw9p.js +0 -3
  179. package/dist/chunk-gw07qmjk.js +0 -2
  180. package/dist/chunk-hbxz85wy.js +0 -2
  181. package/dist/chunk-hjg3ndgh.js +0 -2
  182. package/dist/chunk-hkxsewzk.js +0 -2
  183. package/dist/chunk-hrbbbtbn.js +0 -2
  184. package/dist/chunk-j9qcrwbg.js +0 -2
  185. package/dist/chunk-jk4njz0w.js +0 -2
  186. package/dist/chunk-jmabeqfq.js +0 -2
  187. package/dist/chunk-jt0n43mk.js +0 -2
  188. package/dist/chunk-m1vdghnx.js +0 -2
  189. package/dist/chunk-mhq0pjws.js +0 -2
  190. package/dist/chunk-nn2vstke.js +0 -2
  191. package/dist/chunk-p2v2a68k.js +0 -2
  192. package/dist/chunk-pdt69hpb.js +0 -2
  193. package/dist/chunk-pj1wg7jg.js +0 -2
  194. package/dist/chunk-q6vrb2pe.js +0 -2
  195. package/dist/chunk-q7qchkvk.js +0 -2
  196. package/dist/chunk-qz519eyp.js +0 -2
  197. package/dist/chunk-s2x4wcrz.js +0 -2
  198. package/dist/chunk-sd321bn3.js +0 -2
  199. package/dist/chunk-se7mwqd1.js +0 -2
  200. package/dist/chunk-syaw6b75.js +0 -2
  201. package/dist/chunk-x5bpeb4a.js +0 -2
  202. package/dist/chunk-x72tv2cg.js +0 -3
  203. package/dist/chunk-ydjfar14.js +0 -2
  204. package/dist/chunk-z6d0jmjb.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{h,je,wt,Be,Fe,ee,M,le,X,d,ve,Ji,ds,r,n,K,Kn,i,T,ue}from"./chunk-69mc2np8.js";import{J,fn,re,_,At}from"./chunk-z0g9jvv0.js";import{H,e,Tt,ln,f}from"./chunk-h0atqq82.js";import{yn,ar,cr,lr,Qe,et,tt,nt,rt,st,Ce}from"./chunk-czxt605c.js";import{Pe,ni,se,C,ri,Sr,En,me,si,ie}from"./chunk-scezfp0w.js";import{Zt,Qt}from"./chunk-pqxzp1bb.js";import{Ot}from"./chunk-x72tv2cg.js";import{Me}from"./chunk-mepdnezf.js";import{o}from"./chunk-fzapbw9p.js";import{O}from"./chunk-px7fvbj6.js";async function Xn(t){try{let s=await Bun.file(t).text(),a=Gn(s),p=Jn(s,t),c=Yn(s,a),l=Qn(s,a);return{file:t,metrics:a,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Gn(t){let s=t.split(`
2
+ import{h,je,xt,Be,Fe,ee,M,le,X,d,ve,Yi,ps,r,n,K,Gn,i,T,ue}from"./chunk-dg1n3g1d.js";import{J,gn,re,_,Pt}from"./chunk-c4bkj1xw.js";import{H,e,_t,un,f}from"./chunk-26j2q9rq.js";import{Qe,bn,cr,lr,ur,et,tt,nt,rt,st,it,Ce}from"./chunk-rhw7pqhy.js";import{Pe,ri,se,C,si,kr,Tn,me,ii,ie}from"./chunk-gyv1t0f0.js";import{Qt,en}from"./chunk-9fyss0yk.js";import{Mt}from"./chunk-8ygks6dx.js";import{Me}from"./chunk-y6rahx7t.js";import{o}from"./chunk-ty7t3gp4.js";import{O}from"./chunk-2qa7hjp2.js";async function Xn(t){try{let s=await Bun.file(t).text(),a=Jn(s),p=Yn(s,t),c=Qn(s,a),l=Zn(s,a);return{file:t,metrics:a,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Jn(t){let s=t.split(`
3
3
  `),a=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(a?a[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,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,E=0;for(let R of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(R)&&!/@end/.test(R)&&!/@else/.test(R))E++,S=Math.max(S,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(R))E--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+b*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:c,complexity:x}}function Jn(t,s){let a=[],p=Xt(t,"if","endif");if(p>0)a.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Xt(t,"foreach","endforeach");if(c>0)a.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)a.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)a.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)a.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)a.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)a.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return a}function Yn(t,s){let a=[];if(s.complexity>7)a.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)a.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)a.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)a.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)a.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)a.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)a.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return a}function Qn(t,s){let a=1;if(a+=s.directives.conditionals*0.1,a+=s.directives.loops*0.5,a+=s.directives.includes*2,a+=s.expressions*0.05,a+=s.components*1,s.scriptLines>10)a+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(a>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(a*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Xt(t,s,a){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${a}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Hs(t=["**/*.stx"],s){let a=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await Xn(l);a.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=Zn(a);return{results:a,summary:c}}function Zn(t){let s=t.length,a=t.reduce((g,b)=>g+b.metrics.lines,0),p=s>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/s:0,c=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 m=s>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*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:s,totalLines:a,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as er,readFile as tr,readdir as nr,stat as Gt,writeFile as rr}from"fs/promises";import Ee 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 sn=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 Bt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function or(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ir(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function dr(t){let s=[];async function a(p){let c=await nr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await a(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await a(t),s}function pr(t,s){let a=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!a)return{};let p=a[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function ur(t,s){let a={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(y){throw Error(`${s}: failed to transpile <script client> (${y.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let y=u[1];if(sn.has(y))throw Error(`${s}: client ${rn(y)}`);let g=m.lastIndex,b=1,w="",S=!1,E=g;for(;E<l.length&&b>0;E++){let x=l[E];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(`${s}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";a[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return a}function fr(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 Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
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,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,E=0;for(let R of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(R)&&!/@end/.test(R)&&!/@else/.test(R))E++,S=Math.max(S,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(R))E--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+b*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:c,complexity:x}}function Yn(t,s){let a=[],p=Gt(t,"if","endif");if(p>0)a.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Gt(t,"foreach","endforeach");if(c>0)a.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)a.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)a.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)a.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)a.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)a.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return a}function Qn(t,s){let a=[];if(s.complexity>7)a.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)a.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)a.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)a.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)a.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)a.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)a.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return a}function Zn(t,s){let a=1;if(a+=s.directives.conditionals*0.1,a+=s.directives.loops*0.5,a+=s.directives.includes*2,a+=s.expressions*0.05,a+=s.components*1,s.scriptLines>10)a+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(a>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(a*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Gt(t,s,a){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${a}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Vs(t=["**/*.stx"],s){let a=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await Xn(l);a.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(a);return{results:a,summary:c}}function er(t){let s=t.length,a=t.reduce((g,b)=>g+b.metrics.lines,0),p=s>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/s:0,c=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 m=s>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*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:s,totalLines:a,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Jt,writeFile as sr}from"fs/promises";import Ee from"path";function sn(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 or(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ft(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 dr(t){let s=[];async function a(p){let c=await rr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await a(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await a(t),s}function pr(t,s){let a=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!a)return{};let p=a[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function fr(t,s){let a={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(y){throw Error(`${s}: failed to transpile <script client> (${y.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let y=u[1];if(on.has(y))throw Error(`${s}: client ${sn(y)}`);let g=m.lastIndex,b=1,w="",S=!1,E=g;for(;E<l.length&&b>0;E++){let x=l[E];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(`${s}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";a[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return a}function gr(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 Yt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
6
6
 
7
- `)}function yr(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 br(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 xr(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 vr(t){let s=[],a=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(y)=>{if(p[y]!=="(")return null;let g=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(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)s.push(`out += ${JSON.stringify(y.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<y.length)s.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=c.exec(p)){u(p.slice(a,l.index)),a=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(a):null;if(g)a=g.end,c.lastIndex=g.end;let b=g?.expression;switch(l[1]){case"if":s.push(`if (${b}) {`);break;case"elseif":s.push(`} else if (${b}) {`);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((b||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${b})`:""))};`);break}let[,S,E,v]=w;s.push(E?`for (const [${E}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(a)),s.join(`
8
- `)}function yt(t,s,a,p){if(t[s]!==a)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===a)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function jt(t,s,a){let p=a?"([{<":"([{",c=a?")]}>":")]}",l=[],m=0,u=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))m++;else if(c.includes(b))m--;if(m===0&&s.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function wr(t){let s=0,a=null;for(let p=0;p<t.length;p++){let c=t[p];if(a){if(c==="\\"){p++;continue}if(c===a)a=null;continue}if(c==="'"||c==='"'||c==="`"){a=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Yt(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 kr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let a=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=a.exec(t);k&&k.index<s.index;k=a.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=yt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let E="";if(y(),t[u]==="<"){let k=yt(t,u,"<",">");if(k===-1)return null;E=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=yt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=yt(t,u,"{","}");if(k===-1)return null;for(let[F,L]of Ht(t.slice(u,k)))l[F]=L;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let R=/^[A-Za-z_$][\w$]*$/.test(E)?E:void 0;if(E.startsWith("{"))for(let k of jt(E.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let F=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(F)c[F[1]]=F[2].trim()}if(x.startsWith("{"))for(let[k,F]of Ht(x)){if(m.push(k),!F.startsWith("{")){let L=Yt(F);if(L)c[k]=L;continue}for(let[L,j]of Ht(F))if(L==="default")l[k]=j;else if(L==="type"){let P=Yt(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of jt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of jt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let F=wr(k),j=(F===-1?k:k.slice(0,F)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),F!==-1)l[j]=k.slice(F+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:R}}function Ht(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),a=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",y=p;while(p<s.length){let b=s[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")m++;else if(b==="}"||b==="]"||b===")")m--;else if(b===","&&m===0)break;p++}let g=s.slice(y,p).trim();if(g)a.push([l[1],g]);p++}return a}function Tr(t,s,a){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],y={},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*['"])(\.[^'"]*)(['"])/,(E,v,x,R)=>{let k=Ee.resolve(Ee.dirname(s),x),F=Ee.relative(a,k);return`${v}${F.startsWith(".")?F:`./${F}`}${R}`})),""});let b=kr(l);if(b)u.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 E=[];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(),E.push(v[1]);w[S[1]]=E}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:y,declared:g}}function $r(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let y=c.toLowerCase();s.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Cr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Rr(t){let s=new Set;for(let a of t.matchAll(/<slot\b([^>]*)>/gi))s.add(a[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((a)=>({name:a}))}function Er(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 Pr(t,s,a){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await tr(p,"utf8"),l=pr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||sr(m),y=`${Bt(a.prefix||"stx")}-${Bt(m)}`,g=s.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!or(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([L,j])=>[L,en(L,j)])),S=$r(fr(c)),E=Cr(S.template),v=Tr(c,p,Ee.resolve(a.outputDir)),x=vr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=en(L,{type:yr(v.declared[L])??br(j),...j===void 0?{}:{default:xr(j)}})}let R=l.methods||{},k=s.methods||{},F=ur(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:Jt(c),shadowMode:ir(s.shadowDOM??l.shadowDOM??a.shadowDOM),progressive:s.progressive??l.progressive??a.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...R,...k,...F},eventTypes:S.eventTypes,bindings:E.bindings,slots:Rr(E.template),cssProperties:Er(Jt(c)),scope:v,render:x}}function Ar(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
7
+ `)}function br(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 xr(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 vr(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 wr(t){let s=[],a=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(y)=>{if(p[y]!=="(")return null;let g=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(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)s.push(`out += ${JSON.stringify(y.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<y.length)s.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=c.exec(p)){u(p.slice(a,l.index)),a=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(a):null;if(g)a=g.end,c.lastIndex=g.end;let b=g?.expression;switch(l[1]){case"if":s.push(`if (${b}) {`);break;case"elseif":s.push(`} else if (${b}) {`);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((b||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${b})`:""))};`);break}let[,S,E,v]=w;s.push(E?`for (const [${E}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(a)),s.join(`
8
+ `)}function bt(t,s,a,p){if(t[s]!==a)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===a)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Ht(t,s,a){let p=a?"([{<":"([{",c=a?")]}>":")]}",l=[],m=0,u=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))m++;else if(c.includes(b))m--;if(m===0&&s.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function Sr(t){let s=0,a=null;for(let p=0;p<t.length;p++){let c=t[p];if(a){if(c==="\\"){p++;continue}if(c===a)a=null;continue}if(c==="'"||c==='"'||c==="`"){a=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function 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 Tr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let a=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=a.exec(t);k&&k.index<s.index;k=a.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let E="";if(y(),t[u]==="<"){let k=bt(t,u,"<",">");if(k===-1)return null;E=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=bt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=bt(t,u,"{","}");if(k===-1)return null;for(let[F,L]of Bt(t.slice(u,k)))l[F]=L;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let R=/^[A-Za-z_$][\w$]*$/.test(E)?E:void 0;if(E.startsWith("{"))for(let k of Ht(E.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let F=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(F)c[F[1]]=F[2].trim()}if(x.startsWith("{"))for(let[k,F]of Bt(x)){if(m.push(k),!F.startsWith("{")){let L=Zt(F);if(L)c[k]=L;continue}for(let[L,j]of Bt(F))if(L==="default")l[k]=j;else if(L==="type"){let P=Zt(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of Ht(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of Ht(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let F=Sr(k),j=(F===-1?k:k.slice(0,F)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),F!==-1)l[j]=k.slice(F+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:R}}function Bt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),a=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",y=p;while(p<s.length){let b=s[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")m++;else if(b==="}"||b==="]"||b===")")m--;else if(b===","&&m===0)break;p++}let g=s.slice(y,p).trim();if(g)a.push([l[1],g]);p++}return a}function $r(t,s,a){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],y={},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*['"])(\.[^'"]*)(['"])/,(E,v,x,R)=>{let k=Ee.resolve(Ee.dirname(s),x),F=Ee.relative(a,k);return`${v}${F.startsWith(".")?F:`./${F}`}${R}`})),""});let b=Tr(l);if(b)u.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 E=[];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(),E.push(v[1]);w[S[1]]=E}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:y,declared:g}}function Cr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let y=c.toLowerCase();s.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Rr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Er(t){let s=new Set;for(let a of t.matchAll(/<slot\b([^>]*)>/gi))s.add(a[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((a)=>({name:a}))}function Pr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function tn(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 Ar(t,s,a){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await nr(p,"utf8"),l=pr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||or(m),y=`${Ft(a.prefix||"stx")}-${Ft(m)}`,g=s.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!ir(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([L,j])=>[L,tn(L,j)])),S=Cr(gr(c)),E=Rr(S.template),v=$r(c,p,Ee.resolve(a.outputDir)),x=wr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=tn(L,{type:br(v.declared[L])??xr(j),...j===void 0?{}:{default:vr(j)}})}let R=l.methods||{},k=s.methods||{},F=fr(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:Yt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??a.shadowDOM),progressive:s.progressive??l.progressive??a.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...R,...k,...F},eventTypes:S.eventTypes,bindings:E.bindings,slots:Er(E.template),cssProperties:Pr(Yt(c)),scope:v,render:x}}function Or(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -303,7 +303,7 @@ export function defineComponent(Component, definition) {
303
303
  }
304
304
  return Component;
305
305
  }
306
- `}function Or(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),a=Object.entries(t.methods).map(([u,y])=>{if(sn.has(u))throw Error(`${t.sourcePath}: ${rn(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
306
+ `}function Dr(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),a=Object.entries(t.methods).map(([u,y])=>{if(on.has(u))throw Error(`${t.sourcePath}: ${sn(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
307
307
  ${y}
308
308
  }`}).join(`
309
309
 
@@ -328,8 +328,8 @@ ${a}${m}
328
328
 
329
329
  defineComponent(${t.name}, ${s});
330
330
  export default ${t.name};
331
- `}function bt(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 Dr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${bt(m)}`).join(`
332
- `),a=Object.entries(t.properties).map(([l,m])=>` ${l}: ${bt(m)}`).join(`
331
+ `}function vt(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 Mr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${vt(m)}`).join(`
332
+ `),a=Object.entries(t.properties).map(([l,m])=>` ${l}: ${vt(m)}`).join(`
333
333
  `),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
334
334
  `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
335
335
  `);return`export interface ${t.name}Props {
@@ -355,10 +355,10 @@ declare global {
355
355
  }
356
356
 
357
357
  export default ${t.name}
358
- `}function Mr(t){return`declare global {
358
+ `}function _r(t){return`declare global {
359
359
  namespace JSX {
360
360
  interface IntrinsicElements {
361
- ${t.map((a)=>{let p=Object.entries(a.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${bt(m)}`).join(`
361
+ ${t.map((a)=>{let p=Object.entries(a.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${vt(m)}`).join(`
362
362
  `),c=Object.keys(a.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${a.events[l].detailType||"unknown"}>) => void`).join(`
363
363
  `);return` ${JSON.stringify(a.tag)}: {
364
364
  ${p}
@@ -374,9 +374,9 @@ ${c}
374
374
  }
375
375
 
376
376
  export {}
377
- `}function _r(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(([a,p])=>({kind:"field",name:a,description:p.description,type:{text:bt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Bt(a),reflects:p.reflect})),events:Object.entries(s.events).map(([a,p])=>({name:a,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function 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}) {
377
+ `}function Lr(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(([a,p])=>({kind:"field",name:a,description:p.description,type:{text:vt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ft(a),reflects:p.reflect})),events:Object.entries(s.events).map(([a,p])=>({name:a,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function nn(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
378
  ${s}
379
- }`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Lr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),a=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
379
+ }`}function rn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Ir(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),a=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
380
380
  `);return`const definitions = ${JSON.stringify(c,null,2)};
381
381
  const escapeHTML = (value) => String(value ?? '')
382
382
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -410,21 +410,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
410
410
  }
411
411
 
412
412
  ${l}
413
- `}async function Vs(t){let s=Ee.resolve(t.inputDir),a=Ee.resolve(t.outputDir);if(!(await Gt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await dr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Pr(s,x,t)));l.sort((x,R)=>x.tag.localeCompare(R.tag));let m=l.filter((x,R)=>l.findIndex((k)=>k.tag===x.tag)!==R);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,R)=>l.findIndex((k)=>k.name===x.name)!==R);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await er(a,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(a,x);return await rr(k,R.endsWith(`
413
+ `}async function Us(t){let s=Ee.resolve(t.inputDir),a=Ee.resolve(t.outputDir);if(!(await Jt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await dr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Ar(s,x,t)));l.sort((x,R)=>x.tag.localeCompare(R.tag));let m=l.filter((x,R)=>l.findIndex((k)=>k.tag===x.tag)!==R);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,R)=>l.findIndex((k)=>k.name===x.name)!==R);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await tr(a,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(a,x);return await sr(k,R.endsWith(`
414
414
  `)?R:`${R}
415
- `,"utf8"),y.push(k),k};await g("runtime.js",Ar());for(let x of l){if(await g(`${x.tag}.js`,Or(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Dr(x));if(t.css!==!1&&x.styles){let R=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(R):R)}}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",Lr(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",Mr(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(`
415
+ `,"utf8"),y.push(k),k};await g("runtime.js",Or());for(let x of l){if(await g(`${x.tag}.js`,Dr(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Mr(x));if(t.css!==!1&&x.styles){let R=x.shadowMode?x.styles:nn(x);await g(`${x.tag}.css`,t.minify?rn(R):R)}}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",Ir(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",_r(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(_r(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(tn).join(`
421
+ `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(Lr(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(nn).join(`
422
422
 
423
- `);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(a,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(a,"index.js")],outdir:a,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(R){let k=R instanceof AggregateError?R.errors:[R],F=k.map((L)=>String(L).trim()).filter(Boolean).join(`
423
+ `);if(x)S=await g("bundle.css",t.minify?rn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(a,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(a,"index.js")],outdir:a,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(R){let k=R instanceof AggregateError?R.errors:[R],F=k.map((L)=>String(L).trim()).filter(Boolean).join(`
424
424
  `);throw AggregateError(k,`Failed to bundle component library${F?`
425
425
  ${F}`:""}`)}if(!x.success){let R=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
426
  `);throw AggregateError(x.logs,`Failed to bundle component library${R?`
427
- ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await Gt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(a,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}var{serve:Wr}=globalThis.Bun;import zt from"fs";import dt from"path";function xt(){return`
427
+ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await Jt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(a,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}var{serve:Vr}=globalThis.Bun;import Nt from"fs";import pt from"path";function wt(){return`
428
428
  /* Theme selector for code blocks */
429
429
  .theme-selector {
430
430
  margin: 1rem 0;
@@ -474,13 +474,13 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
474
474
 
475
475
  body.dark-mode a {
476
476
  color: #58a6ff;
477
- }`}function vt(t){return`
477
+ }`}function St(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 kt(){return`
484
484
  function changeTheme() {
485
485
  const theme = document.getElementById('themeSelector').value;
486
486
 
@@ -496,7 +496,7 @@ 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 Tt(t){if(Object.keys(t).length===0)return"";return`
500
500
  <div class="frontmatter">
501
501
  <h3>Frontmatter</h3>
502
502
  ${Object.entries(t).map(([s,a])=>`
@@ -504,19 +504,19 @@ else {
504
504
  <span class="frontmatter-label">${s}:</span>
505
505
  <span>${Array.isArray(a)?a.join(", "):String(a)}</span>
506
506
  </div>`).join("")}
507
- </div>`}import on from"net";async function Ir(t){return new Promise((s)=>{let a=on.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"0.0.0.0")})}async function jr(t){return new Promise((s)=>{let a=on.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"::")})}async function Hr(t){if(!await Ir(t))return!1;return await jr(t)}async function Ye(t,s=20){t=Number(t);for(let a=0;a<s;a++){let p=t+a;if(await Hr(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Br={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Fr(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function lt(t,s={}){let a={...Br,...s},p=await Fr();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:a.title,width:a.width,height:a.height,darkMode:a.darkMode,hotReload:a.hotReload,titlebarHidden:a.titlebarHidden,nativeSidebar:a.nativeSidebar,sidebarWidth:a.sidebarWidth,sidebarConfig:a.sidebarConfig});if(c&&a.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 $t(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 an from"net";async function jr(t){return new Promise((s)=>{let a=an.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let a=an.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function Ye(t,s=20){t=Number(t);for(let a=0;a<s;a++){let p=t+a;if(await Br(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Fr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function zr(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let a={...Fr,...s},p=await zr();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:a.title,width:a.width,height:a.height,darkMode:a.darkMode,hotReload:a.hotReload,titlebarHidden:a.titlebarHidden,nativeSidebar:a.nativeSidebar,sidebarWidth:a.sidebarWidth,sidebarConfig:a.sidebarConfig});if(c&&a.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 $t(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=`
508
508
  ${l}
509
509
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
- `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let a=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(a)try{return JSON.parse(a[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ft(){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 zr(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`),Ft()}function Nr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ze(t,s,a){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ft();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(a?.onQuit)a.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
512
- `)){let l=p.trim().toLowerCase();p="",Ur(l,t,s,a)}})}function Ur(t,s,a,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Nr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),zr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),a(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ft();break;default:break}}async function Nt(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=dt.resolve(t);if(!zt.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 ue(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),E=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,v=E?.defaultTheme||"github-dark",x=["github-dark"],R=E?.additionalThemes||[],F=[...new Set([...x,...R])].map((L)=>`<option value="${L}"${L===v?" selected":""}>${L}</option>`).join(`
510
+ `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let a=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(a)try{return JSON.parse(a[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function zt(){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 Nr(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`),zt()}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 Ze(t,s,a){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(a?.onQuit)a.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
512
+ `)){let l=p.trim().toLowerCase();p="",Wr(l,t,s,a)}})}function Wr(t,s,a,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ur(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Nr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),a(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Nt.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 ue(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),E=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,v=E?.defaultTheme||"github-dark",x=["github-dark"],R=E?.additionalThemes||[],F=[...new Set([...x,...R])].map((L)=>`<option value="${L}"${L===v?" selected":""}>${L}</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>${Vr(S.title||dt.basename(c))}</title>
519
+ <title>${qr(S.title||pt.basename(c))}</title>
520
520
  <!-- Syntax highlighting styles -->
521
521
  <style id="syntax-theme">
522
522
  :root {
@@ -658,26 +658,26 @@ 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
- ${xt()}
661
+ ${wt()}
662
662
  </style>
663
663
  </head>
664
664
  <body>
665
- ${kt(S)}
666
- ${vt(F)}
665
+ ${Tt(S)}
666
+ ${St(F)}
667
667
 
668
668
  ${w}
669
669
 
670
670
  <script>
671
- ${St()}
671
+ ${kt()}
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 y=a;try{if(y=await Ye(a),y!==a)console.log(`${e.yellow}Port ${a} 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=Wr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
675
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let y=a;try{if(y=await Ye(a),y!==a)console.log(`${e.yellow}Port ${a} 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=Vr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
676
676
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
677
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
678
678
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
679
- ${e.yellow}Routes:${e.reset}`);let b=dt.relative(process.cwd(),c);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`),Ze(g.url.toString(),()=>{if(p)zt.watch(dt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await lt(y,{title:dt.basename(c,".md")});if(p){let w=dt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=zt.watch(w,{recursive:!0},async(E,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 Vr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Kr}=globalThis.Bun;import Ne from"fs";import we 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,a=20;for(let p=0;p<a;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${a} 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),a=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),a++}catch{this.clients.delete(p)}if(this.options.verbose&&a>0)console.log(`[HMR] Broadcast ${t.type} to ${a} 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 qr(t,s={}){let{showOverlay:a=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
679
+ ${e.yellow}Routes:${e.reset}`);let b=pt.relative(process.cwd(),c);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`),Ze(g.url.toString(),()=>{if(p)Nt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(y,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Nt.watch(w,{recursive:!0},async(E,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 Ne from"fs";import we from"path";class cn{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,a=20;for(let p=0;p<a;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${a} 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),a=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),a++}catch{this.clients.delete(p)}if(this.options.verbose&&a>0)console.log(`[HMR] Broadcast ${t.type} to ${a} 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:a=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function Xe(t,s,a={}){let p=qr(s,a),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Et(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((a)=>a.test(t))}var pt=null;function Pt(t){if(!pt)pt=new an(t);return pt}function gt(){if(pt)pt.stop(),pt=null}import Dt from"path";var ut={name:"bun-plugin-stx",async setup(t){let a={...await i(),...t.config?.stx},p=new Set,c=a.webComponents?.enabled?`./${Dt.relative(Dt.dirname(t.config?.outdir||"dist"),a.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(a.webComponents?.enabled)try{let m=await Kn(a,p);if(l.push(...m),a.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(a.cache&&a.cachePath){let x=await Zt(m,a);if(x){if(a.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await re(()=>Bun.file(m).text(),"",(x)=>{throw new fn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=H.time("script-extraction",()=>{let x=y,R=ee(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],F="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",z=P.match(/<script\b([^>]*)>/i),G=z?z[1]:"";if(/\bserver\b/i.test(G))F=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:F,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:Dt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await re(()=>d(g,S,m),void 0,(x)=>{let R=new J(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),a.debug)throw R});let v=await H.timeAsync("directive-processing",async()=>await r(b,S,m,a,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-mhq0pjws.js"),R=x(w.join(`
879
+ `}function Xe(t,s,a={}){let p=Kr(s,a),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Et(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((a)=>a.test(t))}var ut=null;function At(t){if(!ut)ut=new cn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Ot from"path";var ft={name:"bun-plugin-stx",async setup(t){let a={...await i(),...t.config?.stx},p=new Set,c=a.webComponents?.enabled?`./${Ot.relative(Ot.dirname(t.config?.outdir||"dist"),a.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(a.webComponents?.enabled)try{let m=await Gn(a,p);if(l.push(...m),a.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(a.cache&&a.cachePath){let x=await Qt(m,a);if(x){if(a.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await re(()=>Bun.file(m).text(),"",(x)=>{throw new gn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new gn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=H.time("script-extraction",()=>{let x=y,R=ee(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],F="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",z=P.match(/<script\b([^>]*)>/i),G=z?z[1]:"";if(/\bserver\b/i.test(G))F=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:F,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:Ot.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await re(()=>d(g,S,m),void 0,(x)=>{let R=new J(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),a.debug)throw R});let v=await H.timeAsync("directive-processing",async()=>await r(b,S,m,a,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-5y1mekxe.js"),R=x(w.join(`
880
880
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+R+`
881
881
  `+v.slice(k);else v+=`
882
- ${R}`}if(v=await X(v),u.forEach((x)=>p.add(x)),a.cache&&a.cachePath){if(await Qt(m,v,u,a),a.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new J(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),At.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),a.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:a.debug||O()?`<!DOCTYPE html>
882
+ ${R}`}if(v=await X(v),u.forEach((x)=>p.add(x)),a.cache&&a.cachePath){if(await en(m,v,u,a),a.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new J(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),Pt.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),a.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:a.debug||O()?`<!DOCTYPE html>
883
883
  <html lang="en">
884
884
  <head>
885
885
  <meta charset="UTF-8">
@@ -920,7 +920,7 @@ ${R}`}if(v=await X(v),u.forEach((x)=>p.add(x)),a.cache&&a.cachePath){if(await Qt
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 ${h(Dt.basename(m))}</code> for detailed analysis</li>
923
+ <li>Run <code>stx debug ${h(Ot.basename(m))}</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 @@ ${R}`}if(v=await X(v),u.forEach((x)=>p.add(x)),a.cache&&a.cachePath){if(await Qt
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 wn(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=we.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Nt(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=o(process.cwd(),"output");Ne.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let I={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},z=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ut],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return console.error(`${e.red}Build failed:${e.reset}`,z.logs),!1;let G=z.outputs.find((Te)=>Te.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=we.dirname(u);await Tt(S);let E=a;try{if(E=await Ye(a),E!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||E+1;l=Pt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-48bwk47q.js"),z=await I();if(R=s.stxOptions?.serverApi??z.serverApi,z?.apiRouter)x=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){v=z.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:te}=await import("./chunk-dgdm3hy3.js"),Te=z.broadcasting;await G(Te);let he=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=we.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let ae=await te(Oe);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:F}=await import("./chunk-5g3y8kym.js"),L=await k(process.cwd(),R);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Kr({port:E,async fetch(I){return Ot(I,await(async()=>{let z=new URL(I.url);if([y,we.dirname(u),we.join(process.cwd(),"public")].some((ae)=>F(we.join(ae,z.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(I);if(ae.status!==404)return ae}catch{}if(v[z.pathname])try{return await v[z.pathname](I)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(z.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let te=we.join(y,z.pathname);if(Ne.existsSync(te)&&Ne.statSync(te).isFile()){let ae=Bun.file(te),W=we.extname(te).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Te=we.dirname(u),he=we.join(Te,z.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let ae=Bun.file(he),W=we.extname(he).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Oe=we.join(process.cwd(),"public",z.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let ae=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),B="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
942
+ </html>`,loader:"html"}}})}};async function xn(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=we.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ut(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=o(process.cwd(),"output");Ne.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let I={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},z=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return console.error(`${e.red}Build failed:${e.reset}`,z.logs),!1;let G=z.outputs.find((Te)=>Te.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=we.dirname(u);await _t(S);let E=a;try{if(E=await Ye(a),E!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||E+1;l=At({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-yxfx44fv.js"),z=await I();if(R=s.stxOptions?.serverApi??z.serverApi,z?.apiRouter)x=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){v=z.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:te}=await import("./chunk-gr3r9xdh.js"),Te=z.broadcasting;await G(Te);let he=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=we.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let ae=await te(Oe);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:F}=await import("./chunk-gp1bhn7t.js"),L=await k(process.cwd(),R);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Xr({port:E,async fetch(I){return Mt(I,await(async()=>{let z=new URL(I.url);if([y,we.dirname(u),we.join(process.cwd(),"public")].some((ae)=>F(we.join(ae,z.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(I);if(ae.status!==404)return ae}catch{}if(v[z.pathname])try{return await v[z.pathname](I)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(z.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let te=we.join(y,z.pathname);if(Ne.existsSync(te)&&Ne.statSync(te).isFile()){let ae=Bun.file(te),W=we.extname(te).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Te=we.dirname(u),he=we.join(Te,z.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let ae=Bun.file(he),W=we.extname(he).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Oe=we.join(process.cwd(),"public",z.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let ae=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),B="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
943
943
  ${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
944
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
945
945
  ${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
946
946
  ${e.yellow}Routes:${e.reset}`);let P=we.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${P}${e.reset}`),console.log(`
947
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(j.url.toString(),()=>{if(p)Ne.watch(we.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),z=$t(I);await lt(E,{title:we.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!z,sidebarConfig:z})}if(p){let I=we.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let z=Ne.watch(I,{recursive:!0},async(G,te)=>{if(!te||Et(te))return;if(Rt(te)){console.log(`${e.yellow}File ${e.bright}${te}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K();let Te=await b();if(await ln(S),c&&l)if(Te)l.reload(te);else l.error("Build failed - check console for details")}else if(Ct(te)){if(console.log(`${e.cyan}CSS ${e.bright}${te}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(te)}});process.on("SIGINT",()=>{if(z.close(),l)gt();j.stop(),process.exit(0)})}return!0}var{serve:Xr}=globalThis.Bun;import ot from"fs";import Ae from"path";var cn=`
947
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(j.url.toString(),()=>{if(p)Ne.watch(we.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),z=$t(I);await dt(E,{title:we.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!z,sidebarConfig:z})}if(p){let I=we.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let z=Ne.watch(I,{recursive:!0},async(G,te)=>{if(!te||Et(te))return;if(Rt(te)){console.log(`${e.yellow}File ${e.bright}${te}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K();let Te=await b();if(await un(S),c&&l)if(Te)l.reload(te);else l.error("Build failed - check console for details")}else if(Ct(te)){if(console.log(`${e.cyan}CSS ${e.bright}${te}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(te)}});process.on("SIGINT",()=>{if(z.close(),l)ht();j.stop(),process.exit(0)})}return!0}var{serve:Gr}=globalThis.Bun;import ot from"fs";import Ae from"path";var ln=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,7 +1255,7 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function pn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),a=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))a.push(c);else break}return a.join(Ae.sep)}async function xn(t,s={}){let a=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!ot.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=o(process.cwd(),"output");ot.mkdirSync(c,{recursive:!0});let l=pn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],y=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:F}=await ue(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,j=L?.defaultTheme||"github-dark",P=["github-dark"],I=L?.additionalThemes||[],G=[...new Set([...P,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
1258
+ `;function pn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),a=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))a.push(c);else break}return a.join(Ae.sep)}async function Sn(t,s={}){let a=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!ot.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=o(process.cwd(),"output");ot.mkdirSync(c,{recursive:!0});let l=pn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],y=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:F}=await ue(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,j=L?.defaultTheme||"github-dark",P=["github-dark"],I=L?.additionalThemes||[],G=[...new Set([...P,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
1259
1259
  `),te=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
@@ -1404,40 +1404,40 @@ else {
1404
1404
  min-width: 100px;
1405
1405
  color: #555;
1406
1406
  }
1407
- ${xt()}
1407
+ ${wt()}
1408
1408
  </style>
1409
1409
  </head>
1410
1410
  <body>
1411
- ${kt(F)}
1412
- ${vt(G)}
1411
+ ${Tt(F)}
1412
+ ${St(G)}
1413
1413
 
1414
1414
  ${k}
1415
1415
 
1416
1416
  <script>
1417
- ${St()}
1417
+ ${kt()}
1418
1418
  </script>
1419
1419
  </body>
1420
1420
  </html>
1421
- `,he=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:te,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(P){P.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},F;try{let P=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ut],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!P.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Me(P.logs,x));continue}let I=P.outputs.find((z)=>z.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}F=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
- ${Me(P,x)}`);continue}let j=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=ar(j);u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:F,fileType:"stx"}}else m[j||"/"]={filePath:x,content:F,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}`,Me(v)),!1}};if(!await y())return!1;let b=a;try{if(b=await Ye(a),b!==a)console.log(`${e.yellow}Port ${a} 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=Xr({port:b,async fetch(v){let x=new URL(v.url),R=Ae.join(process.cwd(),"public",x.pathname);if(ot.existsSync(R)&&ot.statSync(R).isFile()){let L=Bun.file(R),j=Ae.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),z=await L.text(),G=I.transformSync(z);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let L of u){let j=x.pathname.match(L.pattern);if(j){let P=m[L.routeTemplate];if(P){let I={};for(let te=0;te<L.paramNames.length;te++)I[L.paramNames[te]]=decodeURIComponent(j[te+1]);let z=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(z.includes("</head>"))z=z.replace("</head>",`${G}
1423
- </head>`);else z=G+z;k={...P,content:z}}break}}if(k)return f(k.content).then((L)=>{if(L.includes("</head>"))L=L.replace("</head>",`${cn}
1421
+ `,he=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:te,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(P){P.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},F;try{let P=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!P.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Me(P.logs,x));continue}let I=P.outputs.find((z)=>z.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}F=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${Me(P,x)}`);continue}let j=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=cr(j,{page:!0});u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:F,fileType:"stx"}}else m[j||"/"]={filePath:x,content:F,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}`,Me(v)),!1}};if(!await y())return!1;let b=a;try{if(b=await Ye(a),b!==a)console.log(`${e.yellow}Port ${a} 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=Gr({port:b,async fetch(v){let x=new URL(v.url),R=Ae.join(process.cwd(),"public",x.pathname);if(ot.existsSync(R)&&ot.statSync(R).isFile()){let L=Bun.file(R),j=Ae.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),z=await L.text(),G=I.transformSync(z);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let L of u){let j=x.pathname.match(L.pattern);if(j){let P=m[L.routeTemplate];if(P){let I={};for(let te=0;te<L.paramNames.length;te++)I[L.paramNames[te]]=decodeURIComponent(j[te+1]);let z=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(z.includes("</head>"))z=z.replace("</head>",`${G}
1423
+ </head>`);else z=G+z;k={...P,content:z}}break}}if(k)return f(k.content).then((L)=>{if(L.includes("</head>"))L=L.replace("</head>",`${ln}
1424
1424
  </head>`);return new Response(L,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let F=Ae.join(c,x.pathname);if(ot.existsSync(F)&&ot.statSync(F).isFile()){let L=Bun.file(F),j=Ae.extname(F).toLowerCase(),P="text/plain";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),z=await L.text(),G=I.transformSync(z);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}if(x.pathname!=="/"&&m["/"]){let L=se(v);return f(m["/"].content).then((j)=>{if(L){let P=j.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(P){let I=j.match(/<title[^>]*>([\s\S]*?)<\/title>/i),z=I?I[1]:"",G=`<!DOCTYPE html><html><head><title>${dn(z)}</title></head><body><main>${P[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...C(),"Cache-Control":Pe,Pragma:"no-cache",Expires:"0"}})}}return new Response(j,{headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1425
1425
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1426
1426
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1427
1427
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1428
1428
  ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),E=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");E.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(E.sort((v,x)=>v.route.localeCompare(x.route)),E.forEach((v,x)=>{let k=x===E.length-1?"\u2514\u2500 ":"\u251C\u2500 ",F=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${F}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(p)ot.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=ot.watch(l,{recursive:!0},async(x,R)=>{if(!R)return;if(R.endsWith(".stx")||R.endsWith(".js")||R.endsWith(".ts")||R.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${R}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function dn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gr}=globalThis.Bun;import be from"fs";import oe from"path";async function un(t){try{return wt(await Bun.file(t).text())}catch{return}}function Ut(t){let s=Bun.file(t),a=oe.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(a)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[a]||"application/octet-stream",...l}})}async function Sn(t=".",s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=oe.resolve(t),{loadStxConfig:y}=await import("./chunk-48bwk47q.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-5g3y8kym.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?oe.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",R=oe.join(v,x);if(!be.existsSync(R)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${R}${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=M(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[R,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${R}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let F=g?._pluginPageDirs||[],L=[];for(let{dir:A,prefix:N}of F)if(be.existsSync(A)){let U=M(oe.dirname(A),{pagesDir:oe.basename(A)});for(let V of U){let xe=N==="/"?V.pattern:`${N}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:xe},prefix:N})}if(U.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${U.length}${e.blue} routes at ${e.cyan}${N}${e.reset}`)}let j=new Map,P=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await ri(u,s.stxOptions?.shell),I){if(P=await Sr(I,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let z=et();if(z.length>0)console.log(`${e.blue}Loaded ${e.bright}${z.length}${e.blue} middleware: ${e.dim}${z.join(", ")}${e.reset}`);let G={},te=null;try{let{loadStxConfig:A}=await import("./chunk-48bwk47q.js"),N=await A(u);if(N?.apiRouter)te=N?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(N?.apiRoutes){G=N.apiRoutes;let U=Object.keys(G).length;if(U>0)console.log(`${e.blue}Loaded ${e.bright}${U} API route${U>1?"s":""}${e.reset}`)}if(N?.broadcasting?.enabled)try{let{startBroadcasting:U,loadChannels:V}=await import("./chunk-dgdm3hy3.js"),xe=N.broadcasting;await U(xe);let We=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=oe.join(process.cwd(),"channels.ts");if(be.existsSync(Ge))try{let ne=await V(Ge);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(U){console.warn(`${e.yellow}Broadcasting failed to start: ${U.message}${e.reset}`)}}catch{}let Te=o(u,"output");be.mkdirSync(Te,{recursive:!0});let he=new Map,Oe=new Set,ae=async(A)=>{let N=cr(R,A);if(!N)return null;try{let U=await Bun.build({entrypoints:[N],outdir:Te,plugins:[ut],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!U.success)return null;let V=U.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,B=async(A,N)=>{try{let{processDirectives:U,extractVariables:V,defaultConfig:xe,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-48bwk47q.js"),{checkCache:ne,cacheTemplate:Z,readFileCached:q,templateCache:Y}=await import("./chunk-s2x4wcrz.js"),Se=await We(u),Je=(ce)=>{if(!ce)return ce;if(oe.isAbsolute(ce))return ce;return oe.resolve(u,ce)},D={...xe,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)D.debug=!0;D.partialsDir=Je(D.partialsDir),D.componentsDir=Je(D.componentsDir),D.layoutsDir=Je(D.layoutsDir),D.storesDir=Je(D.storesDir||"stores"),D.cachePath=Je(D.cachePath)??o(u,"cache");let ye=!N&&!s.profile,de=D.cache!==!1;if(de&&ye){let ce=Y.get(A.filePath);if(ce)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=ce.mtime){let ze=!0;for(let Re of ce.dependencies){if(!be.existsSync(Re)){ze=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>ce.mtime){ze=!1;break}}if(ze){let Re=ce.output;if(P)Re=me(Re,{preserveHead:!0});let mt=W.get(A.filePath);return{route:A,content:Re,status:mt?.status??await un(A.filePath),headers:mt?.headers}}}}catch{}let Ie=await ne(A.filePath,D);if(Ie){let He=Ie;if(P)He=me(He,{preserveHead:!0});let ze=W.get(A.filePath);return{route:A,content:He,status:ze?.status??await un(A.filePath),headers:ze?.headers}}}let ge=de?await q(A.filePath):await Bun.file(A.filePath).text(),$e=wt(ge),{classifyAllScripts:Q}=await import("./chunk-48bwk47q.js"),Le=Q(ge),Ve=Le.server.map((ce)=>ce.content),pe=ge;for(let ce of Le.server)pe=pe.replace(ce.fullTag,"");let fe={__filename:A.filePath,__dirname:oe.dirname(A.filePath),__stx_options:D,params:N??{},__stx_runtime_head:{}};for(let ce of Ve)try{await V(ce,fe,A.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Ie?.message||Ie)}let Ke=new Set,De;if(s.profile){let ce=performance.now();De=await U(pe,fe,A.filePath,D,Ke);let Ie=performance.now()-ce,He=oe.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else De=await U(pe,fe,A.filePath,D,Ke);if(!P)De=await Ge(De,{router:D.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-mhq0pjws.js");De=De.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${ce(ze,fe)}</script>`})}if(P)De=me(De,{preserveHead:!0});if(de&&ye)await Z(A.filePath,De,Ke,D);let{extractStreamBoundaries:Vn}=await import("./chunk-bmt7w2pk.js"),ct=Vn(fe),ft=fe.__streamTemplates;if(ft&&typeof ft==="object"&&Object.keys(ft).length>0){let ce=fe.streamBoundaries||{},Ie={...D,autoShell:!1},He=Object.keys(ft).map((Re)=>({id:Re,render:async()=>{let mt=typeof ce[Re]==="function"?await ce[Re]():void 0;return U(ft[Re],{...fe,$boundary:mt},A.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));ct=[...(ct||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(ct&&ct.length>0)Oe.add(A.pattern);else ct=void 0;let qt=Be(fe),Kt=Fe(fe);if(ye)W.set(A.filePath,{status:qt,headers:Kt});return{route:A,content:De,status:qt??$e,headers:Kt,boundaries:ct}}catch(U){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,U),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let A=0;A<k.length;A+=Ue){let N=k.slice(A,A+Ue),U=await Promise.all(N.map((V)=>B(V)));for(let V of U)if(V)he.set(V.route.pattern,V)}for(let A=0;A<L.length;A+=Ue){let N=L.slice(A,A+Ue),U=await Promise.all(N.map(({route:V})=>B(V)));for(let V of U)if(V)j.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Tt(u);let it=a;try{if(it=await Ye(a),it!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${it} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||it+1;l=Pt({wsPort:A,verbose:!1}),m=l.start(A)}let _t=(A,N)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(N).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>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Gr({port:it,async fetch(A){let N=new URL(A.url),U=g?.publicDir||"public",V=oe.join(u,U,N.pathname),xe=oe.join(u,N.pathname),We=oe.join(Te,N.pathname);if([V,xe,We].some((D)=>w(D,u,S)))return new Response("Not Found",{status:404});let[Ge,ne,Z]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(xe).catch(()=>null),be.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return Ut(V);if(ne?.isFile()&&!w(xe,u,S))return Ut(xe);if(Z?.isFile()&&!w(We,u,S))return Ut(We);if(N.pathname.startsWith("/_stx/component/")){let D=decodeURIComponent(N.pathname.slice(16));if(D)try{let ye=`<${D} />`,de={...buildConfig,autoShell:!1},ge=await processDirectives(ye,{},oe.join(u,"components",`${D}.stx`),de,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(N.pathname==="/_stx/img"){let{handleImageRequest:D}=await import("./chunk-q6vrb2pe.js"),ye=await D(A,{publicDir:oe.join(u,U),cacheDir:o(u,"cache","img")});if(ye)return ye}if(te)try{let D=await te.handleRequest(A);if(D.status!==404)return D}catch{}if(G[N.pathname])try{return await G[N.pathname](A)}catch(D){return new Response(JSON.stringify({error:D.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await E(A);if(q)return q;let Y=yn(N.pathname,k);if(Y){let D=he.get(Y.route.pattern),ye=Oe.has(Y.route.pattern);if(Y.route.isDynamic&&Object.keys(Y.params).length>0||ye){let de=await B(Y.route,Y.params);if(de)D=de}if(D){let de=D.status??200,ge=D.headers??{},$e=(Y.route.filePath?je(await Bun.file(Y.route.filePath).text().catch(()=>"")):null)??{};if($e.validate){if(!await $e.validate({params:Y.params})){let Ve=await ae(404);if(Ve){let pe=Ve;if(pe=await f(pe,u),c)pe=Xe(pe,m);return new Response(pe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if($e.middleware){let Le=nt(N.pathname,Y.params,$e,N.search),Ve=rt(Le,null,A,{isServer:!0}),pe=await st($e.middleware,Ve);if(pe.redirect){let fe=pe.redirect.path,Ke=pe.redirect.options.redirectCode||302,De=new Headers(pe.responseHeaders);return De.set("Location",fe),new Response(null,{status:Ke,headers:De})}if(pe.abort){let{statusCode:fe,message:Ke}=pe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(pe.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(pe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;D.content=D.content.replace("</head>",`${fe}</head>`)}}let Q=D.content;if(P&&si(A)){let Le=Ce(Q),Ve=le(Q),pe=Q.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=pe?ni(pe[1].trim()):"";if(Object.keys(Y.params).length>0)Q=_t(Q,Y.params);Q=await f(Q,u);let Ke=g?.router?.container||"main";return Q=ie(Q,Ke),new Response(Q,{status:de,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Ji]:ds(),...C(),"Cache-Control":Pe}})}if(P)Q=En(P,Q);if(Object.keys(Y.params).length>0)Q=_t(Q,Y.params);if(Q=await f(Q,u),c)Q=Xe(Q,m);if(s.native)if(Q.includes("<head>"))Q=Q.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 Q="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Q;if(s.titlebarHidden)if(Q.includes("<head>"))Q=Q.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 Q=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Q}`;if(D.boundaries&&D.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-bmt7w2pk.js");return Ve(Le(Q,D.boundaries,{timeoutMs:30000}),{status:de,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Q,{status:de,headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(L.length>0){let D=L.map((de)=>de.route),ye=yn(N.pathname,D);if(ye){let de=j.get(ye.route.pattern);if(de){let ge=de.content;if(P)ge=En(P,ge);if(Object.keys(ye.params).length>0)ge=_t(ge,ye.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:de.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:de}of F)if(de!=="/"&&N.pathname.startsWith(de)){let ge=j.get(de)||j.get(de+"/");if(ge){let $e=ge.content;if(P)$e=En(P,$e);if($e=await f($e,u),c)$e=Xe($e,m);return new Response($e,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let Se=he.get("/");if(Se){let D=Se.content;if(D=await f(D,u),c)D=Xe(D,m);if(s.native)if(D.includes("<head>"))D=D.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else D="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+D;return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let D=Je;if(D=await f(D,u),c)D=Xe(D,m);return new Response(D,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let N=await ae(500);if(N)return new Response(N,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(p)ot.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=ot.watch(l,{recursive:!0},async(x,R)=>{if(!R)return;if(R.endsWith(".stx")||R.endsWith(".js")||R.endsWith(".ts")||R.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${R}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function dn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Jr}=globalThis.Bun;import be from"fs";import oe from"path";async function fn(t){try{return xt(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),a=oe.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(a)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[a]||"application/octet-stream",...l}})}async function kn(t=".",s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=oe.resolve(t),{loadStxConfig:y}=await import("./chunk-yxfx44fv.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-gp1bhn7t.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?oe.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",R=oe.join(v,x);if(!be.existsSync(R)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${R}${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=M(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[R,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${R}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let F=g?._pluginPageDirs||[],L=[];for(let{dir:A,prefix:N}of F)if(be.existsSync(A)){let U=M(oe.dirname(A),{pagesDir:oe.basename(A)});for(let V of U){let xe=N==="/"?V.pattern:`${N}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:xe},prefix:N})}if(U.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${U.length}${e.blue} routes at ${e.cyan}${N}${e.reset}`)}let j=new Map,P=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await si(u,s.stxOptions?.shell),I){if(P=await kr(I,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}et(),await nt(u);let z=tt();if(z.length>0)console.log(`${e.blue}Loaded ${e.bright}${z.length}${e.blue} middleware: ${e.dim}${z.join(", ")}${e.reset}`);let G={},te=null;try{let{loadStxConfig:A}=await import("./chunk-yxfx44fv.js"),N=await A(u);if(N?.apiRouter)te=N?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(N?.apiRoutes){G=N.apiRoutes;let U=Object.keys(G).length;if(U>0)console.log(`${e.blue}Loaded ${e.bright}${U} API route${U>1?"s":""}${e.reset}`)}if(N?.broadcasting?.enabled)try{let{startBroadcasting:U,loadChannels:V}=await import("./chunk-gr3r9xdh.js"),xe=N.broadcasting;await U(xe);let We=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=oe.join(process.cwd(),"channels.ts");if(be.existsSync(Ge))try{let ne=await V(Ge);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(U){console.warn(`${e.yellow}Broadcasting failed to start: ${U.message}${e.reset}`)}}catch{}let Te=o(u,"output");be.mkdirSync(Te,{recursive:!0});let he=new Map,Oe=new Set,ae=async(A)=>{let N=lr(R,A);if(!N)return null;try{let U=await Bun.build({entrypoints:[N],outdir:Te,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!U.success)return null;let V=U.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,B=async(A,N)=>{try{let{processDirectives:U,extractVariables:V,defaultConfig:xe,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-yxfx44fv.js"),{checkCache:ne,cacheTemplate:Z,readFileCached:q,templateCache:Y}=await import("./chunk-5j52h3e3.js"),Se=await We(u),Je=(ce)=>{if(!ce)return ce;if(oe.isAbsolute(ce))return ce;return oe.resolve(u,ce)},D={...xe,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)D.debug=!0;D.partialsDir=Je(D.partialsDir),D.componentsDir=Je(D.componentsDir),D.layoutsDir=Je(D.layoutsDir),D.storesDir=Je(D.storesDir||"stores"),D.cachePath=Je(D.cachePath)??o(u,"cache");let ye=!N&&!s.profile,de=D.cache!==!1;if(de&&ye){let ce=Y.get(A.filePath);if(ce)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=ce.mtime){let ze=!0;for(let Re of ce.dependencies){if(!be.existsSync(Re)){ze=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>ce.mtime){ze=!1;break}}if(ze){let Re=ce.output;if(P)Re=me(Re,{preserveHead:!0});let gt=W.get(A.filePath);return{route:A,content:Re,status:gt?.status??await fn(A.filePath),headers:gt?.headers}}}}catch{}let Ie=await ne(A.filePath,D);if(Ie){let He=Ie;if(P)He=me(He,{preserveHead:!0});let ze=W.get(A.filePath);return{route:A,content:He,status:ze?.status??await fn(A.filePath),headers:ze?.headers}}}let ge=de?await q(A.filePath):await Bun.file(A.filePath).text(),$e=xt(ge),{classifyAllScripts:Q}=await import("./chunk-yxfx44fv.js"),Le=Q(ge),Ve=Le.server.map((ce)=>ce.content),pe=ge;for(let ce of Le.server)pe=pe.replace(ce.fullTag,"");let fe={__filename:A.filePath,__dirname:oe.dirname(A.filePath),__stx_options:D,params:N??{},__stx_runtime_head:{}};for(let ce of Ve)try{await V(ce,fe,A.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Ie?.message||Ie)}let Ke=new Set,De;if(s.profile){let ce=performance.now();De=await U(pe,fe,A.filePath,D,Ke);let Ie=performance.now()-ce,He=oe.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else De=await U(pe,fe,A.filePath,D,Ke);if(!P)De=await Ge(De,{router:D.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-5y1mekxe.js");De=De.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${ce(ze,fe)}</script>`})}if(P)De=me(De,{preserveHead:!0});if(de&&ye)await Z(A.filePath,De,Ke,D);let{extractStreamBoundaries:qn}=await import("./chunk-ecr598p7.js"),lt=qn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let ce=fe.streamBoundaries||{},Ie={...D,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof ce[Re]==="function"?await ce[Re]():void 0;return U(mt[Re],{...fe,$boundary:gt},A.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(lt&&lt.length>0)Oe.add(A.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(ye)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:De,status:Kt??$e,headers:Xt,boundaries:lt}}catch(U){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,U),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let A=0;A<k.length;A+=Ue){let N=k.slice(A,A+Ue),U=await Promise.all(N.map((V)=>B(V)));for(let V of U)if(V)he.set(V.route.pattern,V)}for(let A=0;A<L.length;A+=Ue){let N=L.slice(A,A+Ue),U=await Promise.all(N.map(({route:V})=>B(V)));for(let V of U)if(V)j.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await _t(u);let at=a;try{if(at=await Ye(a),at!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||at+1;l=At({wsPort:A,verbose:!1}),m=l.start(A)}let Lt=(A,N)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(N).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>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let It=Jr({port:at,async fetch(A){let N=new URL(A.url),U=g?.publicDir||"public",V=oe.join(u,U,N.pathname),xe=oe.join(u,N.pathname),We=oe.join(Te,N.pathname);if([V,xe,We].some((D)=>w(D,u,S)))return new Response("Not Found",{status:404});let[Ge,ne,Z]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(xe).catch(()=>null),be.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return Wt(V);if(ne?.isFile()&&!w(xe,u,S))return Wt(xe);if(Z?.isFile()&&!w(We,u,S))return Wt(We);if(N.pathname.startsWith("/_stx/component/")){let D=decodeURIComponent(N.pathname.slice(16));if(D)try{let ye=`<${D} />`,de={...buildConfig,autoShell:!1},ge=await processDirectives(ye,{},oe.join(u,"components",`${D}.stx`),de,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(N.pathname==="/_stx/img"){let{handleImageRequest:D}=await import("./chunk-g69tnqga.js"),ye=await D(A,{publicDir:oe.join(u,U),cacheDir:o(u,"cache","img")});if(ye)return ye}if(te)try{let D=await te.handleRequest(A);if(D.status!==404)return D}catch{}if(G[N.pathname])try{return await G[N.pathname](A)}catch(D){return new Response(JSON.stringify({error:D.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await E(A);if(q)return q;let Y=bn(N.pathname,k);if(Y){let D=he.get(Y.route.pattern),ye=Oe.has(Y.route.pattern);if(Y.route.isDynamic&&Object.keys(Y.params).length>0||ye){let de=await B(Y.route,Y.params);if(de)D=de}if(D){let de=D.status??200,ge=D.headers??{},$e=(Y.route.filePath?je(await Bun.file(Y.route.filePath).text().catch(()=>"")):null)??{};if($e.validate){if(!await $e.validate({params:Y.params})){let Ve=await ae(404);if(Ve){let pe=Ve;if(pe=await f(pe,u),c)pe=Xe(pe,m);return new Response(pe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if($e.middleware){let Le=rt(N.pathname,Y.params,$e,N.search),Ve=st(Le,null,A,{isServer:!0}),pe=await it($e.middleware,Ve);if(pe.redirect){let fe=pe.redirect.path,Ke=pe.redirect.options.redirectCode||302,De=new Headers(pe.responseHeaders);return De.set("Location",fe),new Response(null,{status:Ke,headers:De})}if(pe.abort){let{statusCode:fe,message:Ke}=pe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(pe.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(pe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;D.content=D.content.replace("</head>",`${fe}</head>`)}}let Q=D.content;if(P&&ii(A)){let Le=Ce(Q),Ve=le(Q),pe=Q.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=pe?ri(pe[1].trim()):"";if(Object.keys(Y.params).length>0)Q=Lt(Q,Y.params);Q=await f(Q,u);let Ke=g?.router?.container||"main";return Q=ie(Q,Ke),new Response(Q,{status:de,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Yi]:ps(),...C(),"Cache-Control":Pe}})}if(P)Q=Tn(P,Q);if(Object.keys(Y.params).length>0)Q=Lt(Q,Y.params);if(Q=await f(Q,u),c)Q=Xe(Q,m);if(s.native)if(Q.includes("<head>"))Q=Q.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 Q="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Q;if(s.titlebarHidden)if(Q.includes("<head>"))Q=Q.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 Q=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Q}`;if(D.boundaries&&D.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-ecr598p7.js");return Ve(Le(Q,D.boundaries,{timeoutMs:30000}),{status:de,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Q,{status:de,headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(L.length>0){let D=L.map((de)=>de.route),ye=bn(N.pathname,D);if(ye){let de=j.get(ye.route.pattern);if(de){let ge=de.content;if(P)ge=Tn(P,ge);if(Object.keys(ye.params).length>0)ge=Lt(ge,ye.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:de.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:de}of F)if(de!=="/"&&N.pathname.startsWith(de)){let ge=j.get(de)||j.get(de+"/");if(ge){let $e=ge.content;if(P)$e=Tn(P,$e);if($e=await f($e,u),c)$e=Xe($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(Qe(N.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=he.get("/");if(Se){let D=Se.content;if(D=await f(D,u),c)D=Xe(D,m);if(s.native)if(D.includes("<head>"))D=D.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else D="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+D;return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let D=Je;if(D=await f(D,u),c)D=Xe(D,m);return new Response(D,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let N=await ae(500);if(N)return new Response(N,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
1430
1430
  ${A.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:${it}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
- ${e.yellow}Routes:${e.reset}`);let It=[...lr(k,u)];for(let{route:A}of L)It.push(`${A.pattern}`);if(It.forEach((A,N)=>{let V=N===It.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(l)gt();Lt.stop()}),s.native){let A,N=oe.join(R,"index.stx");if(be.existsSync(N)){let V=await Bun.file(N).text();A=$t(V)}let U=g?.app?.window??{};await lt(it,{title:g?.app?.head?.title||oe.basename(u)||"stx App",width:U.width,height:U.height,darkMode:U.darkMode,hotReload:U.hotReload,titlebarHidden:U.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ne)=>ne.startsWith("public/")||ne.startsWith("public\\"),N=(ne)=>{let Z=ne.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},U=new Map,V=()=>{let ne=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>oe.dirname(Z))??[]].filter((Z)=>be.existsSync(Z)).map((Z)=>be.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!be.existsSync(q))continue;let Y=be.realpathSync(q);if(![...ne].some((Se)=>Y===Se||Y.startsWith(`${Se}${oe.sep}`)))ne.add(Y)}for(let[Z,q]of U)if(!ne.has(Z))q.close(),U.delete(Z);for(let Z of ne)if(!U.has(Z)&&be.existsSync(Z))U.set(Z,be.watch(Z,{recursive:!0},(q,Y)=>{We(Z,q,Y).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},xe=Promise.resolve(),We=(ne,Z,q)=>(xe=xe.catch(()=>{}).then(()=>Ge(ne,Z,q)),xe),Ge=async(ne,Z,q)=>{if(!q||Et(q))return;if(Rt(q)){if(g._layerGraph){let Y=await y(u);Object.assign(g,Y),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:Y._layerPageDirs?[R,...Y._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(N(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-s2x4wcrz.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(I&&q){if(oe.resolve(ne,q)===I||oe.basename(I)===q){let Se=await Sr(I,s.stxOptions||{});if(Se)P=Se}}if(await qe(),await ln(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-s2x4wcrz.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Ct(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let ne of U.values())ne.close();if(l)gt();Lt.stop(),process.exit(0)})}return!0}import Wt from"fs";import ht from"path";async function Jr(t){try{let a=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!a)return[];let p=a[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],y=m[2]||m[3]||m[4];if(!y)continue;let g={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let E=u.split(`
1435
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=E.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.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 Yr(t){try{let s=await Bun.file(t).text(),a=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(a)return a[1].split(`
1436
- `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Qr(t,s=!1,a){let p=ht.basename(t,".stx"),c=await Jr(t),l=await Yr(t),m="";if(s&&a)m=`<${a}></${a}>`;else{let u=c.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1432
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
+ ${e.yellow}Routes:${e.reset}`);let jt=[...ur(k,u)];for(let{route:A}of L)jt.push(`${A.pattern}`);if(jt.forEach((A,N)=>{let V=N===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),console.log(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let A,N=oe.join(R,"index.stx");if(be.existsSync(N)){let V=await Bun.file(N).text();A=$t(V)}let U=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||oe.basename(u)||"stx App",width:U.width,height:U.height,darkMode:U.darkMode,hotReload:U.hotReload,titlebarHidden:U.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ne)=>ne.startsWith("public/")||ne.startsWith("public\\"),N=(ne)=>{let Z=ne.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},U=new Map,V=()=>{let ne=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>oe.dirname(Z))??[]].filter((Z)=>be.existsSync(Z)).map((Z)=>be.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!be.existsSync(q))continue;let Y=be.realpathSync(q);if(![...ne].some((Se)=>Y===Se||Y.startsWith(`${Se}${oe.sep}`)))ne.add(Y)}for(let[Z,q]of U)if(!ne.has(Z))q.close(),U.delete(Z);for(let Z of ne)if(!U.has(Z)&&be.existsSync(Z))U.set(Z,be.watch(Z,{recursive:!0},(q,Y)=>{We(Z,q,Y).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},xe=Promise.resolve(),We=(ne,Z,q)=>(xe=xe.catch(()=>{}).then(()=>Ge(ne,Z,q)),xe),Ge=async(ne,Z,q)=>{if(!q||Et(q))return;if(Rt(q)){if(g._layerGraph){let Y=await y(u);Object.assign(g,Y),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:Y._layerPageDirs?[R,...Y._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(N(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-5j52h3e3.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(I&&q){if(oe.resolve(ne,q)===I||oe.basename(I)===q){let Se=await kr(I,s.stxOptions||{});if(Se)P=Se}}if(await qe(),await un(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-5j52h3e3.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Ct(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let ne of U.values())ne.close();if(l)ht();It.stop(),process.exit(0)})}return!0}import Vt from"fs";import yt from"path";async function Yr(t){try{let a=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!a)return[];let p=a[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],y=m[2]||m[3]||m[4];if(!y)continue;let g={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let E=u.split(`
1435
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=E.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.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 Qr(t){try{let s=await Bun.file(t).text(),a=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(a)return a[1].split(`
1436
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Zr(t,s=!1,a){let p=yt.basename(t,".stx"),c=await Yr(t),l=await Qr(t),m="";if(s&&a)m=`<${a}></${a}>`;else{let u=c.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
1437
  `);m=`<${p}
1438
1438
  ${u}
1439
- />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:a}}async function mn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){let c=ht.join(t,p.name);if(p.isDirectory()){let l=await mn(c);a.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))a.push(c)}return a}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Zr(t,s){try{if(!await n(t))return[];let a=await mn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of a){let m=c.get(l),u=!!m,y=m?.tag,g=await Qr(l,u,y);p.push(g)}return p}catch(a){return console.error("Error generating component docs:",a),[]}}async function es(t){try{if(!await n(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=ht.join(t,p.name),l=await Bun.file(c).text(),m=ht.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
1440
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",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 E=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=E.exec(l))!==null)v.add(S[1]);a.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return a}catch(s){return console.error("Error generating template docs:",s),[]}}async function ts(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1439
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:a}}async function mn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await mn(c);a.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))a.push(c)}return a}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function es(t,s){try{if(!await n(t))return[];let a=await mn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of a){let m=c.get(l),u=!!m,y=m?.tag,g=await Zr(l,u,y);p.push(g)}return p}catch(a){return console.error("Error generating component docs:",a),[]}}async function ts(t){try{if(!await n(t))return[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[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 E=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=E.exec(l))!==null)v.add(S[1]);a.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return a}catch(s){return console.error("Error generating template docs:",s),[]}}async function ns(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1441
1441
  <p>Welcome, {{ user.name }}!</p>
1442
1442
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1443
1443
  <p>Welcome back!</p>
@@ -1457,7 +1457,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.
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 a of t)s.push({name:a.name,description:a.description||"",hasEndTag:a.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function ns(t=[],s=[],a=[],p){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 a of t)s.push({name:a.name,description:a.description||"",hasEndTag:a.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function rs(t=[],s=[],a=[],p){let c=`# stx Documentation
1461
1461
 
1462
1462
  `;if(p)c+=`${p}
1463
1463
 
@@ -1499,7 +1499,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.
1499
1499
 
1500
1500
  `,c+=`#### Example
1501
1501
 
1502
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function rs(t=[],s=[],a=[],p){let c=`<!DOCTYPE html>
1502
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ss(t=[],s=[],a=[],p){let c=`<!DOCTYPE html>
1503
1503
  <html lang="en">
1504
1504
  <head>
1505
1505
  <meta charset="UTF-8">
@@ -1570,15 +1570,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.
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 a)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 ss(t=[],s=[],a=[],p){return JSON.stringify({components:t,templates:s,directives:a,extraContent:p||""},null,2)}async function os(t){try{let{componentsDir:s,templatesDir:a,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(a)console.log(`Templates directory: ${a}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await Zr(s,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&a)console.log("Generating template documentation..."),y=await es(a),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ts(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=ns(u,y,g,w),E="md";break;case"html":S=rs(u,y,g,w),E="html";break;case"json":S=ss(u,y,g,w),E="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=ht.join(m,`stx-docs.${E}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Us(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},a=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return os({componentsDir:a,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var hn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function gr(t,s={}){let a={...hn,...s};if(t.trim()==="")return`
1574
- `;let p=t;if(a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=cs(p,a),p=fs(p,a),p=ls(p,a),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1573
+ </tr>`;c+="</tbody></table>";for(let l of a)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 os(t=[],s=[],a=[],p){return JSON.stringify({components:t,templates:s,directives:a,extraContent:p||""},null,2)}async function is(t){try{let{componentsDir:s,templatesDir:a,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Vt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(a)console.log(`Templates directory: ${a}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await es(s,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&a)console.log("Generating template documentation..."),y=await ts(a),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ns(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=rs(u,y,g,w),E="md";break;case"html":S=ss(u,y,g,w),E="html";break;case"json":S=os(u,y,g,w),E="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=yt.join(m,`stx-docs.${E}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Ws(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},a=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return is({componentsDir:a,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var yn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function mr(t,s={}){let a={...yn,...s};if(t.trim()==="")return`
1574
+ `;let p=t;if(a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=ls(p,a),p=ms(p,a),p=ds(p,a),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1575
1575
  `).replace(/\r/g,`
1576
1576
  `),!p.endsWith(`
1577
1577
  `))p+=`
1578
- `;return p}function Ws(t,s={}){let a={...hn,...s};if(t.trim()==="")return`
1578
+ `;return p}function qs(t,s={}){let a={...yn,...s};if(t.trim()==="")return`
1579
1579
  `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,y)=>{let g=u.split(`
1580
1580
  `),b=g.filter((x)=>x.trim().length>0);if(b.length===0)return c;let w=Math.min(...b.map((x)=>{let R=x.match(/^( *)/);return R?R[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
- `),v=gr(S,a).trimEnd().split(`
1581
+ `),v=mr(S,a).trimEnd().split(`
1582
1582
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
1583
  `);return`${l}\`\`\`${m}
1584
1584
  ${v}
@@ -1586,7 +1586,7 @@ ${l}\`\`\``}),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replac
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!p.endsWith(`
1588
1588
  `))p+=`
1589
- `;return p}function as(t){let s=t,a=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=a.length;return a.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1589
+ `;return p}function cs(t){let s=t,a=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=a.length;return a.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1590
1590
  $1
1591
1591
  `),s=s.replace(/(@end\w+)/g,`
1592
1592
  $1
@@ -1600,10 +1600,10 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max
1600
1600
  `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>a[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1601
1601
  `),s=s.split(`
1602
1602
  `).map((c)=>c.trim()).join(`
1603
- `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function cs(t,s){let p=as(t).split(`
1604
- `),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let y=0;y<p.length;y++){let g=p[y],b=g.trim();if(b===""){c.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let E=b===">";if(gn(b)&&!b.startsWith("<")&&!b.startsWith("@")){c.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),R=b.startsWith("@")&&us(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),F=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!F&&!k,P=b.includes("/>")||ps(b),I=gn(b);if(L||v)l=Math.max(0,l-1);let z=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(z)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
- `)}function ls(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(a,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(a,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(a,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(a,p)=>`{!! ${p.trim()} !!}`);return t}function ps(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let a=t.match(/<(\w+)/);if(a){let p=a[1];return s.includes(p.toLowerCase())}return!1}function gn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function us(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let a of s)if(t.startsWith(`@${a}`))return!t.includes(`@end${a}`);return!1}function fs(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(a,p,c)=>{if(!c.trim())return a;if(c.includes("<")||c.includes(`
1606
- `)||c.includes("@"))return a;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.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=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import bn from"fs";import Vt from"path";async function qs(t="index.stx",s={}){try{let a=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!a)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!bn.existsSync(c))bn.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=vn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=vn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(a){return console.error(`Error creating file: ${a instanceof Error?a.message:String(a)}`),!1}}function vn(t){switch(t){case"basic":return kn();case"component":return ms();case"layout":return gs();case"blog":return hs();case"api":return ys();case"app":return bs();default:return kn()}}function kn(){return`<script>
1603
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function ls(t,s){let p=cs(t).split(`
1604
+ `),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let y=0;y<p.length;y++){let g=p[y],b=g.trim();if(b===""){c.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let E=b===">";if(hn(b)&&!b.startsWith("<")&&!b.startsWith("@")){c.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),R=b.startsWith("@")&&fs(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),F=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!F&&!k,P=b.includes("/>")||us(b),I=hn(b);if(L||v)l=Math.max(0,l-1);let z=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(z)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
+ `)}function ds(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(a,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(a,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(a,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(a,p)=>`{!! ${p.trim()} !!}`);return t}function us(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let a=t.match(/<(\w+)/);if(a){let p=a[1];return s.includes(p.toLowerCase())}return!1}function hn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function fs(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let a of s)if(t.startsWith(`@${a}`))return!t.includes(`@end${a}`);return!1}function ms(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(a,p,c)=>{if(!c.trim())return a;if(c.includes("<")||c.includes(`
1606
+ `)||c.includes("@"))return a;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.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=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import vn from"fs";import qt from"path";async function Xs(t="index.stx",s={}){try{let a=s.force||!1,p=qt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!a)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(p);if(!vn.existsSync(c))vn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=qt.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=wn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=wn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(a){return console.error(`Error creating file: ${a instanceof Error?a.message:String(a)}`),!1}}function wn(t){switch(t){case"basic":return $n();case"component":return gs();case"layout":return hs();case"blog":return ys();case"api":return bs();case"app":return xs();default:return $n()}}function $n(){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 ms(){return`{{-- Component: Card --}}
1631
+ @endsection`}function gs(){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 gs(){return`<!DOCTYPE html>
1676
+ </style>`}function hs(){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 hs(){return`<script>
1727
+ </html>`}function ys(){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 ys(){return`<script>
1772
+ @endsection`}function bs(){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 bs(){return`<!DOCTYPE html>
1807
+ @endif`}function xs(){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 Xs="f9c3713";function Mo(t){return t}function No(t){return t}function zs(t,s){let a=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)a.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))a.push(m),c++}}return a}import _e from"fs";import ke from"path";function Dn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let a=Math.max(0,Math.round((s-t)/1000));if(a<60)return`${a}s ago`;if(a<3600)return`${Math.round(a/60)}m ago`;return`${Math.round(a/3600)}h ago`}function Oi(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Mn(t,s="stx"){let a=ke.resolve(t);for(let p=0;p<10;p++){let c=ke.join(a,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=ke.dirname(a);if(l===a)break;a=l}return null}var _n=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=_e.readFileSync(ke.join(t,"package.json"),"utf8"),a=JSON.parse(s)?.version;return typeof a==="string"?a:null}catch{return null}}function Mi(t,s=6){let a=ke.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of _n){let S=ke.join(u,w),E=Di(S);if(E!==null)p.push({name:w,version:E,dir:ke.relative(a,S)||S,nested:y>0})}let b;try{b=_e.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ke.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=ke.join(S,x.name,"node_modules");if(_e.existsSync(R))l(R,y+1)}continue}let E=ke.join(S,"node_modules");if(_e.existsSync(E))l(E,y+1)}}let m=ke.join(a,"node_modules");if(_e.existsSync(m))l(m,0);return p}function _i(t){let s=[];for(let a of _n){let p=t.filter((m)=>m.name===a);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${a} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${a} 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 ${a}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${a}/package.json' -exec grep -H '"version"' {} +`})}return s}async function mr(t={}){let s=t.cwd?ke.resolve(t.cwd):process.cwd(),a=t.resolve??Oi,p=Date.now(),c=[],l=a("@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=a("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of _i(Mi(s)))c.push(y);let u=Mn(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ke.join(u,"src/signals.ts"),g=[ke.join(u,"dist/index.js"),ke.join(u,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,b=Dn(y),w=g?Dn(g):null;if(b==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(b,p)}, dist ${Mt(w,p)})`});let S=ke.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=_e.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(y){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:c,ok:!c.some((y)=>y.status==="error")}}function hr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},a=["stx runtime resolution:"];for(let p of t.checks)if(a.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)a.push(` \u2192 ${p.fix}`);return a.push(""),a.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),a.join(`
2033
- `)}export{zs,Hs,Vs,Us,gr,Ws,qs,Xs,Mo,No,mr,hr,wn,xn,Sn};
2032
+ </html>`}var Ks="f9c3713";function No(t){return t}function Lo(t){return t}function Hs(t,s){let a=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)a.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))a.push(m),c++}}return a}import _e from"fs";import ke from"path";function Mn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Dt(t,s){let a=Math.max(0,Math.round((s-t)/1000));if(a<60)return`${a}s ago`;if(a<3600)return`${Math.round(a/60)}m ago`;return`${Math.round(a/3600)}h ago`}function Di(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function _n(t,s="stx"){let a=ke.resolve(t);for(let p=0;p<10;p++){let c=ke.join(a,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=ke.dirname(a);if(l===a)break;a=l}return null}var Ln=["@stacksjs/stx","bun-plugin-stx"];function Mi(t){try{let s=_e.readFileSync(ke.join(t,"package.json"),"utf8"),a=JSON.parse(s)?.version;return typeof a==="string"?a:null}catch{return null}}function _i(t,s=6){let a=ke.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Ln){let S=ke.join(u,w),E=Mi(S);if(E!==null)p.push({name:w,version:E,dir:ke.relative(a,S)||S,nested:y>0})}let b;try{b=_e.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ke.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=ke.join(S,x.name,"node_modules");if(_e.existsSync(R))l(R,y+1)}continue}let E=ke.join(S,"node_modules");if(_e.existsSync(E))l(E,y+1)}}let m=ke.join(a,"node_modules");if(_e.existsSync(m))l(m,0);return p}function Li(t){let s=[];for(let a of Ln){let p=t.filter((m)=>m.name===a);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${a} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${a} 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 ${a}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${a}/package.json' -exec grep -H '"version"' {} +`})}return s}async function hr(t={}){let s=t.cwd?ke.resolve(t.cwd):process.cwd(),a=t.resolve??Di,p=Date.now(),c=[],l=a("@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=a("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of Li(_i(s)))c.push(y);let u=_n(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ke.join(u,"src/signals.ts"),g=[ke.join(u,"dist/index.js"),ke.join(u,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,b=Mn(y),w=g?Mn(g):null;if(b==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Dt(w,p)}) is OLDER than src/signals.ts (${Dt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Dt(b,p)}, dist ${Dt(w,p)})`});let S=ke.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=_e.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(y){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:c,ok:!c.some((y)=>y.status==="error")}}function yr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},a=["stx runtime resolution:"];for(let p of t.checks)if(a.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)a.push(` \u2192 ${p.fix}`);return a.push(""),a.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),a.join(`
2033
+ `)}export{Hs,Vs,Us,Ws,mr,qs,Xs,Ks,No,Lo,hr,yr,xn,Sn,kn};