@stacksjs/stx 0.2.421 → 0.2.423

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 (251) hide show
  1. package/dist/{chunk-ep5jnqdb.js → chunk-02n071n7.js} +6 -6
  2. package/dist/chunk-03n23sh6.js +2 -0
  3. package/dist/chunk-07mxghsz.js +2 -0
  4. package/dist/{chunk-kjkwycce.js → chunk-0bmc75w6.js} +4 -4
  5. package/dist/{chunk-hyak4dzg.js → chunk-0hhq9hbq.js} +3 -3
  6. package/dist/{chunk-66k7yxnr.js → chunk-12pvnn1e.js} +4 -4
  7. package/dist/chunk-1497wcxc.js +2 -0
  8. package/dist/chunk-17n9e5wk.js +2 -0
  9. package/dist/chunk-1p8hc1ve.js +2 -0
  10. package/dist/chunk-1r3ghgsz.js +2 -0
  11. package/dist/{chunk-r8wze9ym.js → chunk-24e7qjb8.js} +2 -2
  12. package/dist/chunk-259ecbwa.js +2 -0
  13. package/dist/chunk-26gfsa9w.js +2 -0
  14. package/dist/{chunk-3ynkg5dz.js → chunk-2bpjq1qz.js} +2 -2
  15. package/dist/{chunk-11ra3sbc.js → chunk-2x9jd5w0.js} +3 -3
  16. package/dist/{chunk-k31fwm2w.js → chunk-3hmy75tw.js} +5 -5
  17. package/dist/{chunk-12b8akfg.js → chunk-3pxp0r0a.js} +3 -3
  18. package/dist/{chunk-x5ks23vx.js → chunk-3ry9ca1s.js} +2 -2
  19. package/dist/{chunk-th9s15es.js → chunk-45rfv3a5.js} +2 -2
  20. package/dist/chunk-47apfsxp.js +2 -0
  21. package/dist/{chunk-ax58cds3.js → chunk-48kgnqpk.js} +4 -4
  22. package/dist/{chunk-rsxvbnp4.js → chunk-4hd5wb8x.js} +3 -3
  23. package/dist/chunk-535nrr6j.js +2 -0
  24. package/dist/chunk-5mfhk69g.js +2 -0
  25. package/dist/{chunk-aync8qmk.js → chunk-5vwg3h5g.js} +2 -2
  26. package/dist/{chunk-tspmynvh.js → chunk-62chbqev.js} +1 -1
  27. package/dist/chunk-6c7294j8.js +2 -0
  28. package/dist/{chunk-z0ck9t6j.js → chunk-6cbvx87h.js} +5 -5
  29. package/dist/{chunk-kea18wnc.js → chunk-6fsbny9m.js} +3 -3
  30. package/dist/chunk-6gh2rvyz.js +2 -0
  31. package/dist/chunk-6j6gbp0y.js +2 -0
  32. package/dist/chunk-6jgjmycb.js +2 -0
  33. package/dist/{chunk-hjp990p8.js → chunk-6t278w29.js} +2 -2
  34. package/dist/{chunk-5vfyxxrp.js → chunk-6t7mxb0b.js} +2 -2
  35. package/dist/chunk-6wmxrn6x.js +2 -0
  36. package/dist/chunk-6wweqfg7.js +2 -0
  37. package/dist/{chunk-h1h6xe1k.js → chunk-7a9h7ycs.js} +5 -5
  38. package/dist/chunk-7pbv9mg7.js +2 -0
  39. package/dist/{chunk-09hhrjk9.js → chunk-89b2r1q0.js} +6 -6
  40. package/dist/{chunk-0varh725.js → chunk-8a0r2j8f.js} +3 -3
  41. package/dist/{chunk-pzngjk81.js → chunk-8nsbf2mz.js} +1074 -1074
  42. package/dist/{chunk-mg13q1kd.js → chunk-8zf5q1m3.js} +2 -2
  43. package/dist/chunk-9d53d0t6.js +2 -0
  44. package/dist/chunk-9j72har9.js +2 -0
  45. package/dist/chunk-9yqz5ge5.js +2 -0
  46. package/dist/chunk-a5c9n7an.js +2 -0
  47. package/dist/chunk-a836zn7c.js +2 -0
  48. package/dist/{chunk-8vq0qjq9.js → chunk-a8g6y9kw.js} +5 -5
  49. package/dist/{chunk-21a7p956.js → chunk-acwgap78.js} +1 -1
  50. package/dist/{chunk-qx3js9tk.js → chunk-aen2baze.js} +1 -1
  51. package/dist/chunk-ahgrkva8.js +2 -0
  52. package/dist/chunk-akbb6j7s.js +2 -0
  53. package/dist/chunk-avakcrbs.js +2 -0
  54. package/dist/{chunk-tafebmtg.js → chunk-axydabse.js} +2 -2
  55. package/dist/{chunk-4n6c5rp5.js → chunk-b7973zvk.js} +2 -2
  56. package/dist/{chunk-debz86rr.js → chunk-bxwe7wxj.js} +10 -10
  57. package/dist/{chunk-2ewa2sg5.js → chunk-c1dmr865.js} +3 -3
  58. package/dist/chunk-cenq2n6e.js +2 -0
  59. package/dist/{chunk-zvh2nnzr.js → chunk-cf6htz63.js} +1 -1
  60. package/dist/chunk-cnmz9543.js +2 -0
  61. package/dist/{chunk-bh4x090w.js → chunk-cx2rdew4.js} +13 -13
  62. package/dist/{chunk-wg1ttvs5.js → chunk-cznsm2n3.js} +2 -2
  63. package/dist/chunk-d1qzhawc.js +2 -0
  64. package/dist/chunk-d6hnvwre.js +2 -0
  65. package/dist/{chunk-014gmm8w.js → chunk-dcwjxq8n.js} +2 -2
  66. package/dist/chunk-dhqwg62x.js +2 -0
  67. package/dist/{chunk-z521cyfv.js → chunk-dmd6yk2x.js} +5 -5
  68. package/dist/chunk-e18qfegt.js +2 -0
  69. package/dist/chunk-eej89wkt.js +2 -0
  70. package/dist/chunk-ekxffxbd.js +2 -0
  71. package/dist/{chunk-hy9e3ny6.js → chunk-ex0tq6x2.js} +1 -1
  72. package/dist/{chunk-8drvzsk1.js → chunk-fg5ve6ey.js} +2 -2
  73. package/dist/{chunk-3kmhv1kf.js → chunk-fnt1q1sp.js} +11 -11
  74. package/dist/chunk-g67gg66e.js +2 -0
  75. package/dist/chunk-gq16fxc2.js +2 -0
  76. package/dist/{chunk-4e101kjp.js → chunk-h3c7z73m.js} +2 -2
  77. package/dist/chunk-h4avjh3q.js +2 -0
  78. package/dist/chunk-h7qte7ye.js +2 -0
  79. package/dist/{chunk-4mew0ae3.js → chunk-hb9gxad0.js} +3 -3
  80. package/dist/{chunk-0y7x0hvr.js → chunk-hg4k3nkr.js} +1 -1
  81. package/dist/{chunk-dhxbjw6k.js → chunk-hnep9jbj.js} +2 -2
  82. package/dist/chunk-hwycbxg7.js +2 -0
  83. package/dist/{chunk-34gy5zjm.js → chunk-j1q65enz.js} +2 -2
  84. package/dist/chunk-j5myfxe8.js +18 -0
  85. package/dist/{chunk-8jqy69td.js → chunk-j7zywbq0.js} +2 -2
  86. package/dist/{chunk-32y3767j.js → chunk-jbrdebzs.js} +7 -7
  87. package/dist/{chunk-1336h4sv.js → chunk-jj4pyeyj.js} +1 -1
  88. package/dist/{chunk-g1fxmp9z.js → chunk-k8sqs7j2.js} +4 -4
  89. package/dist/chunk-mg7jhx5v.js +2 -0
  90. package/dist/chunk-n16wa755.js +2 -0
  91. package/dist/chunk-ngv1c807.js +2 -0
  92. package/dist/{chunk-krr2vb0s.js → chunk-p2x7tjbt.js} +3 -3
  93. package/dist/{chunk-62r4fa4q.js → chunk-ptjqacjd.js} +2 -2
  94. package/dist/{chunk-rj3hyqff.js → chunk-qm1tt8g1.js} +2334 -2334
  95. package/dist/chunk-r7r5h2eh.js +2 -0
  96. package/dist/chunk-rhkx17d9.js +2 -0
  97. package/dist/{chunk-b1fg9vg7.js → chunk-s28eh0jn.js} +2 -2
  98. package/dist/{chunk-10967rws.js → chunk-s295vp9x.js} +3 -3
  99. package/dist/chunk-sazpw71r.js +4 -0
  100. package/dist/{chunk-20tdz0zs.js → chunk-sbdzqqr1.js} +6 -6
  101. package/dist/{chunk-qby6wxat.js → chunk-spx27cs4.js} +2 -2
  102. package/dist/{chunk-m16h8ea0.js → chunk-stxmwytg.js} +2 -2
  103. package/dist/{chunk-2tfe2g58.js → chunk-t3wh1jbk.js} +6 -6
  104. package/dist/{chunk-802pr252.js → chunk-tfexmdkt.js} +2 -2
  105. package/dist/{chunk-6aqcgrhw.js → chunk-tfz95n7j.js} +5 -5
  106. package/dist/chunk-thdbqsxq.js +2 -0
  107. package/dist/chunk-tpnfcb83.js +2 -0
  108. package/dist/chunk-tqkv4th9.js +2 -0
  109. package/dist/chunk-tznejj9h.js +2 -0
  110. package/dist/{chunk-ap6fehea.js → chunk-vfk725vm.js} +5 -5
  111. package/dist/chunk-vsrm9k7p.js +2 -0
  112. package/dist/chunk-vwms759h.js +2 -0
  113. package/dist/{chunk-xvzxrt9a.js → chunk-w2085fwx.js} +5 -5
  114. package/dist/chunk-w252cgnv.js +30 -0
  115. package/dist/chunk-whdw6dhb.js +2 -0
  116. package/dist/chunk-wtms9jhs.js +3 -0
  117. package/dist/chunk-wtqjfar3.js +2 -0
  118. package/dist/chunk-wx7kfet5.js +2 -0
  119. package/dist/chunk-wy873fy8.js +2 -0
  120. package/dist/{chunk-a4r19yxm.js → chunk-xa3wsmt5.js} +11 -11
  121. package/dist/chunk-xrbqf77j.js +2 -0
  122. package/dist/{chunk-757ec865.js → chunk-yaebdyfr.js} +2 -2
  123. package/dist/chunk-ycpq3gxc.js +2 -0
  124. package/dist/chunk-yd50awqp.js +3 -0
  125. package/dist/{chunk-csjw5esc.js → chunk-ydz7w2mt.js} +2 -2
  126. package/dist/chunk-yjgbxf26.js +2 -0
  127. package/dist/{chunk-jjnfj9nf.js → chunk-yqsza22w.js} +2 -2
  128. package/dist/{chunk-8j8k27xb.js → chunk-zbr333kf.js} +115 -31
  129. package/dist/chunk-zcyjdcpx.js +33 -0
  130. package/dist/{chunk-tqnysw0k.js → chunk-zfzcedw4.js} +4 -4
  131. package/dist/chunk-zm73n103.js +2 -0
  132. package/dist/cli.js +21 -21
  133. package/dist/component-renderer.js +54 -2
  134. package/dist/composables/use-outbox.d.ts +1 -0
  135. package/dist/composables/use-outbox.js +14 -4
  136. package/dist/craft-entry.js +2 -2
  137. package/dist/craft.js +2 -2
  138. package/dist/database.js +2 -2
  139. package/dist/native/bridge/protocol.d.ts +5 -0
  140. package/dist/native/bridge/protocol.js +3 -0
  141. package/dist/native/cli.js +12 -2
  142. package/dist/native/compiler/bundle.d.ts +4 -3
  143. package/dist/native/compiler/bundle.js +46 -51
  144. package/dist/native/compiler/component-mapping.d.ts +5 -0
  145. package/dist/native/compiler/component-mapping.js +90 -0
  146. package/dist/native/compiler/html-to-ir.js +42 -6
  147. package/dist/native/compiler/ir.d.ts +2 -0
  148. package/dist/native/compiler/render-screen.d.ts +4 -0
  149. package/dist/native/compiler/render-screen.js +10 -2
  150. package/dist/native/compiler/setup-script.d.ts +6 -0
  151. package/dist/native/compiler/setup-script.js +10 -0
  152. package/dist/native/components/primitives.d.ts +10 -0
  153. package/dist/native/index.d.ts +6 -24
  154. package/dist/native/index.js +1 -17
  155. package/dist/native/primitives/Button.stx +2 -1
  156. package/dist/native/primitives/Text.stx +2 -1
  157. package/dist/native/primitives/TextInput.stx +3 -1
  158. package/dist/native/prop-names.d.ts +2 -0
  159. package/dist/native/prop-names.js +71 -0
  160. package/dist/native/runtime/binding-tree.d.ts +31 -0
  161. package/dist/native/runtime/binding-tree.js +100 -0
  162. package/dist/native/runtime/craft-bridge.d.ts +9 -0
  163. package/dist/native/runtime/craft-bridge.js +231 -0
  164. package/dist/native/runtime/craft.d.ts +28 -3
  165. package/dist/native/runtime/jsc-globals.d.ts +16 -0
  166. package/dist/native/runtime/jsc-globals.js +64 -0
  167. package/dist/native/runtime/native-host.d.ts +3 -1
  168. package/dist/native/runtime/native-host.js +183 -33
  169. package/dist/native/runtime/shared-screen.d.ts +15 -0
  170. package/dist/native/runtime/shared-screen.js +41 -0
  171. package/dist/pwa.js +3 -3
  172. package/dist/signal-processing.d.ts +3 -1
  173. package/dist/signal-processing.js +4 -3
  174. package/dist/signals.js +104 -20
  175. package/dist/ssg.js +28 -28
  176. package/dist/variable-extractor.js +4 -1
  177. package/package.json +5 -5
  178. package/dist/chunk-0n76c3g8.js +0 -2
  179. package/dist/chunk-10fh9qhe.js +0 -2
  180. package/dist/chunk-18awnp9d.js +0 -2
  181. package/dist/chunk-2hswgxpb.js +0 -2
  182. package/dist/chunk-3zye6eh1.js +0 -2
  183. package/dist/chunk-4488r5j1.js +0 -2
  184. package/dist/chunk-4amznxaq.js +0 -2
  185. package/dist/chunk-5akd7qsb.js +0 -2
  186. package/dist/chunk-5eqd40k0.js +0 -2
  187. package/dist/chunk-6r9y4p81.js +0 -2
  188. package/dist/chunk-75zcwcrt.js +0 -2
  189. package/dist/chunk-89e1d0rz.js +0 -4
  190. package/dist/chunk-8nsqac4z.js +0 -2
  191. package/dist/chunk-8ttvazck.js +0 -2
  192. package/dist/chunk-8y4bqsxz.js +0 -2
  193. package/dist/chunk-ac033b93.js +0 -2
  194. package/dist/chunk-aj43359g.js +0 -2
  195. package/dist/chunk-aj8yq228.js +0 -2
  196. package/dist/chunk-as72dvvm.js +0 -2
  197. package/dist/chunk-awtrcb5m.js +0 -18
  198. package/dist/chunk-b01jqb5f.js +0 -2
  199. package/dist/chunk-b7z2yegr.js +0 -2
  200. package/dist/chunk-bfvaxrq0.js +0 -2
  201. package/dist/chunk-bkaw7sgz.js +0 -2
  202. package/dist/chunk-bmk0s261.js +0 -2
  203. package/dist/chunk-bvbank3z.js +0 -2
  204. package/dist/chunk-cvzkbsds.js +0 -2
  205. package/dist/chunk-cw6j75ck.js +0 -30
  206. package/dist/chunk-d2c5727w.js +0 -2
  207. package/dist/chunk-d5amzers.js +0 -2
  208. package/dist/chunk-dfchrqw5.js +0 -2
  209. package/dist/chunk-dscsvkfa.js +0 -2
  210. package/dist/chunk-eav0pt6d.js +0 -2
  211. package/dist/chunk-hahzjyxc.js +0 -2
  212. package/dist/chunk-hgqcqg1h.js +0 -2
  213. package/dist/chunk-hjdwf9gp.js +0 -2
  214. package/dist/chunk-jjm0ekw8.js +0 -2
  215. package/dist/chunk-jjtzm6dn.js +0 -3
  216. package/dist/chunk-k1am0dyg.js +0 -2
  217. package/dist/chunk-m2jphkdv.js +0 -2
  218. package/dist/chunk-mk7b3qdz.js +0 -2
  219. package/dist/chunk-ncvfjcr2.js +0 -2
  220. package/dist/chunk-p083sckk.js +0 -2
  221. package/dist/chunk-p7b17yr0.js +0 -2
  222. package/dist/chunk-pc178389.js +0 -2
  223. package/dist/chunk-q1v0jwr4.js +0 -2
  224. package/dist/chunk-r5gjb55x.js +0 -2
  225. package/dist/chunk-rj8rdd8n.js +0 -2
  226. package/dist/chunk-s0pmn48x.js +0 -2
  227. package/dist/chunk-s58yz9q0.js +0 -2
  228. package/dist/chunk-srdzwtsq.js +0 -2
  229. package/dist/chunk-tf44jyrh.js +0 -2
  230. package/dist/chunk-tfypkw4y.js +0 -3
  231. package/dist/chunk-vwxasbtx.js +0 -2
  232. package/dist/chunk-wynvh7dc.js +0 -2
  233. package/dist/chunk-x8rckpyz.js +0 -2
  234. package/dist/chunk-y4xs4m7p.js +0 -2
  235. package/dist/chunk-y8rpk1b9.js +0 -2
  236. package/dist/chunk-y9m93qkk.js +0 -2
  237. package/dist/chunk-ya0qecph.js +0 -27
  238. package/dist/chunk-ya9c8nec.js +0 -2
  239. package/dist/chunk-yvq1f313.js +0 -2
  240. package/dist/chunk-yy3dgwfm.js +0 -2
  241. package/dist/chunk-zpcz2kh6.js +0 -2
  242. package/dist/native/compiler/codegen.d.ts +0 -10
  243. package/dist/native/compiler/codegen.js +0 -145
  244. package/dist/native/compiler/parser.d.ts +0 -88
  245. package/dist/native/compiler/parser.js +0 -753
  246. package/dist/native/runtime/entry.d.ts +0 -1
  247. package/dist/native/runtime/entry.js +0 -3
  248. package/dist/native/runtime/index.d.ts +0 -45
  249. package/dist/native/runtime/index.js +0 -165
  250. package/dist/native/runtime/screen.d.ts +0 -43
  251. package/dist/native/runtime/screen.js +0 -808
