@stacksjs/stx 0.2.416 → 0.2.418

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 (213) hide show
  1. package/dist/chunk-072f6hnz.js +2 -0
  2. package/dist/{chunk-a47yp92z.js → chunk-072mzamc.js} +5 -5
  3. package/dist/{chunk-dd5fa7d6.js → chunk-08p07eq7.js} +2 -2
  4. package/dist/chunk-0x076wz1.js +2 -0
  5. package/dist/{chunk-zyxp0nb3.js → chunk-0xgf3xgy.js} +16 -16
  6. package/dist/chunk-1680nbq4.js +2816 -0
  7. package/dist/{chunk-7tabykst.js → chunk-25n4gmek.js} +2 -2
  8. package/dist/chunk-2gfj59pt.js +2 -0
  9. package/dist/chunk-2gntnw7e.js +2 -0
  10. package/dist/chunk-2hvvwhmv.js +2 -0
  11. package/dist/{chunk-rfdqrv5v.js → chunk-31a8eh0j.js} +4 -4
  12. package/dist/{chunk-vvs75dse.js → chunk-3aqe7wy7.js} +2 -2
  13. package/dist/{chunk-x0mq57pe.js → chunk-3f5td68v.js} +2 -2
  14. package/dist/chunk-3senpdjt.js +3 -0
  15. package/dist/{chunk-jr4dwkvc.js → chunk-3wmxb126.js} +2 -2
  16. package/dist/{chunk-znbay168.js → chunk-47h689h6.js} +2 -2
  17. package/dist/chunk-4bhertga.js +2 -0
  18. package/dist/chunk-4s9dypby.js +2 -0
  19. package/dist/{chunk-rqc4jx2v.js → chunk-5f3k2mke.js} +1 -1
  20. package/dist/{chunk-nj8edn4m.js → chunk-5fwy3xap.js} +3 -3
  21. package/dist/{chunk-zcctf7tx.js → chunk-5vzamjf6.js} +4 -4
  22. package/dist/chunk-5z56g0n4.js +2 -0
  23. package/dist/chunk-68rq2fqt.js +12 -0
  24. package/dist/chunk-6ad0nseq.js +2 -0
  25. package/dist/{chunk-rhw7pqhy.js → chunk-76japd6k.js} +4 -4
  26. package/dist/chunk-7eazcxzf.js +2 -0
  27. package/dist/chunk-7hy29tcy.js +2 -0
  28. package/dist/{chunk-gxrewzhv.js → chunk-7q1yy18q.js} +2 -2
  29. package/dist/{chunk-rp4khnan.js → chunk-85bm5xrm.js} +3 -3
  30. package/dist/{chunk-bfjzfrw3.js → chunk-865xvpp2.js} +2 -2
  31. package/dist/chunk-8fyqbq14.js +2 -0
  32. package/dist/chunk-92xzpt6p.js +2 -0
  33. package/dist/{chunk-sh5c60a2.js → chunk-94ky725r.js} +2 -2
  34. package/dist/{chunk-89xcpdsp.js → chunk-9af8qbwb.js} +5 -5
  35. package/dist/{chunk-m9xdkzm6.js → chunk-9bq4w4d6.js} +3 -3
  36. package/dist/chunk-9kmmafp4.js +2 -0
  37. package/dist/{chunk-gq97zh73.js → chunk-9r5ycpdg.js} +3 -3
  38. package/dist/{chunk-fctjn68q.js → chunk-9yt899e7.js} +6 -6
  39. package/dist/chunk-atgwc7r7.js +2 -0
  40. package/dist/{chunk-a688m6js.js → chunk-ayd5r3se.js} +2 -2
  41. package/dist/{chunk-yzv8n6qw.js → chunk-bk5ndwv3.js} +2 -2
  42. package/dist/chunk-bs6y5wy2.js +2 -0
  43. package/dist/{chunk-j8rxdbe5.js → chunk-bt11a8z4.js} +3 -3
  44. package/dist/{chunk-fkhxz1dx.js → chunk-c8p4v1rd.js} +5 -5
  45. package/dist/chunk-ccg6xjr1.js +2 -0
  46. package/dist/chunk-ckv4aty5.js +2 -0
  47. package/dist/{chunk-1ctvgd7v.js → chunk-d0ynfema.js} +1 -1
  48. package/dist/chunk-d6h9rpm4.js +30 -0
  49. package/dist/chunk-dbh7h0kt.js +2 -0
  50. package/dist/chunk-dhqkg0ph.js +2 -0
  51. package/dist/{chunk-6agy2x1f.js → chunk-dw961rvn.js} +2 -2
  52. package/dist/{chunk-h8wegkb5.js → chunk-dym1eteb.js} +1 -1
  53. package/dist/{chunk-41k0th97.js → chunk-e2m674vf.js} +4 -4
  54. package/dist/{chunk-9t2xx2y4.js → chunk-e83j8xe9.js} +4 -4
  55. package/dist/chunk-ettat5ah.js +2 -0
  56. package/dist/{chunk-cn9hgyh5.js → chunk-ev8bhsc0.js} +2 -2
  57. package/dist/chunk-f4ws0qcd.js +2 -0
  58. package/dist/chunk-f97v10zr.js +2 -0
  59. package/dist/chunk-fe5st320.js +2 -0
  60. package/dist/chunk-fet3hce8.js +2 -0
  61. package/dist/chunk-fq7128p1.js +2 -0
  62. package/dist/{chunk-y5cqkmkf.js → chunk-fr8jq2ys.js} +2 -2
  63. package/dist/chunk-fwy2h1ms.js +2 -0
  64. package/dist/{chunk-ddk6fx5b.js → chunk-fxhvkenf.js} +2 -2
  65. package/dist/{chunk-v096a6fw.js → chunk-g947brd0.js} +6 -6
  66. package/dist/{chunk-wjag92ch.js → chunk-gfm7g98y.js} +85 -85
  67. package/dist/chunk-gtkhykc4.js +2 -0
  68. package/dist/{chunk-vvp4cmfq.js → chunk-h8f18cc5.js} +6 -6
  69. package/dist/chunk-h8pkm7c5.js +2 -0
  70. package/dist/{chunk-yt6h8c6g.js → chunk-hg3tyzn5.js} +11 -11
  71. package/dist/{chunk-std6xw3y.js → chunk-hkxxfzfd.js} +2 -2
  72. package/dist/{chunk-3wrmz1j9.js → chunk-hm2k9a04.js} +7 -7
  73. package/dist/chunk-hneg0155.js +2 -0
  74. package/dist/chunk-hs90en70.js +2 -0
  75. package/dist/{chunk-n5k88y07.js → chunk-jfjym18d.js} +5 -5
  76. package/dist/chunk-jgsgd6rt.js +17 -0
  77. package/dist/chunk-jn3njpxs.js +2 -0
  78. package/dist/chunk-ka8x4sw6.js +18 -0
  79. package/dist/{chunk-9rnh52t2.js → chunk-kds79hq3.js} +11 -11
  80. package/dist/{chunk-rg6csnkw.js → chunk-kkj5x9rp.js} +1 -1
  81. package/dist/chunk-mcqn70v8.js +3 -0
  82. package/dist/chunk-mcs7p3fy.js +2 -0
  83. package/dist/{chunk-wpe72ann.js → chunk-mj6fme15.js} +5 -5
  84. package/dist/{chunk-yk63jd7v.js → chunk-mj9yv1vb.js} +1 -1
  85. package/dist/chunk-mmtg0jxd.js +2 -0
  86. package/dist/chunk-mrsxwd0h.js +2 -0
  87. package/dist/chunk-mscky0ww.js +2 -0
  88. package/dist/chunk-mtphm33a.js +2 -0
  89. package/dist/chunk-p2jbc71s.js +2 -0
  90. package/dist/{chunk-p1tb8kxq.js → chunk-pb0fgdvn.js} +4 -4
  91. package/dist/{chunk-at0ar6t3.js → chunk-psmdbcbc.js} +4 -4
  92. package/dist/chunk-pvd9k3kx.js +2 -0
  93. package/dist/chunk-pz1jc3db.js +2 -0
  94. package/dist/chunk-q8swb7na.js +4 -0
  95. package/dist/{chunk-7mbpjv9e.js → chunk-qmzwhtr2.js} +2 -2
  96. package/dist/chunk-qvr6e2ve.js +3 -0
  97. package/dist/chunk-ra0pkkvd.js +2 -0
  98. package/dist/chunk-rcbtd4w3.js +2 -0
  99. package/dist/chunk-rd2r9jvn.js +2 -0
  100. package/dist/chunk-s8srb8bg.js +2 -0
  101. package/dist/{chunk-3t0yaexe.js → chunk-sjjc670z.js} +9 -9
  102. package/dist/chunk-snf2b68p.js +2 -0
  103. package/dist/chunk-t2bfwr9v.js +2 -0
  104. package/dist/chunk-tbmwdahm.js +2 -0
  105. package/dist/{chunk-388rx71h.js → chunk-v15g9jjh.js} +6 -6
  106. package/dist/{chunk-de2pv6ys.js → chunk-vdqa5gt7.js} +2 -2
  107. package/dist/{chunk-rv5bk83t.js → chunk-vepc9rbt.js} +2 -2
  108. package/dist/{chunk-0es4h5v1.js → chunk-vfdwvt23.js} +2 -2
  109. package/dist/chunk-vpv896zx.js +2 -0
  110. package/dist/{chunk-3g8zzdgs.js → chunk-vyfg2qd2.js} +5 -5
  111. package/dist/{chunk-tfhjbjq5.js → chunk-w5zmvn7b.js} +3 -3
  112. package/dist/chunk-w6h63b48.js +2 -0
  113. package/dist/{chunk-cq408jrm.js → chunk-wgzxmh7w.js} +3 -3
  114. package/dist/{chunk-ppse812s.js → chunk-wpkxbggq.js} +1 -1
  115. package/dist/chunk-wrk3gkgg.js +2 -0
  116. package/dist/chunk-wtd71jsa.js +2 -0
  117. package/dist/{chunk-c4bkj1xw.js → chunk-wweasgq9.js} +18 -18
  118. package/dist/chunk-wymf1ek6.js +2 -0
  119. package/dist/chunk-wz8hyh8h.js +4 -0
  120. package/dist/chunk-x32wpjs0.js +2 -0
  121. package/dist/chunk-x4q2eyt0.js +2 -0
  122. package/dist/chunk-x95ejws0.js +2 -0
  123. package/dist/chunk-xket8ejt.js +2 -0
  124. package/dist/{chunk-t9axxwy9.js → chunk-xt6d3zws.js} +4 -4
  125. package/dist/{chunk-qff4qkx5.js → chunk-xvn3sv3v.js} +3 -3
  126. package/dist/{chunk-tfexmdkt.js → chunk-xwkdv585.js} +2 -2
  127. package/dist/{chunk-ae7j3n39.js → chunk-y9t55tv7.js} +6 -6
  128. package/dist/chunk-ypfzy1mq.js +2 -0
  129. package/dist/{chunk-7zjvsacw.js → chunk-yrbzsrde.js} +2 -2
  130. package/dist/chunk-zg68pwy8.js +2 -0
  131. package/dist/chunk-zs58fnme.js +2 -0
  132. package/dist/chunk-zy3p0vmx.js +3 -0
  133. package/dist/cli.js +21 -21
  134. package/dist/craft-entry.js +2 -2
  135. package/dist/craft.js +2 -2
  136. package/dist/dev-server/ts-css.d.ts +11 -0
  137. package/dist/dev-server/ts-css.js +13 -1
  138. package/dist/pwa.js +3 -3
  139. package/dist/ssg.js +17 -17
  140. package/package.json +5 -5
  141. package/dist/chunk-02k2v1mb.js +0 -2
  142. package/dist/chunk-0dh1rgg8.js +0 -2
  143. package/dist/chunk-0hrqt5c2.js +0 -2
  144. package/dist/chunk-0vtk2rpr.js +0 -2
  145. package/dist/chunk-1rd3jzrq.js +0 -2
  146. package/dist/chunk-26j2q9rq.js +0 -32
  147. package/dist/chunk-2py27bzq.js +0 -2
  148. package/dist/chunk-2qa7hjp2.js +0 -3
  149. package/dist/chunk-35e6zj5x.js +0 -2
  150. package/dist/chunk-3ch40ebr.js +0 -2
  151. package/dist/chunk-49cpqjx2.js +0 -2
  152. package/dist/chunk-4k1nkp9r.js +0 -2
  153. package/dist/chunk-50vq8k55.js +0 -2
  154. package/dist/chunk-56pkjk55.js +0 -2
  155. package/dist/chunk-5hnh00ry.js +0 -2
  156. package/dist/chunk-5j52h3e3.js +0 -2
  157. package/dist/chunk-5y1mekxe.js +0 -2
  158. package/dist/chunk-5zryk911.js +0 -2
  159. package/dist/chunk-72w28vm8.js +0 -2
  160. package/dist/chunk-7s7k94as.js +0 -2
  161. package/dist/chunk-7wb6jf17.js +0 -2
  162. package/dist/chunk-8cbkqckh.js +0 -2
  163. package/dist/chunk-8ycy1b0e.js +0 -2
  164. package/dist/chunk-8ygks6dx.js +0 -3
  165. package/dist/chunk-95165j9c.js +0 -4
  166. package/dist/chunk-9fyss0yk.js +0 -3
  167. package/dist/chunk-aqrnpgn7.js +0 -2
  168. package/dist/chunk-b9rebdtq.js +0 -2
  169. package/dist/chunk-c4thhfx9.js +0 -2
  170. package/dist/chunk-cw6kqb63.js +0 -2
  171. package/dist/chunk-d3vtgnep.js +0 -2
  172. package/dist/chunk-d4ynv4z2.js +0 -2
  173. package/dist/chunk-d7xrewxq.js +0 -2
  174. package/dist/chunk-dg1n3g1d.js +0 -2785
  175. package/dist/chunk-ecr598p7.js +0 -2
  176. package/dist/chunk-eev80mpy.js +0 -2
  177. package/dist/chunk-ef5vz9w5.js +0 -2
  178. package/dist/chunk-et0rr8c7.js +0 -3
  179. package/dist/chunk-f5qd84w8.js +0 -2
  180. package/dist/chunk-g69tnqga.js +0 -2
  181. package/dist/chunk-gacycmb0.js +0 -2
  182. package/dist/chunk-ggywfyzm.js +0 -2
  183. package/dist/chunk-gp1bhn7t.js +0 -2
  184. package/dist/chunk-gr3r9xdh.js +0 -2
  185. package/dist/chunk-gyv1t0f0.js +0 -30
  186. package/dist/chunk-hec0bvvf.js +0 -12
  187. package/dist/chunk-hg1eq72d.js +0 -2
  188. package/dist/chunk-hvyqs5tf.js +0 -2
  189. package/dist/chunk-kbysqxmd.js +0 -2
  190. package/dist/chunk-kjbv8a3m.js +0 -2
  191. package/dist/chunk-kmnsrvrp.js +0 -2
  192. package/dist/chunk-m6fvj7g1.js +0 -2
  193. package/dist/chunk-mgw2cvb7.js +0 -2
  194. package/dist/chunk-mvwt1c8f.js +0 -2
  195. package/dist/chunk-nvh31cxn.js +0 -2
  196. package/dist/chunk-p34gbb4z.js +0 -2
  197. package/dist/chunk-peyt18ce.js +0 -2
  198. package/dist/chunk-qpx8kvd8.js +0 -2
  199. package/dist/chunk-qzkebqm3.js +0 -4
  200. package/dist/chunk-rb272g9d.js +0 -3
  201. package/dist/chunk-rh1dyfsn.js +0 -2
  202. package/dist/chunk-rspc8gn8.js +0 -2
  203. package/dist/chunk-rvs61c88.js +0 -2
  204. package/dist/chunk-sf1vhfrb.js +0 -2
  205. package/dist/chunk-tc274fcv.js +0 -18
  206. package/dist/chunk-ty7t3gp4.js +0 -3
  207. package/dist/chunk-vc9wa97m.js +0 -2
  208. package/dist/chunk-wjzqz3yr.js +0 -2
  209. package/dist/chunk-x7j0krz8.js +0 -2
  210. package/dist/chunk-xkv0evbf.js +0 -2
  211. package/dist/chunk-y6rahx7t.js +0 -17
  212. package/dist/chunk-yt452b4a.js +0 -2
  213. package/dist/chunk-yxfx44fv.js +0 -2