@@ -1,502 +1,77 @@
1
1
  // @bun
2
- import{V,h,Yt,Zt,e,wt,Qt,f,Le,vt,je,Be,Z,M,ae,q,d,ye,Xi,os,r,n,ee,Vn,i,T,ce}from"./chunk-rj3hyqff.js";import{K,ln,te,_,$t}from"./chunk-09hhrjk9.js";import{Ye,fn,nr,rr,sr,Ze,Qe,et,tt,nt,rt,xe}from"./chunk-66k7yxnr.js";import{_e,Ys,ne,C,Zs,yr,Sn,ge,Qs,re}from"./chunk-cw6j75ck.js";import{Rt}from"./chunk-014gmm8w.js";import{Ie}from"./chunk-6aqcgrhw.js";import{a}from"./chunk-tfypkw4y.js";import{D}from"./chunk-jjnfj9nf.js";async function Gn(t){try{let s=await Bun.file(t).text(),o=Jn(s),p=Yn(s,t),c=Qn(s,o),l=Zn(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 Qn(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 Zn(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 Ls(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=er(o);return{results:o,summary:c}}function er(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 tr,readFile as or,readdir as ir,stat as Jt,writeFile as ar}from"fs/promises";import Ee 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 an=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function cr(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 pr(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 ir(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 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 gr(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 hr(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(an.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
-
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 bt(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=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[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=Ee.resolve(Ee.dirname(s),x),B=Ee.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=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await or(p,"utf8"),l=gr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||cr(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(!pr(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,Ee.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=hr(c,p);return{file:Ee.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
-
10
- const escapeHTML = (value) => String(value ?? '')
11
- .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
12
- .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
13
-
14
- const valueAt = (host, path) => {
15
- const parts = path.trim().split('.');
16
- let value = host;
17
- for (const part of parts) value = value?.[part];
18
- return typeof value === 'function' ? value.call(host) : value;
19
- };
20
-
21
- const deserialize = (value, type, fallback) => {
22
- if (value === null) return type === 'boolean' ? false : fallback;
23
- if (type === 'boolean') return value !== 'false' && value !== '0';
24
- if (type === 'number') return Number(value);
25
- if (type === 'object' || type === 'array') {
26
- try { return JSON.parse(value); }
27
- catch { return fallback; }
28
- }
29
- return value;
30
- };
31
-
32
- const serialize = (value, type) => {
33
- if (value == null || value === false) return null;
34
- if (type === 'boolean') return '';
35
- if (type === 'object' || type === 'array') return JSON.stringify(value);
36
- return String(value);
37
- };
38
-
39
- const cloneDefault = (value, type) => {
40
- if (value == null || (type !== 'object' && type !== 'array')) return value;
41
- if (typeof structuredClone === 'function') return structuredClone(value);
42
- return JSON.parse(JSON.stringify(value));
43
- };
44
-
45
- const defaultFor = property => cloneDefault(
46
- property.default ?? ({ string: '', number: 0, boolean: false, object: {}, array: [] })[property.type],
47
- property.type,
48
- );
49
-
50
- export class StxElement extends HTMLElementBase {
51
- static definition = {};
52
- static get observedAttributes() { return this.definition.observedAttributes || []; }
53
-
54
- constructor() {
55
- super();
56
- this._values = Object.create(null);
57
- this._reflecting = false;
58
- this._connected = false;
59
- this._hasConnected = false;
60
- this._initializing = false;
61
- this._updatePending = false;
62
- this._listeners = new Map();
63
- const definition = this.constructor.definition;
64
- for (const [name, property] of Object.entries(definition.properties || {})) {
65
- this._values[name] = defaultFor(property);
2
+ import{K,un,te,_,Et}from"./chunk-89b2r1q0.js";import{Ze,gn,sr,ir,or,Qe,et,tt,nt,rt,st,xe}from"./chunk-12pvnn1e.js";import{U,h,Zt,Qt,e,wt,en,f,je,xt,Be,Fe,Z,M,ae,q,d,ye,Yi,cs,n,r,ee,Wn,i,T,ce}from"./chunk-qm1tt8g1.js";import{_e,ei,ne,C,ti,vr,kn,ge,ni,re}from"./chunk-w252cgnv.js";import{At}from"./chunk-dcwjxq8n.js";import{De}from"./chunk-tfz95n7j.js";import{a}from"./chunk-wtms9jhs.js";import{D}from"./chunk-yqsza22w.js";function Bs(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}var{serve:nr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
3
+ /* Theme selector for code blocks */
4
+ .theme-selector {
5
+ margin: 1rem 0;
6
+ padding: 0.5rem;
7
+ background: #f8f8f8;
8
+ border-radius: 4px;
9
+ text-align: right;
66
10
  }
67
- if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
68
- this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
11
+ select {
12
+ padding: 0.25rem 0.5rem;
13
+ border-radius: 3px;
14
+ border: 1px solid #ddd;
69
15
  }
70
- }
71
-
72
- get updateComplete() { return this._updateComplete || Promise.resolve(); }
73
- get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
74
16
 
75
- connectedCallback() {
76
- if (this._connected) return;
77
- this._connected = true;
78
- this._initializing = true;
79
- const definition = this.constructor.definition;
80
- for (const [name, property] of Object.entries(definition.properties || {})) {
81
- const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
82
- if (attribute && this.hasAttribute?.(attribute)) this._values[name] = deserialize(this.getAttribute(attribute), property.type, defaultFor(property));
83
- }
84
- // Properties assigned before customElements.define() become own properties.
85
- // Upgrade them after attributes so imperative state wins, matching the
86
- // platform's property-first custom-element initialization convention.
87
- for (const name of Object.keys(definition.properties || {})) this._upgradeProperty(name);
88
- this._initializing = false;
89
- const root = this.renderRoot;
90
- const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
91
- const firstConnection = !this._hasConnected;
92
- if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
93
- else this._upgradeDeclarativeEvents();
94
- this._bindEvents();
95
- if (firstConnection) {
96
- this._hasConnected = true;
97
- this.setAttribute?.('hydrated', '');
98
- this.dispatchEvent?.(new CustomEvent('stx:hydrated', { bubbles: true, composed: true }));
17
+ /* Dark mode body styles */
18
+ body.dark-mode {
19
+ background-color: #121212;
20
+ color: #e1e4e8;
99
21
  }
100
- // Called last, so a component that acquires something sees its own rendered
101
- // markup and its events already bound. Reported rather than rethrown: a
102
- // component that fails to set up must not take the element down with it.
103
- try { this.onConnect?.(); }
104
- catch (error) { console.error('[stx] onConnect failed', error); }
105
- }
106
22
 
107
- disconnectedCallback() {
108
- this._connected = false;
109
- // Called before the framework releases anything, so the element is still
110
- // intact for a component that needs to read it on the way out, and inside
111
- // try/finally so a throwing hook cannot leak the framework's own listeners.
112
- try { this.onDisconnect?.(); }
113
- catch (error) { console.error('[stx] onDisconnect failed', error); }
114
- finally {
115
- for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
116
- this._listeners.clear();
23
+ body.dark-mode h1,
24
+ body.dark-mode h2,
25
+ body.dark-mode h3 {
26
+ color: #e1e4e8;
27
+ border-color: #2f363d;
117
28
  }
118
- }
119
29
 
120
- attributeChangedCallback(attribute, oldValue, newValue) {
121
- if (oldValue === newValue || this._reflecting) return;
122
- const definition = this.constructor.definition;
123
- const name = definition.attributeToProperty?.[attribute];
124
- if (!name) return;
125
- const property = definition.properties[name];
126
- const value = deserialize(newValue, property.type, defaultFor(property));
127
- if (!Object.is(this._values[name], value)) {
128
- this._values[name] = value;
129
- this.requestUpdate();
30
+ body.dark-mode .theme-selector {
31
+ background: #2f363d;
32
+ color: #e1e4e8;
130
33
  }
131
- }
132
34
 
133
- /**
134
- * The props a compiled render reads.
135
- *
136
- * Its own method rather than _values directly, so a component that sets a
137
- * property before upgrade still sees it, and so the generated code has one
138
- * name to depend on rather than a private field's shape.
139
- */
140
- _props() {
141
- return this._values;
142
- }
35
+ body.dark-mode select {
36
+ background: #24292e;
37
+ color: #e1e4e8;
38
+ border-color: #444;
39
+ }
143
40
 
144
- requestUpdate() {
145
- if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
146
- this._updatePending = true;
147
- this._updateComplete = new Promise((resolve) => {
148
- queueMicrotask(() => {
149
- this._updatePending = false;
150
- if (this._connected) this._render();
151
- resolve();
152
- });
153
- });
154
- return this._updateComplete;
155
- }
41
+ body.dark-mode blockquote {
42
+ background: #24292e;
43
+ color: #e1e4e8;
44
+ }
156
45
 
157
- emit(name, detail, options = {}) {
158
- return this.dispatchEvent(new CustomEvent(name, {
159
- detail, bubbles: true, composed: true, ...options,
160
- }));
161
- }
46
+ body.dark-mode .frontmatter {
47
+ background: #24292e;
48
+ }
162
49
 
163
- _upgradeProperty(name) {
164
- if (!Object.prototype.hasOwnProperty.call(this, name)) return;
165
- const value = this[name];
166
- delete this[name];
167
- this[name] = value;
168
- }
50
+ body.dark-mode a {
51
+ color: #58a6ff;
52
+ }`}function vt(t){return`
53
+ <div class="theme-selector">
54
+ Theme:
55
+ <select id="themeSelector" onchange="changeTheme()">
56
+ ${t}
57
+ </select>
58
+ </div>`}function St(){return`
59
+ function changeTheme() {
60
+ const theme = document.getElementById('themeSelector').value;
169
61
 
170
- _upgradeDeclarativeEvents() {
171
- for (const element of this.renderRoot.querySelectorAll?.('*') || []) {
172
- const names = element.getAttributeNames?.() || [...(element.attributes || [])].filter(Boolean).map(attribute => attribute.name);
173
- for (const attributeName of names) {
174
- if (!attributeName?.startsWith('@')) continue;
175
- const [event, ...modifiers] = attributeName.slice(1).split('.');
176
- element.setAttribute('data-stx-on-' + event, element.getAttribute(attributeName));
177
- if (modifiers.length) element.setAttribute('data-stx-mod-' + event, modifiers.join(' '));
178
- element.removeAttribute(attributeName);
179
- }
180
- }
181
- }
182
-
183
- _bindEvents() {
184
- for (const event of this.constructor.definition.eventTypes || []) {
185
- if (this._listeners.has(event)) continue;
186
- const listener = ($event) => {
187
- const selector = '[data-stx-on-' + event + ']';
188
- const target = $event.target?.closest?.(selector);
189
- if (!target || !this.renderRoot.contains(target)) return;
190
- const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
191
- if (modifiers.includes('prevent')) $event.preventDefault();
192
- if (modifiers.includes('stop')) $event.stopPropagation();
193
- const method = target.getAttribute('data-stx-on-' + event);
194
- if (typeof this[method] === 'function') this[method]($event);
195
- };
196
- this.renderRoot.addEventListener(event, listener);
197
- this._listeners.set(event, listener);
198
- }
199
- }
200
-
201
- _render() {
202
- const definition = this.constructor.definition;
203
- const root = this.renderRoot;
204
- const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
205
- const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
206
- const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
207
- // A compiled component renders itself: the control flow and the derived
208
- // values were turned into JavaScript at build time, so there is nothing to
209
- // interpret here and nothing that needs an eval the page's CSP forbids.
210
- // The string template remains for components that carry no logic.
211
- let html = typeof this.render === 'function'
212
- ? this.render(RENDER_HELPERS)
213
- : definition.template
214
- .replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
215
- .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
216
- if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
217
- root.innerHTML = html;
218
- this._applyBindings();
219
- this._bindEvents();
220
- if (focusKey) {
221
- const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
222
- const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
223
- next?.focus?.();
224
- if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
225
- }
226
- this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
227
- }
228
-
229
- _applyBindings() {
230
- for (const binding of this.constructor.definition.bindings || []) {
231
- const element = this.renderRoot.querySelector('[data-stx-bind-' + binding.id + ']');
232
- if (!element) continue;
233
- const value = valueAt(this, binding.expression);
234
- if (binding.name === 'class') element.className = value || '';
235
- else if (binding.name === 'style' && typeof value === 'object') {
236
- Object.assign(element.style, value);
237
- }
238
- else if (typeof value === 'boolean') {
239
- element.toggleAttribute(binding.name, value);
240
- if (binding.name in element) element[binding.name] = value;
241
- }
242
- else if (value == null || value === false) element.removeAttribute(binding.name);
243
- else element.setAttribute(binding.name, String(value));
244
- }
245
- }
246
- }
247
-
248
- /**
249
- * What a compiled render is handed.
250
- *
251
- * Passed in rather than closed over so the generated code names no globals, and
252
- * a component module stays readable on its own: __escape is visibly a
253
- * parameter, not something the bundler happened to leave in scope.
254
- */
255
- const RENDER_HELPERS = {
256
- escape: escapeHTML,
257
- // The raw form is the author declaring the value is markup. Null becomes an
258
- // empty string rather than the word "null", which is the only sensible
259
- // reading of a missing fragment.
260
- raw: (value) => String(value ?? ''),
261
- // A loop over something absent runs zero times. Throwing here would fail a
262
- // whole page over one empty list, which is never what the author meant.
263
- values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
264
- entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
265
- };
266
-
267
- export function defineComponent(Component, definition) {
268
- const properties = definition.properties || {};
269
- const attributeToProperty = {};
270
- const observedAttributes = [];
271
- for (const [name, property] of Object.entries(properties)) {
272
- const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
273
- if (attribute) {
274
- attributeToProperty[attribute] = name;
275
- observedAttributes.push(attribute);
276
- }
277
- Object.defineProperty(Component.prototype, name, {
278
- configurable: true,
279
- enumerable: true,
280
- get() { return this._values[name]; },
281
- set(value) {
282
- const oldValue = this._values[name];
283
- if (Object.is(oldValue, value)) return;
284
- this._values[name] = value;
285
- if (property.reflect && attribute && !this._reflecting) {
286
- const serialized = serialize(value, property.type);
287
- this._reflecting = true;
288
- if (serialized === null) this.removeAttribute(attribute);
289
- else this.setAttribute(attribute, serialized);
290
- this._reflecting = false;
291
- }
292
- this.requestUpdate();
293
- this.dispatchEvent?.(new CustomEvent(name + '-changed', {
294
- detail: { value, oldValue }, bubbles: true, composed: true,
295
- }));
296
- },
297
- });
298
- }
299
- Component.definition = { ...definition, attributeToProperty, observedAttributes };
300
- const registry = globalThis.customElements || globalThis.window?.customElements;
301
- if (registry && !registry.get(definition.tag)) {
302
- registry.define(definition.tag, Component);
303
- }
304
- return Component;
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),o=Object.entries(t.methods).map(([u,y])=>{if(an.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
- ${y}
308
- }`}).join(`
309
-
310
- `),p=t.scope,c=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
311
- `).map((y)=>y.trim()===""?y:` ${y}`).join(`
312
- `),m="";if(t.render.trim()!==""||p.body!==""||c!==""){let u=[c?`const { ${c} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
313
- `),y;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
314
- ${u}
315
- }`),b=g.indexOf("{"),w=g.lastIndexOf("}");y=g.slice(b+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
316
- render(__helpers) {
317
- const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
318
- ${l(y.trim())}
319
- }
320
- `}return`import { StxElement, defineComponent } from './runtime.js';
321
- ${p.imports.length?`${p.imports.join(`
322
- `)}
323
- `:""}
324
- /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
325
- export class ${t.name} extends StxElement {
326
- ${o}${m}
327
- }
328
-
329
- defineComponent(${t.name}, ${s});
330
- export default ${t.name};
331
- `}function xt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Mr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${xt(m)}`).join(`
332
- `),o=Object.entries(t.properties).map(([l,m])=>` ${l}: ${xt(m)}`).join(`
333
- `),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
334
- `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
335
- `);return`export interface ${t.name}Props {
336
- ${s}
337
- }
338
-
339
- export interface ${t.name}EventMap {
340
- ${p}
341
- }
342
-
343
- export declare class ${t.name} extends HTMLElement {
344
- ${o}
345
- ${c}
346
- readonly updateComplete: Promise<void>
347
- requestUpdate(): Promise<void>
348
- emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
349
- }
350
-
351
- declare global {
352
- interface HTMLElementTagNameMap {
353
- ${JSON.stringify(t.tag)}: ${t.name}
354
- }
355
- }
356
-
357
- export default ${t.name}
358
- `}function _r(t){return`declare global {
359
- namespace JSX {
360
- interface IntrinsicElements {
361
- ${t.map((o)=>{let p=Object.entries(o.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${xt(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
- ${p}
365
- ${c}
366
- children?: unknown
367
- slot?: string
368
- class?: string
369
- className?: string
370
- }`}).join(`
371
- `)}
372
- }
373
- }
374
- }
375
-
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(([o,p])=>({kind:"field",name:o,description:p.description,type:{text:xt(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
- ${s}
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
- `);return`const definitions = ${JSON.stringify(c,null,2)};
381
- const escapeHTML = (value) => String(value ?? '')
382
- .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
383
- .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
384
- const valueAt = (values, path) => path.trim().split('.').reduce((value, part) => value?.[part], values);
385
-
386
- export function renderComponent(tag, props = {}, slots = {}) {
387
- const definition = definitions[tag];
388
- if (!definition) throw new Error('Unknown STX component: ' + tag);
389
- const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
390
- Object.assign(values, props);
391
- let template = definition.template
392
- .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
393
- .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
394
- .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
395
- const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
396
- if (property.attribute === false || !(name in props)) return [];
397
- const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
398
- const value = props[name];
399
- if (value == null || value === false) return [];
400
- if (value === true) return [attribute];
401
- const serialized = typeof value === 'object' ? JSON.stringify(value) : value;
402
- return [attribute + '=\\"' + escapeHTML(serialized) + '\\"'];
403
- }).join(' ');
404
- if (definition.shadowMode) {
405
- template = '<template shadowrootmode="' + definition.shadowMode + '">' +
406
- (definition.styles ? '<style>' + definition.styles + '</style>' : '') + template + '</template>' +
407
- String(slots.default ?? '');
408
- }
409
- return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
410
- }
411
-
412
- ${l}
413
- `}async function js(t){let s=Ee.resolve(t.inputDir),o=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 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 tr(o,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(o,x);return await ar(k,R.endsWith(`
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: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
- `);if(await g("index.js",b),await g("ssr.js",Ir(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
- `)),await g("custom-elements.d.ts",_r(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
418
- `)}
419
- export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
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(rn).join(`
422
-
423
- `);if(x)S=await g("bundle.css",t.minify?sn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.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
- `);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(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
- /* Theme selector for code blocks */
429
- .theme-selector {
430
- margin: 1rem 0;
431
- padding: 0.5rem;
432
- background: #f8f8f8;
433
- border-radius: 4px;
434
- text-align: right;
435
- }
436
- select {
437
- padding: 0.25rem 0.5rem;
438
- border-radius: 3px;
439
- border: 1px solid #ddd;
440
- }
441
-
442
- /* Dark mode body styles */
443
- body.dark-mode {
444
- background-color: #121212;
445
- color: #e1e4e8;
446
- }
447
-
448
- body.dark-mode h1,
449
- body.dark-mode h2,
450
- body.dark-mode h3 {
451
- color: #e1e4e8;
452
- border-color: #2f363d;
453
- }
454
-
455
- body.dark-mode .theme-selector {
456
- background: #2f363d;
457
- color: #e1e4e8;
458
- }
459
-
460
- body.dark-mode select {
461
- background: #24292e;
462
- color: #e1e4e8;
463
- border-color: #444;
464
- }
465
-
466
- body.dark-mode blockquote {
467
- background: #24292e;
468
- color: #e1e4e8;
469
- }
470
-
471
- body.dark-mode .frontmatter {
472
- background: #24292e;
473
- }
474
-
475
- body.dark-mode a {
476
- color: #58a6ff;
477
- }`}function kt(t){return`
478
- <div class="theme-selector">
479
- Theme:
480
- <select id="themeSelector" onchange="changeTheme()">
481
- ${t}
482
- </select>
483
- </div>`}function Tt(){return`
484
- function changeTheme() {
485
- const theme = document.getElementById('themeSelector').value;
486
-
487
- // Toggle dark mode class based on theme
488
- // Dark themes typically include these keywords in their names
489
- if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
490
- theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
491
- document.body.classList.add('dark-mode');
492
- }
493
- else {
494
- document.body.classList.remove('dark-mode');
62
+ // Toggle dark mode class based on theme
63
+ // Dark themes typically include these keywords in their names
64
+ if (theme.includes('dark') || theme.includes('night') || theme.includes('monokai') ||
65
+ theme.includes('dracula') || theme.includes('nord') || theme.includes('material')) {
66
+ document.body.classList.add('dark-mode');
67
+ }
68
+ else {
69
+ document.body.classList.remove('dark-mode');
495
70
  }
496
71
  }
497
72
 
498
73
  // Initialize theme on page load
499
- document.addEventListener('DOMContentLoaded', changeTheme);`}function Ct(t){if(Object.keys(t).length===0)return"";return`
74
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function kt(t){if(Object.keys(t).length===0)return"";return`
500
75
  <div class="frontmatter">
501
76
  <h3>Frontmatter</h3>
502
77
  ${Object.entries(t).map(([s,o])=>`
@@ -504,19 +79,19 @@ else {
504
79
  <span class="frontmatter-label">${s}:</span>
505
80
  <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
506
81
  </div>`).join("")}
507
- </div>`}import cn from"net";async function jr(t){return new Promise((s)=>{let o=cn.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=cn.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 Et(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
82
+ </div>`}import Gt from"net";async function Xn(t){return new Promise((s)=>{let o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"0.0.0.0")})}async function Gn(t){return new Promise((s)=>{let o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"::")})}async function Jn(t){if(!await Xn(t))return!1;return await Gn(t)}async function Ye(t,s=20){t=Number(t);for(let o=0;o<s;o++){let p=t+o;if(await Jn(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Yn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Qn(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let o={...Yn,...s},p=await Qn();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title: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 Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
508
83
  ${l}
509
84
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
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(`
85
+ `,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 Ht(){console.log(`
86
+ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Zn(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function er(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(),Ht();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(`
87
+ `)){let l=p.trim().toLowerCase();p="",tr(l,t,s,o)}})}function tr(t,s,o,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else er(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Zn(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 Ht();break;default:break}}async function Ft(t,s={}){let o=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await 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
88
  `);return l=`
514
89
  <!DOCTYPE html>
515
90
  <html lang="en">
516
91
  <head>
517
92
  <meta charset="UTF-8">
518
93
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
519
- <title>${qr(S.title||pt.basename(c))}</title>
94
+ <title>${rr(S.title||pt.basename(c))}</title>
520
95
  <!-- Syntax highlighting styles -->
521
96
  <style id="syntax-theme">
522
97
  :root {
@@ -658,26 +233,26 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
658
233
  min-width: 100px;
659
234
  color: #555;
660
235
  }
661
- ${St()}
236
+ ${bt()}
662
237
  </style>
663
238
  </head>
664
239
  <body>
665
- ${Ct(S)}
666
- ${kt(B)}
240
+ ${kt(S)}
241
+ ${vt(B)}
667
242
 
668
243
  ${w}
669
244
 
670
245
  <script>
671
- ${Tt()}
246
+ ${St()}
672
247
  </script>
673
248
  </body>
674
249
  </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=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}
250
+ `,!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 Ye(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=nr({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
251
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
252
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
678
253
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
679
254
  ${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`),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 Ne from"fs";import Se from"path";class dn{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`
255
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(g.url.toString(),()=>{if(p)Bt.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=Bt.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 rr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zi}=globalThis.Bun;import Ne from"fs";import Se from"path";class Jt{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,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 ar(t,s={}){let{showOverlay:o=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
681
256
  <script>
682
257
  (function() {
683
258
  // stx Hot Reload Client
@@ -876,641 +451,511 @@ else {
876
451
  };
877
452
  })();
878
453
  </script>
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 Pt(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function At(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Ot(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var ut=null;function Dt(t){if(!ut)ut=new dn(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import Mt 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?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let m=await Vn(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 Yt(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 ln(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new ln(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=V.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:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let R=new K(`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 V.timeAsync("directive-processing",async()=>await r(b,S,m,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-cvzkbsds.js"),R=x(w.join(`
880
- `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+R+`
881
- `+v.slice(k);else v+=`
882
- ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),o.cache&&o.cachePath){if(await Zt(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 K(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),$t.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
- <html lang="en">
884
- <head>
885
- <meta charset="UTF-8">
886
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
887
- <title>stx Rendering Error</title>
888
- <style>
889
- body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; }
890
- .error-header { color: #dc3545; border-left: 4px solid #dc3545; padding-left: 16px; margin-bottom: 24px; }
891
- .error-details { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 16px; margin: 16px 0; }
892
- .error-code { background: #2d3748; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: 'Monaco', 'Menlo', monospace; font-size: 14px; }
893
- .help-section { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 16px; margin-top: 24px; }
894
- .file-path { font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px; }
895
- </style>
896
- </head>
897
- <body>
898
- <div class="error-header">
899
- <h1>stx Template Error</h1>
900
- <p>An error occurred while processing your stx template.</p>
901
- </div>
454
+ `}function Xe(t,s,o={}){let p=ar(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 $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var ut=null;function Pt(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import _t from"path";async function lr(t){try{let s=await Bun.file(t).text(),o=ur(s),p=mr(s,t),c=gr(s,o),l=hr(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 ur(t){let s=t.split(`
455
+ `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(o?o[1]:"").split(`
456
+ `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,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 mr(t,s){let o=[],p=Yt(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=Yt(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(`
457
+ `).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 gr(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 hr(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 Yt(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 Fs(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 lr(l);o.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=yr(o);return{results:o,summary:c}}function yr(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 br,readFile as xr,readdir as wr,stat as tn,writeFile as Sr}from"fs/promises";import Ee from"path";function cn(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 ln=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function kr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let s=[];async function o(p){let c=await wr(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 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 Rr(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 Er(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(ln.has(y))throw Error(`${s}: client ${cn(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 Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function nn(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
902
458
 
903
- <div class="error-details">
904
- <h3>Error Details</h3>
905
- <p><strong>File:</strong> <span class="file-path">${h(m)}</span></p>
906
- <p><strong>Error:</strong> ${h(y.message)}</p>
907
- ${b?`<p><strong>Line:</strong> ${h(String(b))}</p>`:""}
908
- ${w?`<p><strong>Context:</strong> ${h(String(w))}</p>`:""}
909
- </div>
459
+ `)}function Ar(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 Or(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function Dr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function Mr(t){let s=[],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(`
460
+ `)}function Ot(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 zt(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 _r(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 rn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let 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=Ot(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=Ot(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=Ot(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=Ot(t,u,"{","}");if(k===-1)return null;for(let[B,L]of Nt(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 zt(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 Nt(x)){if(m.push(k),!B.startsWith("{")){let L=rn(B);if(L)c[k]=L;continue}for(let[L,j]of Nt(B))if(L==="default")l[k]=j;else if(L==="type"){let P=rn(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=_r(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 Nt(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 Ir(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=Ee.resolve(Ee.dirname(s),x),B=Ee.relative(o,k);return`${v}${B.startsWith(".")?B:`./${B}`}${R}`})),""});let b=Lr(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 jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let 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 Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Br(t){let s=new Set;for(let o of t.matchAll(/<slot\b([^>]*)>/gi))s.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((o)=>({name:o}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function sn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,o){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await xr(p,"utf8"),l=Rr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||kr(m),y=`${Ut(o.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!Tr(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,sn(L,j)])),S=jr(Pr(c)),E=Hr(S.template),v=Ir(c,p,Ee.resolve(o.outputDir)),x=Mr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=sn(L,{type:Ar(v.declared[L])??Or(j),...j===void 0?{}:{default:Dr(j)}})}let R=l.methods||{},k=s.methods||{},B=Er(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:nn(c),shadowMode:$r(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:Br(E.template),cssProperties:Fr(nn(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
910
461
 
911
- ${y.stack?`
912
- <div class="error-details">
913
- <h3>Stack Trace</h3>
914
- <pre class="error-code">${h(y.stack)}</pre>
915
- </div>`:""}
462
+ const escapeHTML = (value) => String(value ?? '')
463
+ .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
464
+ .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
916
465
 
917
- <div class="help-section">
918
- <h3>Troubleshooting Tips</h3>
919
- <ul>
920
- <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
921
- <li>Verify that all variables used in the template are properly defined</li>
922
- <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
923
- <li>Run <code>stx debug ${h(Mt.basename(m))}</code> for detailed analysis</li>
924
- <li>Enable debug mode in your stx config for more detailed error messages</li>
925
- </ul>
926
- </div>
927
- </body>
928
- </html>`:`<!DOCTYPE html>
929
- <html lang="en">
930
- <head>
931
- <meta charset="UTF-8">
932
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
933
- <title>Error</title>
934
- <style>
935
- body { font-family: system-ui, -apple-system, sans-serif; max-width: 600px; margin: 80px auto; padding: 20px; text-align: center; color: #333; }
936
- </style>
937
- </head>
938
- <body>
939
- <h1>Something went wrong</h1>
940
- <p>An internal error occurred. Please try again later.</p>
941
- </body>
942
- </html>`,loader:"html"}}})}};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=Se.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=a(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($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.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(($e)=>$e.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 wt(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=Dt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-6r9y4p81.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-hgqcqg1h.js"),$e=F.broadcasting;await G($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Ae=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Ae))try{let le=await se(Ae);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-rj8rdd8n.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 Rt(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 U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let se=Se.join(y,F.pathname);if(Ne.existsSync(se)&&Ne.statSync(se).isFile()){let le=Bun.file(se),U=Se.extname(se).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let Ue=new Bun.Transpiler({loader:U===".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(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let $e=Se.dirname(u),he=Se.join($e,F.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let le=Bun.file(he),U=Se.extname(he).toLowerCase(),H="text/plain";if(U===".ts"||U===".tsx"){let Ue=new Bun.Transpiler({loader:U===".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(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let Ae=Se.join(process.cwd(),"public",F.pathname);if(Ne.existsSync(Ae)&&Ne.statSync(Ae).isFile()){let le=Bun.file(Ae),U=Se.extname(Ae).toLowerCase(),H="application/octet-stream";if(U===".ts"||U===".tsx"){let Ue=new Bun.Transpiler({loader:U===".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(U){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
943
- ${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
- ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
945
- ${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
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)Ne.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),F=Et(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=Ne.watch(I,{recursive:!0},async(G,se)=>{if(!se||Ot(se))return;if(At(se)){console.log(`${e.yellow}File ${e.bright}${se}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await Qt(S),c&&l)if($e)l.reload(se);else l.error("Build failed - check console for details")}else if(Pt(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 Pe from"path";var pn=`
948
- <script data-stx-helpers>
949
- (function() {
950
- 'use strict'
466
+ const valueAt = (host, path) => {
467
+ const parts = path.trim().split('.');
468
+ let value = host;
469
+ for (const part of parts) value = value?.[part];
470
+ return typeof value === 'function' ? value.call(host) : value;
471
+ };
951
472
 
952
- if (window.__stxHelpers) return
953
- window.__stxHelpers = true
473
+ const deserialize = (value, type, fallback) => {
474
+ if (value === null) return type === 'boolean' ? false : fallback;
475
+ if (type === 'boolean') return value !== 'false' && value !== '0';
476
+ if (type === 'number') return Number(value);
477
+ if (type === 'object' || type === 'array') {
478
+ try { return JSON.parse(value); }
479
+ catch { return fallback; }
480
+ }
481
+ return value;
482
+ };
954
483
 
955
- window.stx = window.stx || {}
484
+ const serialize = (value, type) => {
485
+ if (value == null || value === false) return null;
486
+ if (type === 'boolean') return '';
487
+ if (type === 'object' || type === 'array') return JSON.stringify(value);
488
+ return String(value);
489
+ };
956
490
 
957
- // ===== FORMATTERS =====
491
+ const cloneDefault = (value, type) => {
492
+ if (value == null || (type !== 'object' && type !== 'array')) return value;
493
+ if (typeof structuredClone === 'function') return structuredClone(value);
494
+ return JSON.parse(JSON.stringify(value));
495
+ };
958
496
 
959
- stx.formatCurrency = function(val, currency, locale) {
960
- return new Intl.NumberFormat(locale || 'en-US', {
961
- style: 'currency',
962
- currency: currency || 'USD',
963
- }).format(val)
964
- }
497
+ const defaultFor = property => cloneDefault(
498
+ property.default ?? ({ string: '', number: 0, boolean: false, object: {}, array: [] })[property.type],
499
+ property.type,
500
+ );
965
501
 
966
- stx.formatNumber = function(val, decimals, locale) {
967
- var opts = {}
968
- if (typeof decimals === 'number') {
969
- opts.minimumFractionDigits = decimals
970
- opts.maximumFractionDigits = decimals
502
+ export class StxElement extends HTMLElementBase {
503
+ static definition = {};
504
+ static get observedAttributes() { return this.definition.observedAttributes || []; }
505
+
506
+ constructor() {
507
+ super();
508
+ this._values = Object.create(null);
509
+ this._reflecting = false;
510
+ this._connected = false;
511
+ this._hasConnected = false;
512
+ this._initializing = false;
513
+ this._updatePending = false;
514
+ this._listeners = new Map();
515
+ const definition = this.constructor.definition;
516
+ for (const [name, property] of Object.entries(definition.properties || {})) {
517
+ this._values[name] = defaultFor(property);
518
+ }
519
+ if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
520
+ this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
971
521
  }
972
- return new Intl.NumberFormat(locale || 'en-US', opts).format(val)
973
522
  }
974
523
 
975
- stx.formatDate = function(val, format, locale) {
976
- locale = locale || 'en-US'
977
- var d = val instanceof Date ? val : new Date(val)
978
- if (isNaN(d.getTime())) return String(val)
524
+ get updateComplete() { return this._updateComplete || Promise.resolve(); }
525
+ get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
979
526
 
980
- if (format === 'long') return d.toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' })
981
- if (format === 'relative') {
982
- var diff = Date.now() - d.getTime()
983
- var mins = Math.floor(diff / 60000)
984
- if (mins < 1) return 'just now'
985
- if (mins < 60) return mins + 'm ago'
986
- var hrs = Math.floor(mins / 60)
987
- if (hrs < 24) return hrs + 'h ago'
988
- var days = Math.floor(hrs / 24)
989
- if (days < 7) return days + 'd ago'
990
- return d.toLocaleDateString(locale)
527
+ connectedCallback() {
528
+ if (this._connected) return;
529
+ this._connected = true;
530
+ this._initializing = true;
531
+ const definition = this.constructor.definition;
532
+ for (const [name, property] of Object.entries(definition.properties || {})) {
533
+ const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
534
+ if (attribute && this.hasAttribute?.(attribute)) this._values[name] = deserialize(this.getAttribute(attribute), property.type, defaultFor(property));
991
535
  }
992
- return d.toLocaleDateString(locale)
536
+ // Properties assigned before customElements.define() become own properties.
537
+ // Upgrade them after attributes so imperative state wins, matching the
538
+ // platform's property-first custom-element initialization convention.
539
+ for (const name of Object.keys(definition.properties || {})) this._upgradeProperty(name);
540
+ this._initializing = false;
541
+ const root = this.renderRoot;
542
+ const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
543
+ const firstConnection = !this._hasConnected;
544
+ if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
545
+ else this._upgradeDeclarativeEvents();
546
+ this._bindEvents();
547
+ if (firstConnection) {
548
+ this._hasConnected = true;
549
+ this.setAttribute?.('hydrated', '');
550
+ this.dispatchEvent?.(new CustomEvent('stx:hydrated', { bubbles: true, composed: true }));
551
+ }
552
+ // Called last, so a component that acquires something sees its own rendered
553
+ // markup and its events already bound. Reported rather than rethrown: a
554
+ // component that fails to set up must not take the element down with it.
555
+ try { this.onConnect?.(); }
556
+ catch (error) { console.error('[stx] onConnect failed', error); }
993
557
  }
994
558
 
995
- stx.formatPhone = function(phone) {
996
- var n = String(phone).replace(/\\D/g, '')
997
- if (n.length === 10) return \`(\${n.slice(0,3)}) \${n.slice(3,6)}-\${n.slice(6)}\`
998
- if (n.length === 11 && n[0] === '1') return \`+1 (\${n.slice(1,4)}) \${n.slice(4,7)}-\${n.slice(7)}\`
999
- return phone
559
+ disconnectedCallback() {
560
+ this._connected = false;
561
+ // Called before the framework releases anything, so the element is still
562
+ // intact for a component that needs to read it on the way out, and inside
563
+ // try/finally so a throwing hook cannot leak the framework's own listeners.
564
+ try { this.onDisconnect?.(); }
565
+ catch (error) { console.error('[stx] onDisconnect failed', error); }
566
+ finally {
567
+ for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
568
+ this._listeners.clear();
569
+ }
1000
570
  }
1001
571
 
1002
- stx.renderStars = function(rating, max) {
1003
- max = max || 5
1004
- var full = Math.floor(rating)
1005
- var half = rating - full >= 0.5
1006
- var h = ''
1007
- for (var i = 0; i < max; i++) {
1008
- if (i < full || (i === full && half))
1009
- h += '<span style="color: var(--badge-amber-text, #f59e0b)">\\u2605</span>'
1010
- else
1011
- h += '<span style="color: var(--text-muted, #6b7280)">\\u2606</span>'
572
+ attributeChangedCallback(attribute, oldValue, newValue) {
573
+ if (oldValue === newValue || this._reflecting) return;
574
+ const definition = this.constructor.definition;
575
+ const name = definition.attributeToProperty?.[attribute];
576
+ if (!name) return;
577
+ const property = definition.properties[name];
578
+ const value = deserialize(newValue, property.type, defaultFor(property));
579
+ if (!Object.is(this._values[name], value)) {
580
+ this._values[name] = value;
581
+ this.requestUpdate();
1012
582
  }
1013
- return h
1014
583
  }
1015
584
 
1016
- // ===== BADGE SYSTEM =====
585
+ /**
586
+ * The props a compiled render reads.
587
+ *
588
+ * Its own method rather than _values directly, so a component that sets a
589
+ * property before upgrade still sees it, and so the generated code has one
590
+ * name to depend on rather than a private field's shape.
591
+ */
592
+ _props() {
593
+ return this._values;
594
+ }
1017
595
 
1018
- var badgeMaps = {
1019
- status: {
1020
- 'Active Repair': 'badge-amber', 'Completed': 'badge-emerald',
1021
- 'Pending Pickup': 'badge-blue', 'Pending Estimate': 'badge-slate',
1022
- 'Approved': 'badge-emerald', 'In Review': 'badge-blue',
1023
- 'Supplement': 'badge-amber', 'Draft': 'badge-slate', 'Rejected': 'badge-red',
1024
- 'Delivered': 'badge-emerald', 'Shipped': 'badge-blue', 'Processing': 'badge-amber',
1025
- 'In Stock': 'badge-emerald', 'Backordered': 'badge-red', 'Low Stock': 'badge-amber',
1026
- },
1027
- priority: { 'Rush': 'badge-red', 'High': 'badge-amber', 'Normal': 'badge-blue', 'Low': 'badge-slate' },
1028
- severity: { 'light': 'severity-light', 'moderate': 'severity-moderate', 'heavy': 'severity-heavy' },
1029
- type: { 'OEM': 'badge-blue', 'Aftermarket': 'badge-amber', 'Recycled': 'badge-emerald', 'Reman': 'badge-slate' },
1030
- drp: { 'Active DRP': 'badge-emerald', 'Preferred': 'badge-blue', 'Standard': 'badge-slate' },
596
+ requestUpdate() {
597
+ if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
598
+ this._updatePending = true;
599
+ this._updateComplete = new Promise((resolve) => {
600
+ queueMicrotask(() => {
601
+ this._updatePending = false;
602
+ if (this._connected) this._render();
603
+ resolve();
604
+ });
605
+ });
606
+ return this._updateComplete;
1031
607
  }
1032
608
 
1033
- stx.registerBadgeMap = function(name, map) {
1034
- badgeMaps[name] = Object.assign(badgeMaps[name] || {}, map)
609
+ emit(name, detail, options = {}) {
610
+ return this.dispatchEvent(new CustomEvent(name, {
611
+ detail, bubbles: true, composed: true, ...options,
612
+ }));
1035
613
  }
1036
614
 
1037
- stx.badgeClass = function(value, mapName) {
1038
- var map = badgeMaps[mapName || 'status'] || badgeMaps.status
1039
- return map[value] || 'badge-slate'
615
+ _upgradeProperty(name) {
616
+ if (!Object.prototype.hasOwnProperty.call(this, name)) return;
617
+ const value = this[name];
618
+ delete this[name];
619
+ this[name] = value;
1040
620
  }
1041
621
 
1042
- stx.badge = function(value, mapName) {
1043
- return \`<span class="inline-flex px-2.5 py-1 rounded-full text-xs font-medium \${stx.badgeClass(value, mapName)}">\${value}</span>\`
622
+ _upgradeDeclarativeEvents() {
623
+ for (const element of this.renderRoot.querySelectorAll?.('*') || []) {
624
+ const names = element.getAttributeNames?.() || [...(element.attributes || [])].filter(Boolean).map(attribute => attribute.name);
625
+ for (const attributeName of names) {
626
+ if (!attributeName?.startsWith('@')) continue;
627
+ const [event, ...modifiers] = attributeName.slice(1).split('.');
628
+ element.setAttribute('data-stx-on-' + event, element.getAttribute(attributeName));
629
+ if (modifiers.length) element.setAttribute('data-stx-mod-' + event, modifiers.join(' '));
630
+ element.removeAttribute(attributeName);
631
+ }
632
+ }
1044
633
  }
1045
634
 
1046
- // ===== DETAIL PANEL BUILDER =====
635
+ _bindEvents() {
636
+ for (const event of this.constructor.definition.eventTypes || []) {
637
+ if (this._listeners.has(event)) continue;
638
+ const listener = ($event) => {
639
+ const selector = '[data-stx-on-' + event + ']';
640
+ const target = $event.target?.closest?.(selector);
641
+ if (!target || !this.renderRoot.contains(target)) return;
642
+ const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
643
+ if (modifiers.includes('prevent')) $event.preventDefault();
644
+ if (modifiers.includes('stop')) $event.stopPropagation();
645
+ const method = target.getAttribute('data-stx-on-' + event);
646
+ if (typeof this[method] === 'function') this[method]($event);
647
+ };
648
+ this.renderRoot.addEventListener(event, listener);
649
+ this._listeners.set(event, listener);
650
+ }
651
+ }
1047
652
 
1048
- function esc(v) { return v != null ? v : '\\u2014' }
653
+ _render() {
654
+ const definition = this.constructor.definition;
655
+ const root = this.renderRoot;
656
+ const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
657
+ const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
658
+ const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
659
+ // A compiled component renders itself: the control flow and the derived
660
+ // values were turned into JavaScript at build time, so there is nothing to
661
+ // interpret here and nothing that needs an eval the page's CSP forbids.
662
+ // The string template remains for components that carry no logic.
663
+ let html = typeof this.render === 'function'
664
+ ? this.render(RENDER_HELPERS)
665
+ : definition.template
666
+ .replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
667
+ .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
668
+ if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
669
+ root.innerHTML = html;
670
+ this._applyBindings();
671
+ this._bindEvents();
672
+ if (focusKey) {
673
+ const escaped = globalThis.CSS?.escape ? globalThis.CSS.escape(focusKey) : focusKey.replace(/["\\\\]/g, '\\$&');
674
+ const next = root.querySelector('[data-key="' + escaped + '"],#' + escaped + ',[name="' + escaped + '"]');
675
+ next?.focus?.();
676
+ if (selection && next?.setSelectionRange) next.setSelectionRange(selection[0], selection[1]);
677
+ }
678
+ this.dispatchEvent?.(new CustomEvent('stx:updated', { bubbles: false }));
679
+ }
1049
680
 
1050
- stx.detail = {
1051
- panel: function(opts) {
1052
- if (!opts || !opts.title) return ''
1053
- var badges = ''
1054
- if (opts.badges) {
1055
- opts.badges.forEach(function(b) { badges += stx.badge(b.text, b.map) })
681
+ _applyBindings() {
682
+ for (const binding of this.constructor.definition.bindings || []) {
683
+ const element = this.renderRoot.querySelector('[data-stx-bind-' + binding.id + ']');
684
+ if (!element) continue;
685
+ const value = valueAt(this, binding.expression);
686
+ if (binding.name === 'class') element.className = value || '';
687
+ else if (binding.name === 'style' && typeof value === 'object') {
688
+ Object.assign(element.style, value);
1056
689
  }
1057
- return \`
1058
- <div style="display:flex;align-items:center;justify-content:space-between;padding:1.25rem 1.5rem;border-bottom:1px solid var(--border-main)">
1059
- <div>
1060
- <h2 style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${opts.title}</h2>
1061
- \${opts.subtitle ? \`<p style="font-size:0.75rem;color:var(--text-muted);margin-top:0.25rem">\${opts.subtitle}</p>\` : ''}
1062
- </div>
1063
- <div style="display:flex;align-items:center;gap:0.75rem">
1064
- \${badges}
1065
- <button onclick="closeSlideOver()" style="padding:0.5rem;border-radius:0.5rem;color:var(--text-muted);background:none;border:none;cursor:pointer;font-size:1.5rem;line-height:1" aria-label="Close">&times;</button>
1066
- </div>
1067
- </div>\`
1068
- },
1069
-
1070
- section: function(label, rows) {
1071
- var inner = ''
1072
- if (rows) {
1073
- if (!Array.isArray(rows) && typeof rows === 'object') {
1074
- Object.keys(rows).forEach(function(k) { inner += stx.detail.row(k, rows[k]) })
1075
- }
1076
- else {
1077
- rows.forEach(function(r) {
1078
- if (Array.isArray(r)) inner += stx.detail.row(r[0], r[1])
1079
- else inner += stx.detail.row(r.label, r.value)
1080
- })
1081
- }
690
+ else if (typeof value === 'boolean') {
691
+ element.toggleAttribute(binding.name, value);
692
+ if (binding.name in element) element[binding.name] = value;
1082
693
  }
1083
- return \`
1084
- <div class="detail-section">
1085
- <div class="detail-label">\${label}</div>
1086
- \${inner}
1087
- </div>\`
1088
- },
694
+ else if (value == null || value === false) element.removeAttribute(binding.name);
695
+ else element.setAttribute(binding.name, String(value));
696
+ }
697
+ }
698
+ }
1089
699
 
1090
- row: function(label, value) {
1091
- return \`
1092
- <div class="detail-row">
1093
- <span class="detail-row-label">\${label}</span>
1094
- <span class="detail-row-value">\${esc(value)}</span>
1095
- </div>\`
1096
- },
700
+ /**
701
+ * What a compiled render is handed.
702
+ *
703
+ * Passed in rather than closed over so the generated code names no globals, and
704
+ * a component module stays readable on its own: __escape is visibly a
705
+ * parameter, not something the bundler happened to leave in scope.
706
+ */
707
+ const RENDER_HELPERS = {
708
+ escape: escapeHTML,
709
+ // The raw form is the author declaring the value is markup. Null becomes an
710
+ // empty string rather than the word "null", which is the only sensible
711
+ // reading of a missing fragment.
712
+ raw: (value) => String(value ?? ''),
713
+ // A loop over something absent runs zero times. Throwing here would fail a
714
+ // whole page over one empty list, which is never what the author meant.
715
+ values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
716
+ entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
717
+ };
1097
718
 
1098
- stats: function(items) {
1099
- var list = Array.isArray(items)
1100
- ? items
1101
- : Object.keys(items).map(function(k) { return { label: k, value: items[k] } })
719
+ export function defineComponent(Component, definition) {
720
+ const properties = definition.properties || {};
721
+ const attributeToProperty = {};
722
+ const observedAttributes = [];
723
+ for (const [name, property] of Object.entries(properties)) {
724
+ const attribute = property.attribute === false ? null : (property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase()));
725
+ if (attribute) {
726
+ attributeToProperty[attribute] = name;
727
+ observedAttributes.push(attribute);
728
+ }
729
+ Object.defineProperty(Component.prototype, name, {
730
+ configurable: true,
731
+ enumerable: true,
732
+ get() { return this._values[name]; },
733
+ set(value) {
734
+ const oldValue = this._values[name];
735
+ if (Object.is(oldValue, value)) return;
736
+ this._values[name] = value;
737
+ if (property.reflect && attribute && !this._reflecting) {
738
+ const serialized = serialize(value, property.type);
739
+ this._reflecting = true;
740
+ if (serialized === null) this.removeAttribute(attribute);
741
+ else this.setAttribute(attribute, serialized);
742
+ this._reflecting = false;
743
+ }
744
+ this.requestUpdate();
745
+ this.dispatchEvent?.(new CustomEvent(name + '-changed', {
746
+ detail: { value, oldValue }, bubbles: true, composed: true,
747
+ }));
748
+ },
749
+ });
750
+ }
751
+ Component.definition = { ...definition, attributeToProperty, observedAttributes };
752
+ const registry = globalThis.customElements || globalThis.window?.customElements;
753
+ if (registry && !registry.get(definition.tag)) {
754
+ registry.define(definition.tag, Component);
755
+ }
756
+ return Component;
757
+ }
758
+ `}function Ur(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),o=Object.entries(t.methods).map(([u,y])=>{if(ln.has(u))throw Error(`${t.sourcePath}: ${cn(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
759
+ ${y}
760
+ }`}).join(`
1102
761
 
1103
- var cards = list.map(function(item) {
1104
- return \`
1105
- <div style="padding:0.75rem;border-radius:0.5rem;background:var(--bg-subtle);text-align:center">
1106
- <div style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${item.value}</div>
1107
- <div style="font-size:0.6875rem;color:var(--text-muted);margin-top:0.25rem">\${item.label}</div>
1108
- </div>\`
1109
- }).join('')
762
+ `),p=t.scope,c=[...new Set([...Object.keys(t.properties),...p.propNames])].map((u)=>p.defaults[u]===void 0?u:`${u} = ${p.defaults[u]}`).join(", "),l=(u)=>u.split(`
763
+ `).map((y)=>y.trim()===""?y:` ${y}`).join(`
764
+ `),m="";if(t.render.trim()!==""||p.body!==""||c!==""){let u=[c?`const { ${c} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
765
+ `),y;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
766
+ ${u}
767
+ }`),b=g.indexOf("{"),w=g.lastIndexOf("}");y=g.slice(b+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
768
+ render(__helpers) {
769
+ const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
770
+ ${l(y.trim())}
771
+ }
772
+ `}return`import { StxElement, defineComponent } from './runtime.js';
773
+ ${p.imports.length?`${p.imports.join(`
774
+ `)}
775
+ `:""}
776
+ /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
777
+ export class ${t.name} extends StxElement {
778
+ ${o}${m}
779
+ }
1110
780
 
1111
- return \`<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:0.75rem;padding:0 1.5rem 1rem">\${cards}</div>\`
1112
- },
781
+ defineComponent(${t.name}, ${s});
782
+ export default ${t.name};
783
+ `}function Dt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Wr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${Dt(m)}`).join(`
784
+ `),o=Object.entries(t.properties).map(([l,m])=>` ${l}: ${Dt(m)}`).join(`
785
+ `),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
786
+ `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
787
+ `);return`export interface ${t.name}Props {
788
+ ${s}
789
+ }
1113
790
 
1114
- timeline: function(items) {
1115
- var entries = items.map(function(item, i) {
1116
- var color = item.color || 'var(--text-accent)'
1117
- var isLast = i === items.length - 1
791
+ export interface ${t.name}EventMap {
792
+ ${p}
793
+ }
1118
794
 
1119
- return \`
1120
- <div style="display:flex;gap:0.75rem">
1121
- <div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0">
1122
- <div style="width:10px;height:10px;border-radius:50%;background:\${color};flex-shrink:0"></div>
1123
- \${!isLast ? '<div style="width:2px;flex:1;background:var(--bar-track);min-height:24px"></div>' : ''}
1124
- </div>
1125
- <div style="padding-bottom:\${isLast ? '0' : '1rem'};flex:1">
1126
- <div style="font-size:0.8125rem;font-weight:500;color:var(--text-primary)">\${item.title}</div>
1127
- \${item.description ? \`<div style="font-size:0.75rem;color:var(--text-muted);margin-top:0.125rem">\${item.description}</div>\` : ''}
1128
- \${item.meta ? \`<div style="font-size:0.6875rem;color:var(--text-tertiary);margin-top:0.25rem">\${item.meta}</div>\` : ''}
1129
- </div>
1130
- </div>\`
1131
- }).join('')
795
+ export declare class ${t.name} extends HTMLElement {
796
+ ${o}
797
+ ${c}
798
+ readonly updateComplete: Promise<void>
799
+ requestUpdate(): Promise<void>
800
+ emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
801
+ }
1132
802
 
1133
- return \`<div style="padding:0 1.5rem 1rem">\${entries}</div>\`
1134
- },
803
+ declare global {
804
+ interface HTMLElementTagNameMap {
805
+ ${JSON.stringify(t.tag)}: ${t.name}
806
+ }
807
+ }
1135
808
 
1136
- open: function(html) {
1137
- if (typeof openSlideOver === 'function') openSlideOver(html)
1138
- },
809
+ export default ${t.name}
810
+ `}function Vr(t){return`declare global {
811
+ namespace JSX {
812
+ interface IntrinsicElements {
813
+ ${t.map((o)=>{let p=Object.entries(o.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${Dt(m)}`).join(`
814
+ `),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(`
815
+ `);return` ${JSON.stringify(o.tag)}: {
816
+ ${p}
817
+ ${c}
818
+ children?: unknown
819
+ slot?: string
820
+ class?: string
821
+ className?: string
822
+ }`}).join(`
823
+ `)}
824
+ }
1139
825
  }
826
+ }
1140
827
 
1141
- // ===== DATA TABLE HELPERS =====
828
+ export {}
829
+ `}function qr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([o,p])=>({kind:"field",name:o,description:p.description,type:{text:Dt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ut(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 on(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
830
+ ${s}
831
+ }`}function an(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),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(`
832
+ `);return`const definitions = ${JSON.stringify(c,null,2)};
833
+ const escapeHTML = (value) => String(value ?? '')
834
+ .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
835
+ .replaceAll('"', '&quot;').replaceAll("'", '&#039;');
836
+ const valueAt = (values, path) => path.trim().split('.').reduce((value, part) => value?.[part], values);
1142
837
 
1143
- stx.table = {
1144
- filter: function(opts) {
1145
- var searchEl = document.getElementById(opts.searchId)
1146
- var search = searchEl ? searchEl.value.toLowerCase() : ''
1147
- var rows = document.querySelectorAll(opts.rowSelector || 'tbody tr')
1148
- var filters = opts.filters || []
1149
- var matched = []
838
+ export function renderComponent(tag, props = {}, slots = {}) {
839
+ const definition = definitions[tag];
840
+ if (!definition) throw new Error('Unknown STX component: ' + tag);
841
+ const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
842
+ Object.assign(values, props);
843
+ let template = definition.template
844
+ .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
845
+ .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
846
+ .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
847
+ const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
848
+ if (property.attribute === false || !(name in props)) return [];
849
+ const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
850
+ const value = props[name];
851
+ if (value == null || value === false) return [];
852
+ if (value === true) return [attribute];
853
+ const serialized = typeof value === 'object' ? JSON.stringify(value) : value;
854
+ return [attribute + '=\\"' + escapeHTML(serialized) + '\\"'];
855
+ }).join(' ');
856
+ if (definition.shadowMode) {
857
+ template = '<template shadowrootmode="' + definition.shadowMode + '">' +
858
+ (definition.styles ? '<style>' + definition.styles + '</style>' : '') + template + '</template>' +
859
+ String(slots.default ?? '');
860
+ }
861
+ return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
862
+ }
1150
863
 
1151
- rows.forEach(function(row) {
1152
- var text = row.textContent.toLowerCase()
1153
- var matchSearch = !search || text.indexOf(search) !== -1
1154
- var matchFilters = filters.every(function(f) {
1155
- var el = document.getElementById(f.id)
1156
- if (!el) return true
1157
- var val = el.value
1158
- if (!val || val === f.allValue) return true
1159
- return row.getAttribute(\`data-\${f.attr}\`) === val
1160
- })
864
+ ${l}
865
+ `}async function zs(t){let s=Ee.resolve(t.inputDir),o=Ee.resolve(t.outputDir);if(!(await tn(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await Cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>zr(s,x,t)));l.sort((x,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 br(o,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(o,x);return await Sr(k,R.endsWith(`
866
+ `)?R:`${R}
867
+ `,"utf8"),y.push(k),k};await g("runtime.js",Nr());for(let x of l){if(await g(`${x.tag}.js`,Ur(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Wr(x));if(t.css!==!1&&x.styles){let R=x.shadowMode?x.styles:on(x);await g(`${x.tag}.css`,t.minify?an(R):R)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
868
+ `);if(await g("index.js",b),await g("ssr.js",Kr(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
869
+ `)),await g("custom-elements.d.ts",Vr(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
870
+ `)}
871
+ export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
872
+ ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
873
+ `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(qr(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(on).join(`
1161
874
 
1162
- if (matchSearch && matchFilters) matched.push(row)
1163
- else row.style.display = 'none'
1164
- })
875
+ `);if(x)S=await g("bundle.css",t.minify?an(x):x)}let E;if(t.bundle!==!1){E=Ee.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.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(`
876
+ `);throw AggregateError(k,`Failed to bundle component library${B?`
877
+ ${B}`:""}`)}if(!x.success){let R=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
878
+ `);throw AggregateError(x.logs,`Failed to bundle component library${R?`
879
+ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await tn(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(o,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}import Wt from"fs";import yt from"path";async function Xr(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(`
880
+ `).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 Gr(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(`
881
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,s=!1,o){let p=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(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(`
882
+ `);m=`<${p}
883
+ ${u}
884
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:o}}async function dn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await dn(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 Yr(t,s){try{if(!await r(t))return[];let o=await dn(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 Jr(l,u,y);p.push(g)}return p}catch(o){return console.error("Error generating component docs:",o),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.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(`
885
+ `).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 Zr(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
886
+ <p>Welcome, {{ user.name }}!</p>
887
+ @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
888
+ <p>Welcome back!</p>
889
+ @else
890
+ <p>Please log in</p>
891
+ @endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
892
+ <p>A</p>
893
+ @elseif(score > 80)
894
+ <p>B</p>
895
+ @elseif(score > 70)
896
+ <p>C</p>
897
+ @endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
898
+ <p>Please log in</p>
899
+ @endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
900
+ <li>{{ item.name }}</li>
901
+ @endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
902
+ <p>Page {{ page }}</p>
903
+ @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
904
+ {{ This will be displayed as-is }}
905
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let 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 es(t=[],s=[],o=[],p){let c=`# stx Documentation
1165
906
 
1166
- return matched
1167
- },
907
+ `;if(p)c+=`${p}
1168
908
 
1169
- sort: function(rows, sortBy, direction) {
1170
- direction = direction || 'asc'
1171
- return rows.slice().sort(function(a, b) {
1172
- var aVal = a.getAttribute(\`data-\${sortBy}\`) || a.textContent
1173
- var bVal = b.getAttribute(\`data-\${sortBy}\`) || b.textContent
1174
- var aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''))
1175
- var bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''))
1176
- if (!isNaN(aNum) && !isNaN(bNum)) return direction === 'asc' ? aNum - bNum : bNum - aNum
1177
- return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
1178
- })
1179
- },
1180
- }
909
+ `;if(t.length>0){c+=`## Components
1181
910
 
1182
- // ===== PAGINATION =====
911
+ `;for(let l of t){if(c+=`### ${l.name}
1183
912
 
1184
- stx.pagination = function(opts) {
1185
- var page = opts.page || 1
1186
- var perPage = opts.perPage || 10
1187
- var items = opts.items || []
1188
- var total = items.length
1189
- var totalPages = Math.max(1, Math.ceil(total / perPage))
1190
- if (page > totalPages) page = totalPages
913
+ `,l.description)c+=`${l.description}
1191
914
 
1192
- var start = (page - 1) * perPage
1193
- var end = Math.min(start + perPage, total)
915
+ `;if(l.isWebComponent)c+=`**Web Component Tag:** \`${l.tag}\`
1194
916
 
1195
- items.forEach(function(el, i) { el.style.display = (i >= start && i < end) ? '' : 'none' })
917
+ `;if(l.props.length>0){c+=`#### Properties
1196
918
 
1197
- var ids = { count: opts.countId, total: opts.totalId, empty: opts.emptyId, bar: opts.barId }
1198
- if (ids.count) { var el = document.getElementById(ids.count); if (el) el.textContent = total === 0 ? '0' : \`\${start + 1}\\u2013\${end}\` }
1199
- if (ids.total) { var el = document.getElementById(ids.total); if (el) el.textContent = total }
1200
- if (ids.empty) { var el = document.getElementById(ids.empty); if (el) el.style.display = total === 0 ? 'block' : 'none' }
1201
- if (ids.bar) { var el = document.getElementById(ids.bar); if (el) el.style.display = total === 0 ? 'none' : '' }
919
+ `,c+=`| Name | Type | Required | Default | Description |
920
+ `,c+=`| ---- | ---- | -------- | ------- | ----------- |
921
+ `;for(let m of l.props)c+=`| ${m.name} | ${m.type||"any"} | ${m.required?"Yes":"No"} | ${m.default||"-"} | ${m.description||"-"} |
922
+ `;c+=`
923
+ `}if(l.example)c+=`#### Example
1202
924
 
1203
- if (opts.buttonsId) {
1204
- var wrap = document.getElementById(opts.buttonsId)
1205
- if (wrap) {
1206
- var go = opts.goToPage
1207
- var pages = stx.pagination.getPages(page, totalPages)
925
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
1208
926
 
1209
- var btn = function(label, target, disabled) {
1210
- return \`<button onclick="\${go}(\${target})" \${disabled ? 'disabled' : ''}
1211
- class="px-3 py-1.5 rounded-lg text-sm cursor-pointer"
1212
- style="background:var(--bg-subtle);border:1px solid var(--border-input);color:\${disabled ? 'var(--text-muted)' : 'var(--text-primary)'};opacity:\${disabled ? '0.5' : '1'}">\${label}</button>\`
1213
- }
927
+ `;for(let l of s){if(c+=`### ${l.name}
1214
928
 
1215
- var h = btn('Previous', page - 1, page === 1)
1216
- pages.forEach(function(p) {
1217
- if (p === '...') {
1218
- h += '<span class="px-2 text-sm" style="color:var(--text-muted)">\\u2026</span>'
1219
- }
1220
- else if (p === page) {
1221
- h += \`<button class="w-9 h-9 rounded-lg text-sm font-medium" style="background:var(--btn-primary-bg, var(--text-accent));color:#fff">\${p}</button>\`
1222
- }
1223
- else {
1224
- h += btn(p, p, false)
1225
- }
1226
- })
1227
- h += btn('Next', page + 1, page === totalPages)
1228
- wrap.innerHTML = h
1229
- }
1230
- }
929
+ `,l.description)c+=`${l.description}
1231
930
 
1232
- return { page: page, totalPages: totalPages, total: total, start: start, end: end }
1233
- }
931
+ `;if(l.components&&l.components.length>0)c+=`**Components Used:** ${l.components.join(", ")}
1234
932
 
1235
- stx.pagination.getPages = function(current, total) {
1236
- if (total <= 7) return Array.from({ length: total }, function(_, i) { return i + 1 })
1237
- var pages = [1]
1238
- if (current > 3) pages.push('...')
1239
- for (var i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) pages.push(i)
1240
- if (current < total - 2) pages.push('...')
1241
- pages.push(total)
1242
- return pages
1243
- }
933
+ `;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
1244
934
 
1245
- // ===== UTILITIES =====
935
+ `}}if(o.length>0){c+=`## Directives
1246
936
 
1247
- stx.debounce = function(fn, delay) {
1248
- var timer
1249
- return function() {
1250
- var args = arguments, ctx = this
1251
- clearTimeout(timer)
1252
- timer = setTimeout(function() { fn.apply(ctx, args) }, delay || 250)
1253
- }
1254
- }
937
+ `,c+=`| Directive | Description | Has End Tag |
938
+ `,c+=`| --------- | ----------- | ----------- |
939
+ `;for(let l of o)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
940
+ `;c+=`
941
+ `;for(let l of o)if(l.example)c+=`### @${l.name}
1255
942
 
1256
- })()
1257
- </script>
1258
- `;function mn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.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(Pe.sep)}async function yn(t,s={}){let o=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Pe.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=mn(t.map((v)=>Pe.dirname(Pe.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=Pe.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((Ae)=>`<option value="${Ae}"${Ae===j?" selected":""}>${Ae}</option>`).join(`
1259
- `),se=`
1260
- <!DOCTYPE html>
943
+ `,c+=`${l.description||""}
944
+
945
+ `,c+=`#### Example
946
+
947
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ts(t=[],s=[],o=[],p){let c=`<!DOCTYPE html>
1261
948
  <html lang="en">
1262
949
  <head>
1263
950
  <meta charset="UTF-8">
1264
951
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
- <title>${un(B.title||Pe.basename(x))}</title>
1266
- <!-- Syntax highlighting styles -->
1267
- <style id="syntax-theme">
1268
- :root {
1269
- --shiki-color-text: #24292e;
1270
- --shiki-color-background: #ffffff;
1271
- --shiki-token-constant: #005cc5;
1272
- --shiki-token-string: #032f62;
1273
- --shiki-token-comment: #6a737d;
1274
- --shiki-token-keyword: #d73a49;
1275
- --shiki-token-parameter: #24292e;
1276
- --shiki-token-function: #6f42c1;
1277
- --shiki-token-string-expression: #032f62;
1278
- --shiki-token-punctuation: #24292e;
1279
- --shiki-token-link: #032f62;
1280
- }
1281
- pre {
1282
- background-color: var(--shiki-color-background);
1283
- padding: 1rem;
1284
- border-radius: 4px;
1285
- }
1286
- code {
1287
- color: var(--shiki-color-text);
1288
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1289
- }
1290
- .dark-mode {
1291
- --shiki-color-text: #e1e4e8;
1292
- --shiki-color-background: #24292e;
1293
- --shiki-token-constant: #79b8ff;
1294
- --shiki-token-string: #9ecbff;
1295
- --shiki-token-comment: #6a737d;
1296
- --shiki-token-keyword: #f97583;
1297
- --shiki-token-parameter: #e1e4e8;
1298
- --shiki-token-function: #b392f0;
1299
- --shiki-token-string-expression: #9ecbff;
1300
- --shiki-token-punctuation: #e1e4e8;
1301
- --shiki-token-link: #9ecbff;
1302
- }
1303
- </style>
952
+ <title>stx Documentation</title>
1304
953
  <style>
1305
954
  body {
1306
- font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
955
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
1307
956
  line-height: 1.6;
1308
957
  color: #333;
1309
- max-width: 800px;
1310
- margin: 0 auto;
1311
- padding: 2rem;
1312
- }
1313
- pre, code {
1314
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1315
- }
1316
- pre {
1317
- border-radius: 4px;
1318
- padding: 0;
1319
- margin: 1.5rem 0;
1320
- overflow-x: auto;
1321
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
1322
- }
1323
- pre code {
1324
- display: block;
1325
- padding: 1rem;
1326
- overflow-x: auto;
1327
- }
1328
- /* Apply background color to code blocks based on theme */
1329
- pre.syntax-highlighter {
1330
- background-color: var(--shiki-color-background) !important;
1331
- }
1332
- .dark-mode pre.syntax-highlighter {
1333
- background-color: var(--shiki-color-background) !important;
1334
- }
1335
- code {
1336
- padding: 0.2rem 0.4rem;
1337
- border-radius: 3px;
1338
- }
1339
- h1, h2, h3, h4 {
1340
- margin-top: 2rem;
1341
- margin-bottom: 1rem;
1342
- }
1343
- h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
1344
- h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
1345
- h3 { color: #444; }
1346
- img {
1347
- max-width: 100%;
1348
- border-radius: 4px;
1349
- margin: 1rem 0;
1350
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1351
- }
1352
- blockquote {
1353
- border-left: 4px solid #ddd;
1354
- padding-left: 1rem;
1355
- margin-left: 0;
1356
- color: #555;
1357
- background: #f9f9f9;
1358
- padding: 0.5rem 1rem;
1359
- margin: 1.5rem 0;
1360
- }
1361
- table {
1362
- border-collapse: collapse;
1363
- width: 100%;
1364
- margin: 1.5rem 0;
1365
- }
1366
- th, td {
1367
- border: 1px solid #ddd;
1368
- padding: 0.5rem;
1369
- }
1370
- th {
1371
- background: #f0f0f0;
1372
- text-align: left;
1373
- }
1374
- tr:nth-child(even) {
1375
- background-color: #f8f8f8;
1376
- }
1377
- a {
1378
- color: #0066cc;
1379
- text-decoration: none;
1380
- }
1381
- a:hover {
1382
- text-decoration: underline;
1383
- }
1384
- hr {
1385
- border: 0;
1386
- border-top: 1px solid #eee;
1387
- margin: 2rem 0;
1388
- }
1389
- .frontmatter {
1390
- background: #f8f8f8;
1391
- border-radius: 4px;
1392
- padding: 1.5rem;
1393
- margin-bottom: 2rem;
1394
- font-size: 0.9rem;
1395
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1396
- border-left: 4px solid #ddd;
1397
- }
1398
- .frontmatter-item {
1399
- margin-bottom: 0.5rem;
1400
- display: flex;
1401
- }
1402
- .frontmatter-label {
1403
- font-weight: bold;
1404
- min-width: 100px;
1405
- color: #555;
1406
- }
1407
- ${St()}
1408
- </style>
1409
- </head>
1410
- <body>
1411
- ${Ct(B)}
1412
- ${kt(G)}
1413
-
1414
- ${k}
1415
-
1416
- <script>
1417
- ${Tt()}
1418
- </script>
1419
- </body>
1420
- </html>
1421
- `,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={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}:`,Ie(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
- ${Ie(P,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=nr(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}`,Ie(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=Pe.join(process.cwd(),"public",x.pathname);if(it.existsSync(R)&&it.statSync(R).isFile()){let L=Bun.file(R),j=Pe.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>",`${pn}
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=Pe.join(c,x.pathname);if(it.existsSync(B)&&it.statSync(B).isFile()){let L=Bun.file(B),j=Pe.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>${un(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":_e,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
- ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1426
- ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1427
- ${e.bright}\u2192 ${e.cyan}http://localhost:${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:Pe.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:Pe.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}`),ye.clear(),ee(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function un(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Jr}=globalThis.Bun;import ve from"fs";import ie from"path";async function gn(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 bn(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-6r9y4p81.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-rj8rdd8n.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(!ve.existsSync(R)&&!g._layerPageDirs?.some((A)=>ve.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(ve.existsSync(A)){let N=M(ie.dirname(A),{pagesDir:ie.basename(A)});for(let W of N){let we=z==="/"?W.pattern:`${z}${W.pattern==="/"?"":W.pattern}`;L.push({route:{...W,pattern:we},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 Zs(u,s.stxOptions?.shell),I){if(P=await yr(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}`)}}Ze(),await et(u);let F=Qe();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-6r9y4p81.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:W}=await import("./chunk-hgqcqg1h.js"),we=z.broadcasting;await N(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let oe=await W(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 $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Ae=new Set,le=async(A)=>{let z=rr(R,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let W=N.outputs.find((we)=>we.path.endsWith(".html"));if(!W)return null;return await Bun.file(W.path).text()}catch{return null}},U=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:W,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-6r9y4p81.js"),{checkCache:oe,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-75zcwcrt.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},O={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(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 ve.promises.stat(A.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=U.get(A.filePath);return{route:A,content:Re,status:gt?.status??await gn(A.filePath),headers:gt?.headers}}}}catch{}let He=await oe(A.filePath,O);if(He){let Fe=He;if(P)Fe=ge(Fe,{preserveHead:!0});let ze=U.get(A.filePath);return{route:A,content:Fe,status:ze?.status??await gn(A.filePath),headers:ze?.headers}}}let me=pe?await X(A.filePath):await Bun.file(A.filePath).text(),Ce=vt(me),{classifyAllScripts:Y}=await import("./chunk-6r9y4p81.js"),Me=Y(me),Ve=Me.server.map((de)=>de.content),ue=me;for(let de of Me.server)ue=ue.replace(de.fullTag,"");let fe={__filename:A.filePath,__dirname:ie.dirname(A.filePath),__stx_options:O,params:z??{},__stx_runtime_head:{}};for(let de of Ve)try{await W(de,fe,A.filePath)}catch(He){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,He?.message||He)}let Ke=new Set,Oe;if(s.profile){let de=performance.now();Oe=await N(ue,fe,A.filePath,O,Ke);let He=performance.now()-de,Fe=ie.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${Fe} \u2192 ${He.toFixed(2)}ms`)}else Oe=await N(ue,fe,A.filePath,O,Ke);if(!P)Oe=await Ge(Oe,{router:O.router});{let{interpolateScriptExpressions:de}=await import("./chunk-cvzkbsds.js");Oe=Oe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(He,Fe,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return He;return`<script${Fe}>${de(ze,fe)}</script>`})}if(P)Oe=ge(Oe,{preserveHead:!0});if(pe&&be)await Q(A.filePath,Oe,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-bmk0s261.js"),lt=Kn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},He={...O,autoShell:!1},Fe=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return N(mt[Re],{...fe,$boundary:gt},A.filePath,He,new Set)}})),ze=new Set(Fe.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...Fe]}if(lt&&lt.length>0)Ae.add(A.pattern);else lt=void 0;let Kt=je(fe),Xt=Be(fe);if(be)U.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Oe,status:Kt??Ce,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()=>{he.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((W)=>H(W)));for(let W of N)if(W)he.set(W.route.pattern,W)}for(let A=0;A<L.length;A+=Ue){let z=L.slice(A,A+Ue),N=await Promise.all(z.map(({route:W})=>H(W)));for(let W of N)if(W)j.set(W.route.pattern,W)}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 wt(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=Dt({wsPort:A,verbose:!1}),m=l.start(A)}let Lt=(A,z)=>{let W=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${W}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${W}`);return W+A};console.log(`${e.blue}Starting server...${e.reset}`);let It=Jr({port:at,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",W=ie.join(u,N,z.pathname),we=ie.join(u,z.pathname),We=ie.join($e,z.pathname);if([W,we,We].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Q]=await Promise.all([ve.promises.stat(W).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(W,u,S))return Wt(W);if(oe?.isFile()&&!w(we,u,S))return Wt(we);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},me=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),pe,new Set);return new Response(me,{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-0n76c3g8.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 X=await E(A);if(X)return X;let J=fn(z.pathname,k);if(J){let O=he.get(J.route.pattern),be=Ae.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,me=O.headers??{},Ce=(J.route.filePath?Le(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.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(Ce.middleware){let Me=tt(z.pathname,J.params,Ce,z.search),Ve=nt(Me,null,A,{isServer:!0}),ue=await rt(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Oe=new Headers(ue.responseHeaders);return Oe.set("Location",fe),new Response(null,{status:Ke,headers:Oe})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.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(ue.state).length>0){let fe=`<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>",`${fe}</head>`)}}let Y=O.content;if(P&&Qs(A)){let Me=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?Ys(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":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Xi]:os(),...C(),"Cache-Control":_e}})}if(P)Y=Sn(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:Me,streamToResponse:Ve}=await import("./chunk-bmk0s261.js");return Ve(Me(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",...me}})}}if(L.length>0){let O=L.map((pe)=>pe.route),be=fn(z.pathname,O);if(be){let pe=j.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=Sn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{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 me=j.get(pe)||j.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=Sn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ye(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.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 Je=await le(404);if(Je){let O=Je;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
- ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1431
- ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1432
- ${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
- ${e.yellow}Routes:${e.reset}`);let jt=[...sr(k,u)];for(let{route:A}of L)jt.push(`${A.pattern}`);if(jt.forEach((A,z)=>{let W=z===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${W}${e.reset}${A}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let A,z=ie.join(R,"index.stx");if(ve.existsSync(z)){let W=await Bun.file(z).text();A=Et(W)}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,W=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let X of Object.values(Q.resources)){if(!ve.existsSync(X))continue;let J=ve.realpathSync(X);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Q,X]of N)if(!oe.has(Q))X.close(),N.delete(Q);for(let Q of oe)if(!N.has(Q)&&ve.existsSync(Q))N.set(Q,ve.watch(Q,{recursive:!0},(X,J)=>{We(Q,X,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(oe,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(oe,Q,X)),we),Ge=async(oe,Q,X)=>{if(!X||Ot(X))return;if(At(X)){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})),W()}if(A(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),c&&l)l.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-75zcwcrt.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(I&&X){if(ie.resolve(oe,X)===I||ie.basename(I)===X){let ke=await yr(I,s.stxOptions||{});if(ke)P=ke}}if(await qe(),await Qt(u),c&&l)l.reload(X)}else{console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-75zcwcrt.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(await qe(),c&&l)l.reload(X)}}else if(Pt(X)){if(console.log(`${e.cyan}CSS ${X} changed${e.reset}`),c&&l)l.updateCss(X)}};W(),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
- `);m=`<${p}
1438
- ${u}
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
- <p>Welcome, {{ user.name }}!</p>
1442
- @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
1443
- <p>Welcome back!</p>
1444
- @else
1445
- <p>Please log in</p>
1446
- @endif`},{name:"elseif",description:"Provides an alternative condition",hasEndTag:!1,example:`@if(score > 90)
1447
- <p>A</p>
1448
- @elseif(score > 80)
1449
- <p>B</p>
1450
- @elseif(score > 70)
1451
- <p>C</p>
1452
- @endif`},{name:"unless",description:"Conditionally render content if a condition is false",hasEndTag:!0,example:`@unless(user.isLoggedIn)
1453
- <p>Please log in</p>
1454
- @endunless`},{name:"for",description:"Loop through an array or object",hasEndTag:!0,example:`@for(item of items)
1455
- <li>{{ item.name }}</li>
1456
- @endfor`},{name:"while",description:"Loop while a condition is true",hasEndTag:!0,example:`@while(page < totalPages)
1457
- <p>Page {{ page }}</p>
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
- {{ 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 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 rs(t=[],s=[],o=[],p){let c=`# stx Documentation
1461
-
1462
- `;if(p)c+=`${p}
1463
-
1464
- `;if(t.length>0){c+=`## Components
1465
-
1466
- `;for(let l of t){if(c+=`### ${l.name}
1467
-
1468
- `,l.description)c+=`${l.description}
1469
-
1470
- `;if(l.isWebComponent)c+=`**Web Component Tag:** \`${l.tag}\`
1471
-
1472
- `;if(l.props.length>0){c+=`#### Properties
1473
-
1474
- `,c+=`| Name | Type | Required | Default | Description |
1475
- `,c+=`| ---- | ---- | -------- | ------- | ----------- |
1476
- `;for(let m of l.props)c+=`| ${m.name} | ${m.type||"any"} | ${m.required?"Yes":"No"} | ${m.default||"-"} | ${m.description||"-"} |
1477
- `;c+=`
1478
- `}if(l.example)c+=`#### Example
1479
-
1480
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
1481
-
1482
- `;for(let l of s){if(c+=`### ${l.name}
1483
-
1484
- `,l.description)c+=`${l.description}
1485
-
1486
- `;if(l.components&&l.components.length>0)c+=`**Components Used:** ${l.components.join(", ")}
1487
-
1488
- `;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
1489
-
1490
- `}}if(o.length>0){c+=`## Directives
1491
-
1492
- `,c+=`| Directive | Description | Has End Tag |
1493
- `,c+=`| --------- | ----------- | ----------- |
1494
- `;for(let l of o)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
- `;c+=`
1496
- `;for(let l of o)if(l.example)c+=`### @${l.name}
1497
-
1498
- `,c+=`${l.description||""}
1499
-
1500
- `,c+=`#### Example
1501
-
1502
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function ss(t=[],s=[],o=[],p){let c=`<!DOCTYPE html>
1503
- <html lang="en">
1504
- <head>
1505
- <meta charset="UTF-8">
1506
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1507
- <title>stx Documentation</title>
1508
- <style>
1509
- body {
1510
- font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
1511
- line-height: 1.6;
1512
- color: #333;
1513
- max-width: 1200px;
958
+ max-width: 1200px;
1514
959
  margin: 0 auto;
1515
960
  padding: 2rem;
1516
961
  }
@@ -1570,15 +1015,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.
1570
1015
  <td>@${l.name}</td>
1571
1016
  <td>${l.description||"-"}</td>
1572
1017
  <td>${l.hasEndTag?"Yes":"No"}</td>
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=rs(u,y,g,w),E="md";break;case"html":S=ss(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 Bs(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 wn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function lr(t,s={}){let o={...wn,...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,`
1018
+ </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 ns(t=[],s=[],o=[],p){return JSON.stringify({components:t,templates:s,directives:o,extraContent:p||""},null,2)}async function rs(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 Wt.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 Yr(s,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&o)console.log("Generating template documentation..."),y=await Qr(o),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=es(u,y,g,w),E="md";break;case"html":S=ts(u,y,g,w),E="html";break;case"json":S=ns(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 Hs(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 rs({componentsDir:o,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function dr(t,s={}){let o={...fn,...s};if(t.trim()==="")return`
1019
+ `;let p=t;if(o.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=is(p,o),p=ps(p,o),p=as(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
1020
  `).replace(/\r/g,`
1576
1021
  `),!p.endsWith(`
1577
1022
  `))p+=`
1578
- `;return p}function Fs(t,s={}){let o={...wn,...s};if(t.trim()==="")return`
1023
+ `;return p}function Vs(t,s={}){let o={...fn,...s};if(t.trim()==="")return`
1579
1024
  `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,y)=>{let g=u.split(`
1580
1025
  `),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=lr(S,o).trimEnd().split(`
1026
+ `),v=dr(S,o).trimEnd().split(`
1582
1027
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
1028
  `);return`${l}\`\`\`${m}
1584
1029
  ${v}
@@ -1586,7 +1031,7 @@ ${l}\`\`\``}),o.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replac
1586
1031
  `).replace(/\r/g,`
1587
1032
  `),!p.endsWith(`
1588
1033
  `))p+=`
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,`
1034
+ `;return p}function os(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
1035
  $1
1591
1036
  `),s=s.replace(/(@end\w+)/g,`
1592
1037
  $1
@@ -1600,10 +1045,10 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max
1600
1045
  `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>o[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1601
1046
  `),s=s.split(`
1602
1047
  `).map((c)=>c.trim()).join(`
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 zs(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>
1048
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function is(t,s){let p=os(t).split(`
1049
+ `),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(pn(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("@")&&ds(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||ls(b),I=pn(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(`
1050
+ `)}function as(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 ls(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 pn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ds(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 ps(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(`
1051
+ `)||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 mn from"fs";import Vt from"path";async function Us(t="index.stx",s={}){try{let o=s.force||!1,p=Vt.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=Vt.dirname(p);if(!mn.existsSync(c))mn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=hn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=hn("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 hn(t){switch(t){case"basic":return xn();case"component":return us();case"layout":return fs();case"blog":return ms();case"api":return gs();case"app":return hs();default:return xn()}}function xn(){return`<script>
1607
1052
  const title = "My stx Page"
1608
1053
  const description = "A page built with stx"
1609
1054
  const features = [
@@ -1628,7 +1073,7 @@ const features = [
1628
1073
  </div>
1629
1074
  @endforeach
1630
1075
  </main>
1631
- @endsection`}function gs(){return`{{-- Component: Card --}}
1076
+ @endsection`}function us(){return`{{-- Component: Card --}}
1632
1077
  {{-- Props: title, variant, collapsible --}}
1633
1078
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1634
1079
  <script>
@@ -1673,7 +1118,7 @@ const features = [
1673
1118
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
1674
1119
  .card__body { padding: 1rem; }
1675
1120
  .card.collapsed .card__body { display: none; }
1676
- </style>`}function hs(){return`<!DOCTYPE html>
1121
+ </style>`}function fs(){return`<!DOCTYPE html>
1677
1122
  <html lang="en">
1678
1123
  <head>
1679
1124
  <meta charset="UTF-8">
@@ -1724,7 +1169,7 @@ const features = [
1724
1169
 
1725
1170
  @yield('scripts')
1726
1171
  </body>
1727
- </html>`}function ys(){return`<script>
1172
+ </html>`}function ms(){return`<script>
1728
1173
  // Article metadata
1729
1174
  const title = "My Blog Post"
1730
1175
  const author = "Your Name"
@@ -1769,7 +1214,7 @@ const features = [
1769
1214
  <p>Wrap up your thoughts here.</p>
1770
1215
  </div>
1771
1216
  </article>
1772
- @endsection`}function bs(){return`<script>
1217
+ @endsection`}function gs(){return`<script>
1773
1218
  // API endpoint configuration
1774
1219
  const endpoint = "/api/data"
1775
1220
  const method = "GET"
@@ -1804,7 +1249,7 @@ const features = [
1804
1249
  }
1805
1250
  @else
1806
1251
  {{ JSON.stringify(data, null, 2) }}
1807
- @endif`}function xs(){return`<!DOCTYPE html>
1252
+ @endif`}function hs(){return`<!DOCTYPE html>
1808
1253
  <html lang="en">
1809
1254
  <head>
1810
1255
  <meta charset="UTF-8">
@@ -2029,5 +1474,560 @@ const features = [
2029
1474
  })();
2030
1475
  </script>
2031
1476
  </body>
2032
- </html>`}var Hs="f9c3713";function _o(t){return t}function Ro(t){return t}function Ns(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 De from"fs";import Te from"path";function Mn(t){try{return De.statSync(t).mtimeMs}catch{return null}}function _t(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=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(o,"pantry","@stacksjs",s);if(De.existsSync(c))return c;let l=Te.dirname(o);if(l===o)break;o=l}return null}var Ln=["@stacksjs/stx","bun-plugin-stx"];function Mi(t){try{let s=De.readFileSync(Te.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=Te.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=De.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Ln){let S=Te.join(u,w),E=Mi(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(o,S)||S,nested:y>0})}let b;try{b=De.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=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=De.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=Te.join(S,x.name,"node_modules");if(De.existsSync(R))l(R,y+1)}continue}let E=Te.join(S,"node_modules");if(De.existsSync(E))l(E,y+1)}}let m=Te.join(o,"node_modules");if(De.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 ur(t={}){let s=t.cwd?Te.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=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>De.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 (${_t(w,p)}) is OLDER than src/signals.ts (${_t(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 ${_t(b,p)}, dist ${_t(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=De.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=De.realpathSync(S)}catch{}let x=(()=>{try{return De.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 dr(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{Ns,Ls,js,Bs,lr,Fs,zs,Hs,_o,Ro,ur,dr,hn,yn,bn};
1477
+ </html>`}var Ws="f9c3713";function Io(t){return t}function Do(t){return t}var wn=`
1478
+ <script data-stx-helpers>
1479
+ (function() {
1480
+ 'use strict'
1481
+
1482
+ if (window.__stxHelpers) return
1483
+ window.__stxHelpers = true
1484
+
1485
+ window.stx = window.stx || {}
1486
+
1487
+ // ===== FORMATTERS =====
1488
+
1489
+ stx.formatCurrency = function(val, currency, locale) {
1490
+ return new Intl.NumberFormat(locale || 'en-US', {
1491
+ style: 'currency',
1492
+ currency: currency || 'USD',
1493
+ }).format(val)
1494
+ }
1495
+
1496
+ stx.formatNumber = function(val, decimals, locale) {
1497
+ var opts = {}
1498
+ if (typeof decimals === 'number') {
1499
+ opts.minimumFractionDigits = decimals
1500
+ opts.maximumFractionDigits = decimals
1501
+ }
1502
+ return new Intl.NumberFormat(locale || 'en-US', opts).format(val)
1503
+ }
1504
+
1505
+ stx.formatDate = function(val, format, locale) {
1506
+ locale = locale || 'en-US'
1507
+ var d = val instanceof Date ? val : new Date(val)
1508
+ if (isNaN(d.getTime())) return String(val)
1509
+
1510
+ if (format === 'long') return d.toLocaleDateString(locale, { year: 'numeric', month: 'long', day: 'numeric' })
1511
+ if (format === 'relative') {
1512
+ var diff = Date.now() - d.getTime()
1513
+ var mins = Math.floor(diff / 60000)
1514
+ if (mins < 1) return 'just now'
1515
+ if (mins < 60) return mins + 'm ago'
1516
+ var hrs = Math.floor(mins / 60)
1517
+ if (hrs < 24) return hrs + 'h ago'
1518
+ var days = Math.floor(hrs / 24)
1519
+ if (days < 7) return days + 'd ago'
1520
+ return d.toLocaleDateString(locale)
1521
+ }
1522
+ return d.toLocaleDateString(locale)
1523
+ }
1524
+
1525
+ stx.formatPhone = function(phone) {
1526
+ var n = String(phone).replace(/\\D/g, '')
1527
+ if (n.length === 10) return \`(\${n.slice(0,3)}) \${n.slice(3,6)}-\${n.slice(6)}\`
1528
+ if (n.length === 11 && n[0] === '1') return \`+1 (\${n.slice(1,4)}) \${n.slice(4,7)}-\${n.slice(7)}\`
1529
+ return phone
1530
+ }
1531
+
1532
+ stx.renderStars = function(rating, max) {
1533
+ max = max || 5
1534
+ var full = Math.floor(rating)
1535
+ var half = rating - full >= 0.5
1536
+ var h = ''
1537
+ for (var i = 0; i < max; i++) {
1538
+ if (i < full || (i === full && half))
1539
+ h += '<span style="color: var(--badge-amber-text, #f59e0b)">\\u2605</span>'
1540
+ else
1541
+ h += '<span style="color: var(--text-muted, #6b7280)">\\u2606</span>'
1542
+ }
1543
+ return h
1544
+ }
1545
+
1546
+ // ===== BADGE SYSTEM =====
1547
+
1548
+ var badgeMaps = {
1549
+ status: {
1550
+ 'Active Repair': 'badge-amber', 'Completed': 'badge-emerald',
1551
+ 'Pending Pickup': 'badge-blue', 'Pending Estimate': 'badge-slate',
1552
+ 'Approved': 'badge-emerald', 'In Review': 'badge-blue',
1553
+ 'Supplement': 'badge-amber', 'Draft': 'badge-slate', 'Rejected': 'badge-red',
1554
+ 'Delivered': 'badge-emerald', 'Shipped': 'badge-blue', 'Processing': 'badge-amber',
1555
+ 'In Stock': 'badge-emerald', 'Backordered': 'badge-red', 'Low Stock': 'badge-amber',
1556
+ },
1557
+ priority: { 'Rush': 'badge-red', 'High': 'badge-amber', 'Normal': 'badge-blue', 'Low': 'badge-slate' },
1558
+ severity: { 'light': 'severity-light', 'moderate': 'severity-moderate', 'heavy': 'severity-heavy' },
1559
+ type: { 'OEM': 'badge-blue', 'Aftermarket': 'badge-amber', 'Recycled': 'badge-emerald', 'Reman': 'badge-slate' },
1560
+ drp: { 'Active DRP': 'badge-emerald', 'Preferred': 'badge-blue', 'Standard': 'badge-slate' },
1561
+ }
1562
+
1563
+ stx.registerBadgeMap = function(name, map) {
1564
+ badgeMaps[name] = Object.assign(badgeMaps[name] || {}, map)
1565
+ }
1566
+
1567
+ stx.badgeClass = function(value, mapName) {
1568
+ var map = badgeMaps[mapName || 'status'] || badgeMaps.status
1569
+ return map[value] || 'badge-slate'
1570
+ }
1571
+
1572
+ stx.badge = function(value, mapName) {
1573
+ return \`<span class="inline-flex px-2.5 py-1 rounded-full text-xs font-medium \${stx.badgeClass(value, mapName)}">\${value}</span>\`
1574
+ }
1575
+
1576
+ // ===== DETAIL PANEL BUILDER =====
1577
+
1578
+ function esc(v) { return v != null ? v : '\\u2014' }
1579
+
1580
+ stx.detail = {
1581
+ panel: function(opts) {
1582
+ if (!opts || !opts.title) return ''
1583
+ var badges = ''
1584
+ if (opts.badges) {
1585
+ opts.badges.forEach(function(b) { badges += stx.badge(b.text, b.map) })
1586
+ }
1587
+ return \`
1588
+ <div style="display:flex;align-items:center;justify-content:space-between;padding:1.25rem 1.5rem;border-bottom:1px solid var(--border-main)">
1589
+ <div>
1590
+ <h2 style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${opts.title}</h2>
1591
+ \${opts.subtitle ? \`<p style="font-size:0.75rem;color:var(--text-muted);margin-top:0.25rem">\${opts.subtitle}</p>\` : ''}
1592
+ </div>
1593
+ <div style="display:flex;align-items:center;gap:0.75rem">
1594
+ \${badges}
1595
+ <button onclick="closeSlideOver()" style="padding:0.5rem;border-radius:0.5rem;color:var(--text-muted);background:none;border:none;cursor:pointer;font-size:1.5rem;line-height:1" aria-label="Close">&times;</button>
1596
+ </div>
1597
+ </div>\`
1598
+ },
1599
+
1600
+ section: function(label, rows) {
1601
+ var inner = ''
1602
+ if (rows) {
1603
+ if (!Array.isArray(rows) && typeof rows === 'object') {
1604
+ Object.keys(rows).forEach(function(k) { inner += stx.detail.row(k, rows[k]) })
1605
+ }
1606
+ else {
1607
+ rows.forEach(function(r) {
1608
+ if (Array.isArray(r)) inner += stx.detail.row(r[0], r[1])
1609
+ else inner += stx.detail.row(r.label, r.value)
1610
+ })
1611
+ }
1612
+ }
1613
+ return \`
1614
+ <div class="detail-section">
1615
+ <div class="detail-label">\${label}</div>
1616
+ \${inner}
1617
+ </div>\`
1618
+ },
1619
+
1620
+ row: function(label, value) {
1621
+ return \`
1622
+ <div class="detail-row">
1623
+ <span class="detail-row-label">\${label}</span>
1624
+ <span class="detail-row-value">\${esc(value)}</span>
1625
+ </div>\`
1626
+ },
1627
+
1628
+ stats: function(items) {
1629
+ var list = Array.isArray(items)
1630
+ ? items
1631
+ : Object.keys(items).map(function(k) { return { label: k, value: items[k] } })
1632
+
1633
+ var cards = list.map(function(item) {
1634
+ return \`
1635
+ <div style="padding:0.75rem;border-radius:0.5rem;background:var(--bg-subtle);text-align:center">
1636
+ <div style="font-size:1.25rem;font-weight:700;color:var(--text-primary)">\${item.value}</div>
1637
+ <div style="font-size:0.6875rem;color:var(--text-muted);margin-top:0.25rem">\${item.label}</div>
1638
+ </div>\`
1639
+ }).join('')
1640
+
1641
+ return \`<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:0.75rem;padding:0 1.5rem 1rem">\${cards}</div>\`
1642
+ },
1643
+
1644
+ timeline: function(items) {
1645
+ var entries = items.map(function(item, i) {
1646
+ var color = item.color || 'var(--text-accent)'
1647
+ var isLast = i === items.length - 1
1648
+
1649
+ return \`
1650
+ <div style="display:flex;gap:0.75rem">
1651
+ <div style="display:flex;flex-direction:column;align-items:center;flex-shrink:0">
1652
+ <div style="width:10px;height:10px;border-radius:50%;background:\${color};flex-shrink:0"></div>
1653
+ \${!isLast ? '<div style="width:2px;flex:1;background:var(--bar-track);min-height:24px"></div>' : ''}
1654
+ </div>
1655
+ <div style="padding-bottom:\${isLast ? '0' : '1rem'};flex:1">
1656
+ <div style="font-size:0.8125rem;font-weight:500;color:var(--text-primary)">\${item.title}</div>
1657
+ \${item.description ? \`<div style="font-size:0.75rem;color:var(--text-muted);margin-top:0.125rem">\${item.description}</div>\` : ''}
1658
+ \${item.meta ? \`<div style="font-size:0.6875rem;color:var(--text-tertiary);margin-top:0.25rem">\${item.meta}</div>\` : ''}
1659
+ </div>
1660
+ </div>\`
1661
+ }).join('')
1662
+
1663
+ return \`<div style="padding:0 1.5rem 1rem">\${entries}</div>\`
1664
+ },
1665
+
1666
+ open: function(html) {
1667
+ if (typeof openSlideOver === 'function') openSlideOver(html)
1668
+ },
1669
+ }
1670
+
1671
+ // ===== DATA TABLE HELPERS =====
1672
+
1673
+ stx.table = {
1674
+ filter: function(opts) {
1675
+ var searchEl = document.getElementById(opts.searchId)
1676
+ var search = searchEl ? searchEl.value.toLowerCase() : ''
1677
+ var rows = document.querySelectorAll(opts.rowSelector || 'tbody tr')
1678
+ var filters = opts.filters || []
1679
+ var matched = []
1680
+
1681
+ rows.forEach(function(row) {
1682
+ var text = row.textContent.toLowerCase()
1683
+ var matchSearch = !search || text.indexOf(search) !== -1
1684
+ var matchFilters = filters.every(function(f) {
1685
+ var el = document.getElementById(f.id)
1686
+ if (!el) return true
1687
+ var val = el.value
1688
+ if (!val || val === f.allValue) return true
1689
+ return row.getAttribute(\`data-\${f.attr}\`) === val
1690
+ })
1691
+
1692
+ if (matchSearch && matchFilters) matched.push(row)
1693
+ else row.style.display = 'none'
1694
+ })
1695
+
1696
+ return matched
1697
+ },
1698
+
1699
+ sort: function(rows, sortBy, direction) {
1700
+ direction = direction || 'asc'
1701
+ return rows.slice().sort(function(a, b) {
1702
+ var aVal = a.getAttribute(\`data-\${sortBy}\`) || a.textContent
1703
+ var bVal = b.getAttribute(\`data-\${sortBy}\`) || b.textContent
1704
+ var aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''))
1705
+ var bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''))
1706
+ if (!isNaN(aNum) && !isNaN(bNum)) return direction === 'asc' ? aNum - bNum : bNum - aNum
1707
+ return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
1708
+ })
1709
+ },
1710
+ }
1711
+
1712
+ // ===== PAGINATION =====
1713
+
1714
+ stx.pagination = function(opts) {
1715
+ var page = opts.page || 1
1716
+ var perPage = opts.perPage || 10
1717
+ var items = opts.items || []
1718
+ var total = items.length
1719
+ var totalPages = Math.max(1, Math.ceil(total / perPage))
1720
+ if (page > totalPages) page = totalPages
1721
+
1722
+ var start = (page - 1) * perPage
1723
+ var end = Math.min(start + perPage, total)
1724
+
1725
+ items.forEach(function(el, i) { el.style.display = (i >= start && i < end) ? '' : 'none' })
1726
+
1727
+ var ids = { count: opts.countId, total: opts.totalId, empty: opts.emptyId, bar: opts.barId }
1728
+ if (ids.count) { var el = document.getElementById(ids.count); if (el) el.textContent = total === 0 ? '0' : \`\${start + 1}\\u2013\${end}\` }
1729
+ if (ids.total) { var el = document.getElementById(ids.total); if (el) el.textContent = total }
1730
+ if (ids.empty) { var el = document.getElementById(ids.empty); if (el) el.style.display = total === 0 ? 'block' : 'none' }
1731
+ if (ids.bar) { var el = document.getElementById(ids.bar); if (el) el.style.display = total === 0 ? 'none' : '' }
1732
+
1733
+ if (opts.buttonsId) {
1734
+ var wrap = document.getElementById(opts.buttonsId)
1735
+ if (wrap) {
1736
+ var go = opts.goToPage
1737
+ var pages = stx.pagination.getPages(page, totalPages)
1738
+
1739
+ var btn = function(label, target, disabled) {
1740
+ return \`<button onclick="\${go}(\${target})" \${disabled ? 'disabled' : ''}
1741
+ class="px-3 py-1.5 rounded-lg text-sm cursor-pointer"
1742
+ style="background:var(--bg-subtle);border:1px solid var(--border-input);color:\${disabled ? 'var(--text-muted)' : 'var(--text-primary)'};opacity:\${disabled ? '0.5' : '1'}">\${label}</button>\`
1743
+ }
1744
+
1745
+ var h = btn('Previous', page - 1, page === 1)
1746
+ pages.forEach(function(p) {
1747
+ if (p === '...') {
1748
+ h += '<span class="px-2 text-sm" style="color:var(--text-muted)">\\u2026</span>'
1749
+ }
1750
+ else if (p === page) {
1751
+ h += \`<button class="w-9 h-9 rounded-lg text-sm font-medium" style="background:var(--btn-primary-bg, var(--text-accent));color:#fff">\${p}</button>\`
1752
+ }
1753
+ else {
1754
+ h += btn(p, p, false)
1755
+ }
1756
+ })
1757
+ h += btn('Next', page + 1, page === totalPages)
1758
+ wrap.innerHTML = h
1759
+ }
1760
+ }
1761
+
1762
+ return { page: page, totalPages: totalPages, total: total, start: start, end: end }
1763
+ }
1764
+
1765
+ stx.pagination.getPages = function(current, total) {
1766
+ if (total <= 7) return Array.from({ length: total }, function(_, i) { return i + 1 })
1767
+ var pages = [1]
1768
+ if (current > 3) pages.push('...')
1769
+ for (var i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) pages.push(i)
1770
+ if (current < total - 2) pages.push('...')
1771
+ pages.push(total)
1772
+ return pages
1773
+ }
1774
+
1775
+ // ===== UTILITIES =====
1776
+
1777
+ stx.debounce = function(fn, delay) {
1778
+ var timer
1779
+ return function() {
1780
+ var args = arguments, ctx = this
1781
+ clearTimeout(timer)
1782
+ timer = setTimeout(function() { fn.apply(ctx, args) }, delay || 250)
1783
+ }
1784
+ }
1785
+
1786
+ })()
1787
+ </script>
1788
+ `;import Me from"fs";import Te from"path";function An(t){try{return Me.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 Pi(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function On(t,s="stx"){let o=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(o,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(o);if(l===o)break;o=l}return null}var Dn=["@stacksjs/stx","bun-plugin-stx"];function Ai(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),o=JSON.parse(s)?.version;return typeof o==="string"?o:null}catch{return null}}function Oi(t,s=6){let o=Te.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=Me.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Dn){let S=Te.join(u,w),E=Ai(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(o,S)||S,nested:y>0})}let b;try{b=Me.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=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=Te.join(S,x.name,"node_modules");if(Me.existsSync(R))l(R,y+1)}continue}let E=Te.join(S,"node_modules");if(Me.existsSync(E))l(E,y+1)}}let m=Te.join(o,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Di(t){let s=[];for(let o of Dn){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 pr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),o=t.resolve??Pi,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 Di(Oi(s)))c.push(y);let u=On(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,b=An(y),w=g?An(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=Te.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=Me.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=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.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 fr(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(`
1789
+ `)}var ft={name:"bun-plugin-stx",async setup(t){let o={...await i(),...t.config?.stx},p=new Set,c=o.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let m=await Wn(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 Zt(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 un(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new un(`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:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let R=new K(`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 n(b,S,m,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-47apfsxp.js"),R=x(w.join(`
1790
+ `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+R+`
1791
+ `+v.slice(k);else v+=`
1792
+ ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),o.cache&&o.cachePath){if(await Qt(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 K(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),Et.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>
1793
+ <html lang="en">
1794
+ <head>
1795
+ <meta charset="UTF-8">
1796
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1797
+ <title>stx Rendering Error</title>
1798
+ <style>
1799
+ body { font-family: system-ui, -apple-system, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; line-height: 1.6; }
1800
+ .error-header { color: #dc3545; border-left: 4px solid #dc3545; padding-left: 16px; margin-bottom: 24px; }
1801
+ .error-details { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 16px; margin: 16px 0; }
1802
+ .error-code { background: #2d3748; color: #e2e8f0; padding: 16px; border-radius: 8px; overflow-x: auto; font-family: 'Monaco', 'Menlo', monospace; font-size: 14px; }
1803
+ .help-section { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 16px; margin-top: 24px; }
1804
+ .file-path { font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px; }
1805
+ </style>
1806
+ </head>
1807
+ <body>
1808
+ <div class="error-header">
1809
+ <h1>stx Template Error</h1>
1810
+ <p>An error occurred while processing your stx template.</p>
1811
+ </div>
1812
+
1813
+ <div class="error-details">
1814
+ <h3>Error Details</h3>
1815
+ <p><strong>File:</strong> <span class="file-path">${h(m)}</span></p>
1816
+ <p><strong>Error:</strong> ${h(y.message)}</p>
1817
+ ${b?`<p><strong>Line:</strong> ${h(String(b))}</p>`:""}
1818
+ ${w?`<p><strong>Context:</strong> ${h(String(w))}</p>`:""}
1819
+ </div>
1820
+
1821
+ ${y.stack?`
1822
+ <div class="error-details">
1823
+ <h3>Stack Trace</h3>
1824
+ <pre class="error-code">${h(y.stack)}</pre>
1825
+ </div>`:""}
1826
+
1827
+ <div class="help-section">
1828
+ <h3>Troubleshooting Tips</h3>
1829
+ <ul>
1830
+ <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
1831
+ <li>Verify that all variables used in the template are properly defined</li>
1832
+ <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
1833
+ <li>Run <code>stx debug ${h(_t.basename(m))}</code> for detailed analysis</li>
1834
+ <li>Enable debug mode in your stx config for more detailed error messages</li>
1835
+ </ul>
1836
+ </div>
1837
+ </body>
1838
+ </html>`:`<!DOCTYPE html>
1839
+ <html lang="en">
1840
+ <head>
1841
+ <meta charset="UTF-8">
1842
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1843
+ <title>Error</title>
1844
+ <style>
1845
+ body { font-family: system-ui, -apple-system, sans-serif; max-width: 600px; margin: 80px auto; padding: 20px; text-align: center; color: #333; }
1846
+ </style>
1847
+ </head>
1848
+ <body>
1849
+ <h1>Something went wrong</h1>
1850
+ <p>An internal error occurred. Please try again later.</p>
1851
+ </body>
1852
+ </html>`,loader:"html"}}})}};async function yn(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(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=a(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($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.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(($e)=>$e.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 wt(S);let E=o;try{if(E=await Ye(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=Pt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-ycpq3gxc.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-h4avjh3q.js"),$e=F.broadcasting;await G($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Ae=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Ae))try{let le=await se(Ae);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-hwycbxg7.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=zi({port:E,async fetch(I){return At(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(Ne.existsSync(se)&&Ne.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 $e=Se.dirname(u),he=Se.join($e,F.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let le=Bun.file(he),W=Se.extname(he).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 Ae=Se.join(process.cwd(),"public",F.pathname);if(Ne.existsSync(Ae)&&Ne.statSync(Ae).isFile()){let le=Bun.file(Ae),W=Se.extname(Ae).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}
1853
+ ${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1854
+ ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1855
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
1856
+ ${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(`
1857
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.url.toString(),()=>{if(p)Ne.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),F=Tt(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=Ne.watch(I,{recursive:!0},async(G,se)=>{if(!se||Rt(se))return;if(Ct(se)){console.log(`${e.yellow}File ${e.bright}${se}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await en(S),c&&l)if($e)l.reload(se);else l.error("Build failed - check console for details")}else if($t(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:Ni}=globalThis.Bun;import it from"fs";import Pe from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.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(Pe.sep)}async function bn(t,s={}){let o=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Pe.resolve(v);if(!it.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");it.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Pe.dirname(Pe.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=Pe.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((Ae)=>`<option value="${Ae}"${Ae===j?" selected":""}>${Ae}</option>`).join(`
1858
+ `),se=`
1859
+ <!DOCTYPE html>
1860
+ <html lang="en">
1861
+ <head>
1862
+ <meta charset="UTF-8">
1863
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1864
+ <title>${Un(B.title||Pe.basename(x))}</title>
1865
+ <!-- Syntax highlighting styles -->
1866
+ <style id="syntax-theme">
1867
+ :root {
1868
+ --shiki-color-text: #24292e;
1869
+ --shiki-color-background: #ffffff;
1870
+ --shiki-token-constant: #005cc5;
1871
+ --shiki-token-string: #032f62;
1872
+ --shiki-token-comment: #6a737d;
1873
+ --shiki-token-keyword: #d73a49;
1874
+ --shiki-token-parameter: #24292e;
1875
+ --shiki-token-function: #6f42c1;
1876
+ --shiki-token-string-expression: #032f62;
1877
+ --shiki-token-punctuation: #24292e;
1878
+ --shiki-token-link: #032f62;
1879
+ }
1880
+ pre {
1881
+ background-color: var(--shiki-color-background);
1882
+ padding: 1rem;
1883
+ border-radius: 4px;
1884
+ }
1885
+ code {
1886
+ color: var(--shiki-color-text);
1887
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1888
+ }
1889
+ .dark-mode {
1890
+ --shiki-color-text: #e1e4e8;
1891
+ --shiki-color-background: #24292e;
1892
+ --shiki-token-constant: #79b8ff;
1893
+ --shiki-token-string: #9ecbff;
1894
+ --shiki-token-comment: #6a737d;
1895
+ --shiki-token-keyword: #f97583;
1896
+ --shiki-token-parameter: #e1e4e8;
1897
+ --shiki-token-function: #b392f0;
1898
+ --shiki-token-string-expression: #9ecbff;
1899
+ --shiki-token-punctuation: #e1e4e8;
1900
+ --shiki-token-link: #9ecbff;
1901
+ }
1902
+ </style>
1903
+ <style>
1904
+ body {
1905
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
1906
+ line-height: 1.6;
1907
+ color: #333;
1908
+ max-width: 800px;
1909
+ margin: 0 auto;
1910
+ padding: 2rem;
1911
+ }
1912
+ pre, code {
1913
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1914
+ }
1915
+ pre {
1916
+ border-radius: 4px;
1917
+ padding: 0;
1918
+ margin: 1.5rem 0;
1919
+ overflow-x: auto;
1920
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
1921
+ }
1922
+ pre code {
1923
+ display: block;
1924
+ padding: 1rem;
1925
+ overflow-x: auto;
1926
+ }
1927
+ /* Apply background color to code blocks based on theme */
1928
+ pre.syntax-highlighter {
1929
+ background-color: var(--shiki-color-background) !important;
1930
+ }
1931
+ .dark-mode pre.syntax-highlighter {
1932
+ background-color: var(--shiki-color-background) !important;
1933
+ }
1934
+ code {
1935
+ padding: 0.2rem 0.4rem;
1936
+ border-radius: 3px;
1937
+ }
1938
+ h1, h2, h3, h4 {
1939
+ margin-top: 2rem;
1940
+ margin-bottom: 1rem;
1941
+ }
1942
+ h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
1943
+ h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
1944
+ h3 { color: #444; }
1945
+ img {
1946
+ max-width: 100%;
1947
+ border-radius: 4px;
1948
+ margin: 1rem 0;
1949
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1950
+ }
1951
+ blockquote {
1952
+ border-left: 4px solid #ddd;
1953
+ padding-left: 1rem;
1954
+ margin-left: 0;
1955
+ color: #555;
1956
+ background: #f9f9f9;
1957
+ padding: 0.5rem 1rem;
1958
+ margin: 1.5rem 0;
1959
+ }
1960
+ table {
1961
+ border-collapse: collapse;
1962
+ width: 100%;
1963
+ margin: 1.5rem 0;
1964
+ }
1965
+ th, td {
1966
+ border: 1px solid #ddd;
1967
+ padding: 0.5rem;
1968
+ }
1969
+ th {
1970
+ background: #f0f0f0;
1971
+ text-align: left;
1972
+ }
1973
+ tr:nth-child(even) {
1974
+ background-color: #f8f8f8;
1975
+ }
1976
+ a {
1977
+ color: #0066cc;
1978
+ text-decoration: none;
1979
+ }
1980
+ a:hover {
1981
+ text-decoration: underline;
1982
+ }
1983
+ hr {
1984
+ border: 0;
1985
+ border-top: 1px solid #eee;
1986
+ margin: 2rem 0;
1987
+ }
1988
+ .frontmatter {
1989
+ background: #f8f8f8;
1990
+ border-radius: 4px;
1991
+ padding: 1.5rem;
1992
+ margin-bottom: 2rem;
1993
+ font-size: 0.9rem;
1994
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
1995
+ border-left: 4px solid #ddd;
1996
+ }
1997
+ .frontmatter-item {
1998
+ margin-bottom: 0.5rem;
1999
+ display: flex;
2000
+ }
2001
+ .frontmatter-label {
2002
+ font-weight: bold;
2003
+ min-width: 100px;
2004
+ color: #555;
2005
+ }
2006
+ ${bt()}
2007
+ </style>
2008
+ </head>
2009
+ <body>
2010
+ ${kt(B)}
2011
+ ${vt(G)}
2012
+
2013
+ ${k}
2014
+
2015
+ <script>
2016
+ ${St()}
2017
+ </script>
2018
+ </body>
2019
+ </html>
2020
+ `,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={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}:`,De(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}:
2021
+ ${De(P,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=sr(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}`,De(v)),!1}};if(!await y())return!1;let b=o;try{if(b=await Ye(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=Ni({port:b,async fetch(v){let x=new URL(v.url),R=Pe.join(process.cwd(),"public",x.pathname);if(it.existsSync(R)&&it.statSync(R).isFile()){let L=Bun.file(R),j=Pe.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}
2022
+ </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>",`${wn}
2023
+ </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=Pe.join(c,x.pathname);if(it.existsSync(B)&&it.statSync(B).isFile()){let L=Bun.file(B),j=Pe.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>${Un(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":_e,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}
2024
+ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
2025
+ ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
2026
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
2027
+ ${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:Pe.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:Pe.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(`
2028
+ 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}`),ye.clear(),ee(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Un(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ui}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return xt(await Bun.file(t).text())}catch{return}}function qt(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 vn(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-ycpq3gxc.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-hwycbxg7.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(!ve.existsSync(R)&&!g._layerPageDirs?.some((A)=>ve.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(ve.existsSync(A)){let N=M(ie.dirname(A),{pagesDir:ie.basename(A)});for(let V of N){let we=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:we},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 ti(u,s.stxOptions?.shell),I){if(P=await vr(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}`)}}Qe(),await tt(u);let F=et();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-ycpq3gxc.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-h4avjh3q.js"),we=z.broadcasting;await N(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let 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 $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Ae=new Set,le=async(A)=>{let z=ir(R,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((we)=>we.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:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-ycpq3gxc.js"),{checkCache:oe,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-r7r5h2eh.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},O={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(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 ve.promises.stat(A.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=W.get(A.filePath);return{route:A,content:Re,status:gt?.status??await qn(A.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(A.filePath,O);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(A.filePath);return{route:A,content:He,status:ze?.status??await qn(A.filePath),headers:ze?.headers}}}let me=pe?await X(A.filePath):await Bun.file(A.filePath).text(),Ce=xt(me),{classifyAllScripts:Y}=await import("./chunk-ycpq3gxc.js"),Le=Y(me),Ve=Le.server.map((de)=>de.content),ue=me;for(let de of Le.server)ue=ue.replace(de.fullTag,"");let fe={__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,fe,A.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Ie?.message||Ie)}let Ke=new Set,Oe;if(s.profile){let de=performance.now();Oe=await N(ue,fe,A.filePath,O,Ke);let Ie=performance.now()-de,He=ie.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Oe=await N(ue,fe,A.filePath,O,Ke);if(!P)Oe=await Ge(Oe,{router:O.router});{let{interpolateScriptExpressions:de}=await import("./chunk-47apfsxp.js");Oe=Oe.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${de(ze,fe)}</script>`})}if(P)Oe=ge(Oe,{preserveHead:!0});if(pe&&be)await Q(A.filePath,Oe,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-xrbqf77j.js"),lt=Kn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...O,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return N(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)Ae.add(A.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Oe,status:Kt??Ce,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()=>{he.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)he.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 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 wt(u);let at=o;try{if(at=await Ye(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=Pt({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=Ui({port:at,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",V=ie.join(u,N,z.pathname),we=ie.join(u,z.pathname),We=ie.join($e,z.pathname);if([V,we,We].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(oe?.isFile()&&!w(we,u,S))return qt(we);if(Q?.isFile()&&!w(We,u,S))return qt(We);if(z.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(z.pathname.slice(16));if(O)try{let be=`<${O} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),pe,new Set);return new Response(me,{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-akbb6j7s.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 X=await E(A);if(X)return X;let J=gn(z.pathname,k);if(J){let O=he.get(J.route.pattern),be=Ae.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,me=O.headers??{},Ce=(J.route.filePath?je(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.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(Ce.middleware){let Le=nt(z.pathname,J.params,Ce,z.search),Ve=rt(Le,null,A,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Oe=new Headers(ue.responseHeaders);return Oe.set("Location",fe),new Response(null,{status:Ke,headers:Oe})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.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(ue.state).length>0){let fe=`<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>",`${fe}</head>`)}}let Y=O.content;if(P&&ni(A)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ei(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":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Yi]:cs(),...C(),"Cache-Control":_e}})}if(P)Y=kn(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:Le,streamToResponse:Ve}=await import("./chunk-xrbqf77j.js");return Ve(Le(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",...me}})}}if(L.length>0){let O=L.map((pe)=>pe.route),be=gn(z.pathname,O);if(be){let pe=j.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=kn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{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 me=j.get(pe)||j.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=kn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ze(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.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 Je=await le(404);if(Je){let O=Je;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}
2029
+ ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
2030
+ ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
2031
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
2032
+ ${e.yellow}Routes:${e.reset}`);let jt=[...or(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(`
2033
+ 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(ve.existsSync(z)){let V=await Bun.file(z).text();A=Tt(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)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let X of Object.values(Q.resources)){if(!ve.existsSync(X))continue;let J=ve.realpathSync(X);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Q,X]of N)if(!oe.has(Q))X.close(),N.delete(Q);for(let Q of oe)if(!N.has(Q)&&ve.existsSync(Q))N.set(Q,ve.watch(Q,{recursive:!0},(X,J)=>{We(Q,X,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(oe,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(oe,Q,X)),we),Ge=async(oe,Q,X)=>{if(!X||Rt(X))return;if(Ct(X)){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(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),c&&l)l.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-r7r5h2eh.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(I&&X){if(ie.resolve(oe,X)===I||ie.basename(I)===X){let ke=await vr(I,s.stxOptions||{});if(ke)P=ke}}if(await qe(),await en(u),c&&l)l.reload(X)}else{console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-r7r5h2eh.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(await qe(),c&&l)l.reload(X)}}else if($t(X)){if(console.log(`${e.cyan}CSS ${X} changed${e.reset}`),c&&l)l.updateCss(X)}};V(),process.on("SIGINT",()=>{for(let oe of N.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Bs,Fs,zs,Hs,dr,Vs,Us,Ws,Io,Do,pr,fr,yn,bn,vn};