@@ -1,11 +1,11 @@
1
1
  // @bun
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
- `),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 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(`
2
+ import{U,h,Jt,Yt,e,bt,Zt,f,Ne,vt,Le,je,Z,M,ae,q,d,he,Wi,rs,r,n,ee,Hn,i,T,ce}from"./chunk-1680nbq4.js";import{X,an,te,_,Ct}from"./chunk-wweasgq9.js";import{Je,dn,Qn,er,tr,Ye,Ze,Qe,et,tt,nt,we}from"./chunk-76japd6k.js";import{Te,Ks,ne,C,Gs,gr,wn,fe,Js,re}from"./chunk-d6h9rpm4.js";import{_t}from"./chunk-3senpdjt.js";import{Pe}from"./chunk-jgsgd6rt.js";import{a}from"./chunk-mcqn70v8.js";import{D}from"./chunk-qvr6e2ve.js";async function Gn(t){try{let s=await Bun.file(t).text(),o=Jn(s),p=Yn(s,t),c=Zn(s,o),l=nr(s,o);return{file:t,metrics:o,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
+ `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(o?o[1]:"").split(`
4
+ `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let 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 o=[],p=Gt(t,"if","endif");if(p>0)o.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)o.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)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)o.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)o.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
+ `).filter((b)=>b.length>120);if(y.length>0)o.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)o.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Zn(t,s){let o=[];if(s.complexity>7)o.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)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)o.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)o.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)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function nr(t,s){let o=1;if(o+=s.directives.conditionals*0.1,o+=s.directives.loops*0.5,o+=s.directives.includes*2,o+=s.expressions*0.05,o+=s.components*1,s.scriptLines>10)o+=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(o>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(o*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Gt(t,s,o){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Os(t=["**/*.stx"],s){let o=[],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 Gn(l);o.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=rr(o);return{results:o,summary:c}}function rr(t){let s=t.length,o=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:o,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as sr,readFile as ir,readdir as lr,stat as Qt,writeFile as dr}from"fs/promises";import Ae from"path";function on(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 cn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function pr(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 ur(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function fr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function mr(t){let s=[];async function o(p){let c=await lr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ae.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await o(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await o(t),s}function hr(t,s){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let p=o[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function yr(t,s){let o={},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(cn.has(y))throw Error(`${s}: client ${on(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 ":"";o[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return o}function br(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function en(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
6
6
 
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 {};
7
+ `)}function xr(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 vr(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 wr(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 Sr(t){let s=[],o=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(o,l.index)),o=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(o):null;if(g)o=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(o)),s.join(`
8
+ `)}function xt(t,s,o,p){if(t[s]!==o)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===o)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function Ht(t,s,o){let p=o?"([{<":"([{",c=o?")]}>":")]}",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 kr(t){let s=0,o=null;for(let p=0;p<t.length;p++){let c=t[p];if(o){if(c==="\\"){p++;continue}if(c===o)o=null;continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function tn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Tr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let o=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=o.exec(t);k&&k.index<s.index;k=o.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=xt(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=xt(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=xt(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=xt(t,u,"{","}");if(k===-1)return null;for(let[B,L]of Bt(t.slice(u,k)))l[B]=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 B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of Bt(x)){if(m.push(k),!B.startsWith("{")){let L=tn(B);if(L)c[k]=L;continue}for(let[L,j]of Bt(B))if(L==="default")l[k]=j;else if(L==="type"){let P=tn(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 B=kr(k),j=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),B!==-1)l[j]=k.slice(B+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(/\}$/,""),o=[],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)o.push([l[1],g]);p++}return o}function $r(t,s,o){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=Ae.resolve(Ae.dirname(s),x),B=Ae.relative(o,k);return`${v}${B.startsWith(".")?B:`./${B}`}${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 o of t.matchAll(/<slot\b([^>]*)>/gi))s.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((o)=>({name:o}))}function Pr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function nn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function Ar(t,s,o){let p=Ae.isAbsolute(s.file)?s.file:Ae.resolve(t,s.file),c=await ir(p,"utf8"),l=hr(c,p),m=Ae.basename(p,".stx"),u=s.name||l.name||pr(m),y=`${Ft(o.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(!ur(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,nn(L,j)])),S=Cr(br(c)),E=Rr(S.template),v=$r(c,p,Ae.resolve(o.outputDir)),x=Sr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=nn(L,{type:xr(v.declared[L])??vr(j),...j===void 0?{}:{default:wr(j)}})}let R=l.methods||{},k=s.methods||{},B=yr(c,p);return{file:Ae.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:en(c),shadowMode:fr(s.shadowDOM??l.shadowDOM??o.shadowDOM),progressive:s.progressive??l.progressive??o.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...R,...k,...B},eventTypes:S.eventTypes,bindings:E.bindings,slots:Er(E.template),cssProperties:Pr(en(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 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) {
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),o=Object.entries(t.methods).map(([u,y])=>{if(cn.has(u))throw Error(`${t.sourcePath}: ${on(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
307
307
  ${y}
308
308
  }`}).join(`
309
309
 
@@ -323,13 +323,13 @@ ${p.imports.length?`${p.imports.join(`
323
323
  `:""}
324
324
  /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
325
325
  export class ${t.name} extends StxElement {
326
- ${a}${m}
326
+ ${o}${m}
327
327
  }
328
328
 
329
329
  defineComponent(${t.name}, ${s});
330
330
  export default ${t.name};
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(`
331
+ `}function wt(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?"":"?"}: ${wt(m)}`).join(`
332
+ `),o=Object.entries(t.properties).map(([l,m])=>` ${l}: ${wt(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 {
@@ -341,7 +341,7 @@ ${p}
341
341
  }
342
342
 
343
343
  export declare class ${t.name} extends HTMLElement {
344
- ${a}
344
+ ${o}
345
345
  ${c}
346
346
  readonly updateComplete: Promise<void>
347
347
  requestUpdate(): Promise<void>
@@ -358,9 +358,9 @@ export default ${t.name}
358
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)}?: ${vt(m)}`).join(`
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
- `);return` ${JSON.stringify(a.tag)}: {
361
+ ${t.map((o)=>{let p=Object.entries(o.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${wt(m)}`).join(`
362
+ `),c=Object.keys(o.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${o.events[l].detailType||"unknown"}>) => void`).join(`
363
+ `);return` ${JSON.stringify(o.tag)}: {
364
364
  ${p}
365
365
  ${c}
366
366
  children?: unknown
@@ -374,9 +374,9 @@ ${c}
374
374
  }
375
375
 
376
376
  export {}
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}) {
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(([o,p])=>({kind:"field",name:o,description:p.description,type:{text:wt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ft(o),reflects:p.reflect})),events:Object.entries(s.events).map(([o,p])=>({name:o,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function rn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
378
378
  ${s}
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(`
379
+ }`}function sn(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*!!\\}"),o=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;')
@@ -390,7 +390,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
390
390
  Object.assign(values, props);
391
391
  let template = definition.template
392
392
  .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
- .replace(new RegExp(${a}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
393
+ .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
394
  .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
395
395
  const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
396
396
  if (property.attribute === false || !(name in props)) return [];
@@ -410,21 +410,21 @@ export function renderComponent(tag, props = {}, slots = {}) {
410
410
  }
411
411
 
412
412
  ${l}
413
- `}async function 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(`
413
+ `}async function Ms(t){let s=Ae.resolve(t.inputDir),o=Ae.resolve(t.outputDir);if(!(await Qt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await mr(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 sr(o,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ae.join(o,x);return await dr(k,R.endsWith(`
414
414
  `)?R:`${R}
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(`
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:rn(x);await g(`${x.tag}.css`,t.minify?sn(R):R)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
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
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(Lr(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(nn).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(rn).join(`
422
422
 
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
- `);throw AggregateError(k,`Failed to bundle component library${F?`
425
- ${F}`:""}`)}if(!x.success){let R=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
423
+ `);if(x)S=await g("bundle.css",t.minify?sn(x):x)}let E;if(t.bundle!==!1){E=Ae.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ae.join(o,"index.js")],outdir:o,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],B=k.map((L)=>String(L).trim()).filter(Boolean).join(`
424
+ `);throw AggregateError(k,`Failed to bundle component library${B?`
425
+ ${B}`:""}`)}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 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`
427
+ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await Qt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ae.join(o,`${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 St(){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 St(t){return`
477
+ }`}function kt(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 kt(){return`
483
+ </div>`}function Tt(){return`
484
484
  function changeTheme() {
485
485
  const theme = document.getElementById('themeSelector').value;
486
486
 
@@ -496,20 +496,20 @@ else {
496
496
  }
497
497
 
498
498
  // Initialize theme on page load
499
- document.addEventListener('DOMContentLoaded', changeTheme);`}function Tt(t){if(Object.keys(t).length===0)return"";return`
499
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function $t(t){if(Object.keys(t).length===0)return"";return`
500
500
  <div class="frontmatter">
501
501
  <h3>Frontmatter</h3>
502
- ${Object.entries(t).map(([s,a])=>`
502
+ ${Object.entries(t).map(([s,o])=>`
503
503
  <div class="frontmatter-item">
504
504
  <span class="frontmatter-label">${s}:</span>
505
- <span>${Array.isArray(a)?a.join(", "):String(a)}</span>
505
+ <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
506
506
  </div>`).join("")}
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=`
507
+ </div>`}import ln from"net";async function jr(t){return new Promise((s)=>{let o=ln.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let o=ln.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function st(t,s=20){t=Number(t);for(let o=0;o<s;o++){let p=t+o;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 o={...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:o.title,width:o.width,height:o.height,darkMode:o.darkMode,hotReload:o.hotReload,titlebarHidden:o.titlebarHidden,nativeSidebar:o.nativeSidebar,sidebarWidth:o.sidebarWidth,sidebarConfig:o.sidebarConfig});if(c&&o.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 Rt(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 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(`
510
+ `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let o=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(o)try{return JSON.parse(o[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let 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 ot(t,s,o){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(o?.onQuit)o.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
512
+ `)){let l=p.trim().toLowerCase();p="",Wr(l,t,s,o)}})}function Wr(t,s,o,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}`),o(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Ut(t,s={}){let o=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 ce(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||[],B=[...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">
@@ -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
- ${wt()}
661
+ ${St()}
662
662
  </style>
663
663
  </head>
664
664
  <body>
665
- ${Tt(S)}
666
- ${St(F)}
665
+ ${$t(S)}
666
+ ${kt(B)}
667
667
 
668
668
  ${w}
669
669
 
670
670
  <script>
671
- ${kt()}
671
+ ${Tt()}
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=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}
675
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let y=o;try{if(y=await st(o),y!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let g=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
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`
680
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(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 ze from"fs";import Se from"path";class pn{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,o=20;for(let p=0;p<o;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 ${o} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),o=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),o++}catch{this.clients.delete(p)}if(this.options.verbose&&o>0)console.log(`[HMR] Broadcast ${t.type} to ${o} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,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:o=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
681
681
  <script>
682
682
  (function() {
683
683
  // stx Hot Reload Client
@@ -689,7 +689,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(g.u
689
689
  var overlay = null;
690
690
  var wasConnected = false; // Track if we ever connected successfully
691
691
 
692
- ${a?`
692
+ ${o?`
693
693
  // Create connection status overlay
694
694
  function createOverlay() {
695
695
  overlay = document.createElement('div');
@@ -876,10 +876,10 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function 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(`
879
+ `}function Xe(t,s,o={}){let p=Kr(s,o),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 Et(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Pt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function At(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var ut=null;function Ot(t){if(!ut)ut=new pn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Dt from"path";var ft={name:"bun-plugin-stx",async setup(t){let o={...await i(),...t.config?.stx},p=new Set,c=o.webComponents?.enabled?`./${Dt.relative(Dt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let m=await Hn(o,p);if(l.push(...m),o.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(o.cache&&o.cachePath){let x=await Jt(m,o);if(x){if(o.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await te(()=>Bun.file(m).text(),"",(x)=>{throw new an(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new an(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=U.time("script-extraction",()=>{let x=y,R=Z(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=P.match(/<script\b([^>]*)>/i),G=F?F[1]:"";if(/\bserver\b/i.test(G))B=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:Dt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let R=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),o.debug)throw R});let v=await U.timeAsync("directive-processing",async()=>await r(b,S,m,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-x4q2eyt0.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 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>
882
+ ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),o.cache&&o.cachePath){if(await Yt(m,v,u,o),o.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new X(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),Ct.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:o.debug||D()?`<!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 en
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(Ot.basename(m))}</code> for detailed analysis</li>
923
+ <li>Run <code>stx debug ${h(Dt.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 en
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 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}
942
+ </html>`,loader:"html"}}})}};async function gn(t,s={}){let o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+1,u=Se.resolve(t);if(!ze.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=a(process.cwd(),"output");ze.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(Ce){Ce.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ye)=>({path:ye.path,external:!0}))}},F=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let G=F.outputs.find((Ce)=>Ce.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=Se.dirname(u);await bt(S);let E=o;try{if(E=await st(o),E!==o)console.log(`${e.yellow}Port ${o} 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=Ot({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-f97v10zr.js"),F=await I();if(R=s.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:se}=await import("./chunk-rcbtd4w3.js"),Ce=F.broadcasting;await G(Ce);let ye=Ce.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ye}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(ze.existsSync(De))try{let le=await se(De);console.log(`${e.blue}Loaded ${e.bright}${le} broadcast channel${le!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(le){console.warn(`${e.yellow}Failed to load channels.ts: ${le.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-dbh7h0kt.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 _t(I,await(async()=>{let F=new URL(I.url);if([y,Se.dirname(u),Se.join(process.cwd(),"public")].some((le)=>B(Se.join(le,F.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let le=await x.handleRequest(I);if(le.status!==404)return le}catch{}if(v[F.pathname])try{return await v[F.pathname](I)}catch(le){return new Response(JSON.stringify({error:le.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(F.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 se=Se.join(y,F.pathname);if(ze.existsSync(se)&&ze.statSync(se).isFile()){let le=Bun.file(se),W=Se.extname(se).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.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":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let Ce=Se.dirname(u),ye=Se.join(Ce,F.pathname);if(ze.existsSync(ye)&&ze.statSync(ye).isFile()){let le=Bun.file(ye),W=Se.extname(ye).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.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":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let De=Se.join(process.cwd(),"public",F.pathname);if(ze.existsSync(De)&&ze.statSync(De).isFile()){let le=Bun.file(De),W=Se.extname(De).toLowerCase(),H="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.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":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}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
- ${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 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=`
946
+ ${e.yellow}Routes:${e.reset}`);let P=Se.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`),ot(j.url.toString(),()=>{if(p)ze.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),F=Rt(I);await dt(E,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(p){let I=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let F=ze.watch(I,{recursive:!0},async(G,se)=>{if(!se||At(se))return;if(Pt(se)){console.log(`${e.yellow}File ${e.bright}${se}${e.yellow} changed, rebuilding...${e.reset}`),he.clear(),ee();let Ce=await b();if(await Zt(S),c&&l)if(Ce)l.reload(se);else l.error("Build failed - check console for details")}else if(Et(se)){if(console.log(`${e.cyan}CSS ${e.bright}${se}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(se)}});process.on("SIGINT",()=>{if(F.close(),l)ht();j.stop(),process.exit(0)})}return!0}var{serve:Gr}=globalThis.Bun;import it from"fs";import Oe from"path";var un=`
948
948
  <script data-stx-helpers>
949
949
  (function() {
950
950
  'use strict'
@@ -1255,14 +1255,14 @@ else {
1255
1255
 
1256
1256
  })()
1257
1257
  </script>
1258
- `;function 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
- `),te=`
1258
+ `;function yn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Oe.sep)),o=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))o.push(c);else break}return o.join(Oe.sep)}async function mn(t,s={}){let o=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Oe.resolve(v);if(!it.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");it.mkdirSync(c,{recursive:!0});let l=yn(t.map((v)=>Oe.dirname(Oe.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=Oe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await ce(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((De)=>`<option value="${De}"${De===j?" selected":""}>${De}</option>`).join(`
1259
+ `),se=`
1260
1260
  <!DOCTYPE html>
1261
1261
  <html lang="en">
1262
1262
  <head>
1263
1263
  <meta charset="UTF-8">
1264
1264
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
- <title>${dn(F.title||Ae.basename(x))}</title>
1265
+ <title>${fn(B.title||Oe.basename(x))}</title>
1266
1266
  <!-- Syntax highlighting styles -->
1267
1267
  <style id="syntax-theme">
1268
1268
  :root {
@@ -1404,40 +1404,40 @@ else {
1404
1404
  min-width: 100px;
1405
1405
  color: #555;
1406
1406
  }
1407
- ${wt()}
1407
+ ${St()}
1408
1408
  </style>
1409
1409
  </head>
1410
1410
  <body>
1411
- ${Tt(F)}
1412
- ${St(G)}
1411
+ ${$t(B)}
1412
+ ${kt(G)}
1413
1413
 
1414
1414
  ${k}
1415
1415
 
1416
1416
  <script>
1417
- ${kt()}
1417
+ ${Tt()}
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,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
- </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}
1421
+ `,ye=`/${Oe.relative(l,x).replace(/\.md$/,"")}`;if(ye.endsWith("/index"))ye=ye.slice(0,-6)||"/";m[ye||"/"]={filePath:x,content:se,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}))}},B;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}:`,Pe(P.logs,x));continue}let I=P.outputs.find((F)=>F.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${Pe(P,x)}`);continue}let j=`/${Oe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=Qn(j,{page:!0});u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:B,fileType:"stx"}}else m[j||"/"]={filePath:x,content:B,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,Pe(v)),!1}};if(!await y())return!1;let b=o;try{if(b=await st(o),b!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Gr({port:b,async fetch(v){let x=new URL(v.url),R=Oe.join(process.cwd(),"public",x.pathname);if(it.existsSync(R)&&it.statSync(R).isFile()){let L=Bun.file(R),j=Oe.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await L.text(),G=I.transformSync(F);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 se=0;se<L.paramNames.length;se++)I[L.paramNames[se]]=decodeURIComponent(j[se+1]);let F=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${G}
1423
+ </head>`);else F=G+F;k={...P,content:F}}break}}if(k)return f(k.content).then((L)=>{if(L.includes("</head>"))L=L.replace("</head>",`${un}
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 B=Oe.join(c,x.pathname);if(it.existsSync(B)&&it.statSync(B).isFile()){let L=Bun.file(B),j=Oe.extname(B).toLowerCase(),P="text/plain";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await L.text(),G=I.transformSync(F);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=ne(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),F=I?I[1]:"",G=`<!DOCTYPE html><html><head><title>${fn(F)}</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":Te,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
- ${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: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}
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:Oe.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:Oe.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 ",B=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${B}`)}),console.log(`
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(w.url.toString(),()=>{if(p)it.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.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}`),he.clear(),ee(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function fn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Jr}=globalThis.Bun;import xe from"fs";import ie from"path";async function bn(t){try{return vt(await Bun.file(t).text())}catch{return}}function Wt(t){let s=Bun.file(t),o=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[o]||"application/octet-stream",...l}})}async function hn(t=".",s={}){let o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+1,u=ie.resolve(t),{loadStxConfig:y}=await import("./chunk-f97v10zr.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-dbh7h0kt.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",R=ie.join(v,x);if(!xe.existsSync(R)&&!g._layerPageDirs?.some((A)=>xe.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 B=g?._pluginPageDirs||[],L=[];for(let{dir:A,prefix:z}of B)if(xe.existsSync(A)){let N=M(ie.dirname(A),{pagesDir:ie.basename(A)});for(let V of N){let ve=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:ve},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,P=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await Gs(u,s.stxOptions?.shell),I){if(P=await gr(I,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Ye(),await Qe(u);let F=Ze();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let G={},se=null;try{let{loadStxConfig:A}=await import("./chunk-f97v10zr.js"),z=await A(u);if(z?.apiRouter)se=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){G=z.apiRoutes;let N=Object.keys(G).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-rcbtd4w3.js"),ve=z.broadcasting;await N(ve);let We=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(xe.existsSync(Ge))try{let oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let Ce=a(u,"output");xe.mkdirSync(Ce,{recursive:!0});let ye=new Map,De=new Set,le=async(A)=>{let z=er(R,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:Ce,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:ve,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-f97v10zr.js"),{checkCache:oe,cacheTemplate:Q,readFileCached:K,templateCache:J}=await import("./chunk-hs90en70.js"),ke=await We(u),rt=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},O={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=rt(O.partialsDir),O.componentsDir=rt(O.componentsDir),O.layoutsDir=rt(O.layoutsDir),O.storesDir=rt(O.storesDir||"stores"),O.cachePath=rt(O.cachePath)??a(u,"cache");let be=!z&&!s.profile,pe=O.cache!==!1;if(pe&&be){let de=J.get(A.filePath);if(de)try{if((await xe.promises.stat(A.filePath)).mtime.getTime()<=de.mtime){let Fe=!0;for(let Ee of de.dependencies){if(!xe.existsSync(Ee)){Fe=!1;break}if((await xe.promises.stat(Ee)).mtime.getTime()>de.mtime){Fe=!1;break}}if(Fe){let Ee=de.output;if(P)Ee=fe(Ee,{preserveHead:!0});let gt=W.get(A.filePath);return{route:A,content:Ee,status:gt?.status??await bn(A.filePath),headers:gt?.headers}}}}catch{}let He=await oe(A.filePath,O);if(He){let Be=He;if(P)Be=fe(Be,{preserveHead:!0});let Fe=W.get(A.filePath);return{route:A,content:Be,status:Fe?.status??await bn(A.filePath),headers:Fe?.headers}}}let ge=pe?await K(A.filePath):await Bun.file(A.filePath).text(),Re=vt(ge),{classifyAllScripts:Y}=await import("./chunk-f97v10zr.js"),Ie=Y(ge),Ve=Ie.server.map((de)=>de.content),ue=ge;for(let de of Ie.server)ue=ue.replace(de.fullTag,"");let me={__filename:A.filePath,__dirname:ie.dirname(A.filePath),__stx_options:O,params:z??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,me,A.filePath)}catch(He){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,He?.message||He)}let Ke=new Set,Me;if(s.profile){let de=performance.now();Me=await N(ue,me,A.filePath,O,Ke);let He=performance.now()-de,Be=ie.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${Be} \u2192 ${He.toFixed(2)}ms`)}else Me=await N(ue,me,A.filePath,O,Ke);if(!P)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:de}=await import("./chunk-x4q2eyt0.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(He,Be,Fe)=>{if(!/function\s+__stx_setup_/.test(Fe))return He;return`<script${Be}>${de(Fe,me)}</script>`})}if(P)Me=fe(Me,{preserveHead:!0});if(pe&&be)await Q(A.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-fe5st320.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=me.streamBoundaries||{},He={...O,autoShell:!1},Be=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof de[Ee]==="function"?await de[Ee]():void 0;return N(mt[Ee],{...me,$boundary:gt},A.filePath,He,new Set)}})),Fe=new Set(Be.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!Fe.has(Ee.id)),...Be]}if(lt&&lt.length>0)De.add(A.pattern);else lt=void 0;let Kt=Le(me),Xt=je(me);if(be)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Ue=8,qe=async()=>{ye.clear(),j.clear();for(let A=0;A<k.length;A+=Ue){let z=k.slice(A,A+Ue),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)ye.set(V.route.pattern,V)}for(let A=0;A<L.length;A+=Ue){let z=L.slice(A,A+Ue),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await bt(u);let at=o;try{if(at=await st(o),at!==o)console.log(`${e.yellow}Port ${o} 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=Ot({wsPort:A,verbose:!1}),m=l.start(A)}let Lt=(A,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${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 z=new URL(A.url),N=g?.publicDir||"public",V=ie.join(u,N,z.pathname),ve=ie.join(u,z.pathname),We=ie.join(Ce,z.pathname);if([V,ve,We].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Q]=await Promise.all([xe.promises.stat(V).catch(()=>null),xe.promises.stat(ve).catch(()=>null),xe.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return Wt(V);if(oe?.isFile()&&!w(ve,u,S))return Wt(ve);if(Q?.isFile()&&!w(We,u,S))return Wt(We);if(z.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(z.pathname.slice(16));if(O)try{let be=`<${O} />`,pe={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),pe,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:O}=await import("./chunk-072f6hnz.js"),be=await O(A,{publicDir:ie.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(se)try{let O=await se.handleRequest(A);if(O.status!==404)return O}catch{}if(G[z.pathname])try{return await G[z.pathname](A)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await E(A);if(K)return K;let J=dn(z.pathname,k);if(J){let O=ye.get(J.route.pattern),be=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let pe=await H(J.route,J.params);if(pe)O=pe}if(O){let pe=O.status??200,ge=O.headers??{},Re=(J.route.filePath?Ne(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await le(404);if(Ve){let ue=Ve;if(ue=await f(ue,u),c)ue=Xe(ue,m);return new Response(ue,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Ie=et(z.pathname,J.params,Re,z.search),Ve=tt(Ie,null,A,{isServer:!0}),ue=await nt(Re.middleware,Ve);if(ue.redirect){let me=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Me=new Headers(ue.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(ue.abort){let{statusCode:me,message:Ke}=ue.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(ue.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ue.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${me}</head>`)}}let Y=O.content;if(P&&Js(A)){let Ie=we(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=ue?Ks(ue[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ie.layout,"X-STX-Layout-Group":Ie.group,"X-STX-Runtime":Ve?"true":"false",...me&&{"X-STX-Title":encodeURIComponent(me)},[Wi]:rs(),...C(),"Cache-Control":Te}})}if(P)Y=wn(P,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Ie,streamToResponse:Ve}=await import("./chunk-fe5st320.js");return Ve(Ie(Y,O.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,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 O=L.map((pe)=>pe.route),be=dn(z.pathname,O);if(be){let pe=j.get(be.route.pattern);if(pe){let ge=pe.content;if(P)ge=wn(P,ge);if(Object.keys(be.params).length>0)ge=Lt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of B)if(pe!=="/"&&z.pathname.startsWith(pe)){let ge=j.get(pe)||j.get(pe+"/");if(ge){let Re=ge.content;if(P)Re=wn(P,Re);if(Re=await f(Re,u),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Je(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=ye.get("/");if(ke){let O=ke.content;if(O=await f(O,u),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let rt=await le(404);if(rt){let O=rt;if(O=await f(O,u),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await le(500);if(z)return new Response(z,{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
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(`
1433
+ ${e.yellow}Routes:${e.reset}`);let jt=[...tr(k,u)];for(let{route:A}of L)jt.push(`${A.pattern}`);if(jt.forEach((A,z)=>{let V=z===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`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let A,z=ie.join(R,"index.stx");if(xe.existsSync(z)){let V=await Bun.file(z).text();A=Rt(V)}let N=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),z=(oe)=>{let Q=oe.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,V=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>xe.existsSync(Q)).map((Q)=>xe.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let K of Object.values(Q.resources)){if(!xe.existsSync(K))continue;let J=xe.realpathSync(K);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Q,K]of N)if(!oe.has(Q))K.close(),N.delete(Q);for(let Q of oe)if(!N.has(Q)&&xe.existsSync(Q))N.set(Q,xe.watch(Q,{recursive:!0},(K,J)=>{We(Q,K,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},ve=Promise.resolve(),We=(oe,Q,K)=>(ve=ve.catch(()=>{}).then(()=>Ge(oe,Q,K)),ve),Ge=async(oe,Q,K)=>{if(!K||At(K))return;if(Pt(K)){if(g._layerGraph){let J=await y(u);Object.assign(g,J),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[R,...J._layerPageDirs.slice(1)]:void 0})),V()}if(A(K)){if(console.log(`${e.cyan}${K} changed${e.reset}`),c&&l)l.reload(K)}else if(z(K)){console.log(`${e.yellow}${K} changed, rebuilding...${e.reset}`),he.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-hs90en70.js");J(ie.resolve(oe,K)),ke.delete(ie.resolve(oe,K))}catch{}if(I&&K){if(ie.resolve(oe,K)===I||ie.basename(I)===K){let ke=await gr(I,s.stxOptions||{});if(ke)P=ke}}if(await qe(),await Zt(u),c&&l)l.reload(K)}else{console.log(`${e.yellow}${K} changed, rebuilding...${e.reset}`),he.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-hs90en70.js");J(ie.resolve(oe,K)),ke.delete(ie.resolve(oe,K))}catch{}if(await qe(),c&&l)l.reload(K)}}else if(Et(K)){if(console.log(`${e.cyan}CSS ${K} changed${e.reset}`),c&&l)l.updateCss(K)}};V(),process.on("SIGINT",()=>{for(let oe of N.values())oe.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 o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let p=o[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(),o=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
1436
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Zr(t,s=!1,o){let p=yt.basename(t,".stx"),c=await Yr(t),l=await Qr(t),m="";if(s&&o)m=`<${o}></${o}>`;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 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)
1439
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:o}}async function xn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await xn(c);o.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))o.push(c)}return o}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function es(t,s){try{if(!await n(t))return[];let o=await xn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of o){let m=c.get(l),u=!!m,y=m?.tag,g=await Zr(l,u,y);p.push(g)}return p}catch(o){return console.error("Error generating component docs:",o),[]}}async function ts(t){try{if(!await n(t))return[];let s=await Vt.promises.readdir(t,{withFileTypes:!0}),o=[];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]);o.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return o}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(It.
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 rs(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 o of t)s.push({name:o.name,description:o.description||"",hasEndTag:o.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function ss(t=[],s=[],o=[],p){let c=`# stx Documentation
1461
1461
 
1462
1462
  `;if(p)c+=`${p}
1463
1463
 
@@ -1487,19 +1487,19 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(It.
1487
1487
 
1488
1488
  `;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
1489
1489
 
1490
- `}}if(a.length>0){c+=`## Directives
1490
+ `}}if(o.length>0){c+=`## Directives
1491
1491
 
1492
1492
  `,c+=`| Directive | Description | Has End Tag |
1493
1493
  `,c+=`| --------- | ----------- | ----------- |
1494
- `;for(let l of a)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1494
+ `;for(let l of o)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
1495
  `;c+=`
1496
- `;for(let l of a)if(l.example)c+=`### @${l.name}
1496
+ `;for(let l of o)if(l.example)c+=`### @${l.name}
1497
1497
 
1498
1498
  `,c+=`${l.description||""}
1499
1499
 
1500
1500
  `,c+=`#### Example
1501
1501
 
1502
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ss(t=[],s=[],a=[],p){let c=`<!DOCTYPE html>
1502
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function os(t=[],s=[],o=[],p){let c=`<!DOCTYPE html>
1503
1503
  <html lang="en">
1504
1504
  <head>
1505
1505
  <meta charset="UTF-8">
@@ -1558,7 +1558,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(It.
1558
1558
  <td>${m.required?"Yes":"No"}</td>
1559
1559
  <td>${m.default||"-"}</td>
1560
1560
  <td>${m.description||"-"}</td>
1561
- </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(a.length>0){c+="<h2>Directives</h2>",c+=`<table>
1561
+ </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(o.length>0){c+="<h2>Directives</h2>",c+=`<table>
1562
1562
  <thead>
1563
1563
  <tr>
1564
1564
  <th>Directive</th>
@@ -1566,27 +1566,27 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(It.
1566
1566
  <th>Has End Tag</th>
1567
1567
  </tr>
1568
1568
  </thead>
1569
- <tbody>`;for(let l of a)c+=`<tr>
1569
+ <tbody>`;for(let l of o)c+=`<tr>
1570
1570
  <td>@${l.name}</td>
1571
1571
  <td>${l.description||"-"}</td>
1572
1572
  <td>${l.hasEndTag?"Yes":"No"}</td>
1573
- </tr>`;c+="</tbody></table>";for(let l of 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,`
1573
+ </tr>`;c+="</tbody></table>";for(let l of o)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 is(t=[],s=[],o=[],p){return JSON.stringify({components:t,templates:s,directives:o,extraContent:p||""},null,2)}async function as(t){try{let{componentsDir:s,templatesDir:o,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(o)console.log(`Templates directory: ${o}`);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&&o)console.log("Generating template documentation..."),y=await ts(o),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=ss(u,y,g,w),E="md";break;case"html":S=os(u,y,g,w),E="html";break;case"json":S=is(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 Ns(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},o=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return as({componentsDir:o,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var Sn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function or(t,s={}){let o={...Sn,...s};if(t.trim()==="")return`
1574
+ `;let p=t;if(o.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=ds(p,o),p=ms(p,o),p=ps(p,o),o.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 qs(t,s={}){let a={...yn,...s};if(t.trim()==="")return`
1578
+ `;return p}function Ls(t,s={}){let o={...Sn,...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=mr(S,a).trimEnd().split(`
1581
+ `),v=or(S,o).trimEnd().split(`
1582
1582
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
1583
  `);return`${l}\`\`\`${m}
1584
1584
  ${v}
1585
- ${l}\`\`\``}),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1585
+ ${l}\`\`\``}),o.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1586
1586
  `).replace(/\r/g,`
1587
1587
  `),!p.endsWith(`
1588
1588
  `))p+=`
1589
- `;return p}function 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,`
1589
+ `;return p}function ls(t){let s=t,o=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=o.length;return o.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
@@ -1597,13 +1597,13 @@ $1
1597
1597
  `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let y=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&y.match(new RegExp(`^</${g}>`)))return c;return`
1598
1598
  ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,y)=>{let g=y.substring(Math.max(0,u-50),u),w=y.substring(u+c.length,Math.min(y.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1599
1599
  ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&y.match(b))return c;return`${c}
1600
- `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>a[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1600
+ `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>o[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 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>
1603
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function ds(t,s){let p=ls(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(vn(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"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||us(b),I=vn(b);if(L||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(F)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
+ `)}function ps(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,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 o=t.match(/<(\w+)/);if(o){let p=o[1];return s.includes(p.toLowerCase())}return!1}function vn(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 o of s)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function ms(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,p,c)=>{if(!c.trim())return o;if(c.includes("<")||c.includes(`
1606
+ `)||c.includes("@"))return o;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 kn from"fs";import qt from"path";async function js(t="index.stx",s={}){try{let o=s.force||!1,p=qt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!o)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=qt.dirname(p);if(!kn.existsSync(c))kn.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=Tn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=Tn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(o){return console.error(`Error creating file: ${o instanceof Error?o.message:String(o)}`),!1}}function Tn(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 = [
@@ -2029,5 +2029,5 @@ const features = [
2029
2029
  })();
2030
2030
  </script>
2031
2031
  </body>
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};
2032
+ </html>`}var Bs="f9c3713";function $o(t){return t}function Eo(t){return t}function Ds(t,s){let o=[],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)o.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))o.push(m),c++}}return o}import _e from"fs";import $e from"path";function Mn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let o=Math.max(0,Math.round((s-t)/1000));if(o<60)return`${o}s ago`;if(o<3600)return`${Math.round(o/60)}m ago`;return`${Math.round(o/3600)}h ago`}function Di(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function _n(t,s="stx"){let o=$e.resolve(t);for(let p=0;p<10;p++){let c=$e.join(o,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=$e.dirname(o);if(l===o)break;o=l}return null}var Ln=["@stacksjs/stx","bun-plugin-stx"];function Mi(t){try{let s=_e.readFileSync($e.join(t,"package.json"),"utf8"),o=JSON.parse(s)?.version;return typeof o==="string"?o:null}catch{return null}}function _i(t,s=6){let o=$e.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=$e.join(u,w),E=Mi(S);if(E!==null)p.push({name:w,version:E,dir:$e.relative(o,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=$e.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=$e.join(S,x.name,"node_modules");if(_e.existsSync(R))l(R,y+1)}continue}let E=$e.join(S,"node_modules");if(_e.existsSync(E))l(E,y+1)}}let m=$e.join(o,"node_modules");if(_e.existsSync(m))l(m,0);return p}function Li(t){let s=[];for(let o of Ln){let p=t.filter((m)=>m.name===o);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:`${o} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${o} 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 ${o}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${o}/package.json' -exec grep -H '"version"' {} +`})}return s}async function ar(t={}){let s=t.cwd?$e.resolve(t.cwd):process.cwd(),o=t.resolve??Di,p=Date.now(),c=[],l=o("@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=o("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=$e.join(u,"src/signals.ts"),g=[$e.join(u,"dist/index.js"),$e.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 (${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=$e.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 cr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let p of t.checks)if(o.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)o.push(` \u2192 ${p.fix}`);return o.push(""),o.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),o.join(`
2033
+ `)}export{Ds,Os,Ms,Ns,or,Ls,js,Bs,$o,Eo,ar,cr,gn,mn,hn};