@stacksjs/stx 0.2.412 → 0.2.414

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 (350) hide show
  1. package/dist/appearance-bootstrap.js +1 -1
  2. package/dist/binding-manifest.d.ts +1 -1
  3. package/dist/builtins/image-delivery.d.ts +38 -0
  4. package/dist/builtins/image-delivery.js +17 -0
  5. package/dist/builtins/stx-image.js +1 -5
  6. package/dist/bundle-analyzer.js +20 -20
  7. package/dist/chunk-020xyn9q.js +3 -0
  8. package/dist/chunk-04jhmfbz.js +2 -0
  9. package/dist/chunk-10957mcb.js +2 -0
  10. package/dist/chunk-1098mas0.js +2 -0
  11. package/dist/chunk-169n1vpx.js +12 -0
  12. package/dist/chunk-1b6t12hd.js +2 -0
  13. package/dist/chunk-1chw8xsw.js +2 -0
  14. package/dist/chunk-1xdzcy9d.js +14 -0
  15. package/dist/chunk-2ce7f416.js +2 -0
  16. package/dist/chunk-2gr351s0.js +7 -0
  17. package/dist/chunk-2mkcjw08.js +2 -0
  18. package/dist/chunk-2v8wztd5.js +2 -0
  19. package/dist/chunk-340a824p.js +2 -0
  20. package/dist/chunk-39g1134q.js +2 -0
  21. package/dist/chunk-3c74vag1.js +2 -0
  22. package/dist/chunk-3kthfs03.js +3 -0
  23. package/dist/chunk-3qn1wcdg.js +2 -0
  24. package/dist/chunk-3s2vnqcf.js +2 -0
  25. package/dist/chunk-48bwk47q.js +2 -0
  26. package/dist/chunk-4bjravgk.js +2 -0
  27. package/dist/chunk-4jjme6a5.js +2 -0
  28. package/dist/chunk-5g3y8kym.js +2 -0
  29. package/dist/chunk-5gsxpaqk.js +2 -0
  30. package/dist/{chunk-bwsxym3d.js → chunk-5qns2sdz.js} +17 -17
  31. package/dist/chunk-69mc2np8.js +2785 -0
  32. package/dist/chunk-6cfa3g0r.js +2 -0
  33. package/dist/{chunk-bjar18jd.js → chunk-6h38kkjf.js} +46 -52
  34. package/dist/chunk-6hc5vz20.js +3 -0
  35. package/dist/chunk-6q6g76vg.js +499 -0
  36. package/dist/{chunk-dbc5awz9.js → chunk-6sgswrqw.js} +29 -29
  37. package/dist/chunk-6y8hnymb.js +2 -0
  38. package/dist/chunk-74j18qk0.js +930 -0
  39. package/dist/chunk-752hw7cd.js +4 -0
  40. package/dist/{chunk-t5ja7qkn.js → chunk-765e1s44.js} +11 -76
  41. package/dist/chunk-7gkv67ky.js +4 -0
  42. package/dist/chunk-7z2ra0yf.js +2 -0
  43. package/dist/chunk-866n724v.js +2 -0
  44. package/dist/chunk-8nhshfz6.js +5 -0
  45. package/dist/chunk-92ps1xpk.js +2 -0
  46. package/dist/chunk-9g27ybyr.js +3 -0
  47. package/dist/{chunk-xq1acw1r.js → chunk-9pt8fd2n.js} +13 -13
  48. package/dist/{chunk-qvnbnsv9.js → chunk-9vrja6vp.js} +4 -4
  49. package/dist/chunk-9xrbve19.js +2 -0
  50. package/dist/chunk-a688m6js.js +3 -0
  51. package/dist/chunk-afhxw2t8.js +2 -0
  52. package/dist/chunk-ak1cgcah.js +5 -0
  53. package/dist/{chunk-4m7ajama.js → chunk-amd6ey3t.js} +14 -14
  54. package/dist/chunk-apg16xcn.js +2 -0
  55. package/dist/chunk-b52s5z0c.js +2 -0
  56. package/dist/chunk-b84h16er.js +61 -0
  57. package/dist/{chunk-hx998w7n.js → chunk-bay9s6rs.js} +13 -13
  58. package/dist/chunk-bmt7w2pk.js +2 -0
  59. package/dist/chunk-btmhj5t7.js +2 -0
  60. package/dist/chunk-ce1sejr3.js +3 -0
  61. package/dist/chunk-cg8hg6cs.js +3 -0
  62. package/dist/{chunk-8wp64mym.js → chunk-czxt605c.js} +4 -5
  63. package/dist/chunk-d44b9ktb.js +4 -0
  64. package/dist/chunk-daz5aqcf.js +24 -0
  65. package/dist/chunk-dgdm3hy3.js +2 -0
  66. package/dist/chunk-dvgv8nry.js +11 -0
  67. package/dist/chunk-dx7n22ed.js +2 -0
  68. package/dist/chunk-e57rhf65.js +3 -0
  69. package/dist/chunk-eed4fwps.js +3 -0
  70. package/dist/chunk-ej9j6k1q.js +3 -0
  71. package/dist/chunk-et0rr8c7.js +3 -0
  72. package/dist/chunk-f46qsp4m.js +4 -0
  73. package/dist/chunk-f6az0xj5.js +2 -0
  74. package/dist/{chunk-bjcsc6wx.js → chunk-fh1qrp68.js} +21 -21
  75. package/dist/chunk-fjs0a8h7.js +2 -0
  76. package/dist/chunk-fr2txj8q.js +829 -0
  77. package/dist/{chunk-vx86cf4r.js → chunk-ft4p6d28.js} +14 -14
  78. package/dist/chunk-fyzajkrx.js +2 -0
  79. package/dist/chunk-fzapbw9p.js +3 -0
  80. package/dist/chunk-g578mcb0.js +194 -0
  81. package/dist/chunk-gawrg4gb.js +216 -0
  82. package/dist/chunk-gw07qmjk.js +2 -0
  83. package/dist/chunk-h0atqq82.js +32 -0
  84. package/dist/chunk-h6zsqb9r.js +3 -0
  85. package/dist/{chunk-hdysywd8.js → chunk-h85hrwkq.js} +13 -13
  86. package/dist/chunk-hbxz85wy.js +2 -0
  87. package/dist/chunk-hjg3ndgh.js +2 -0
  88. package/dist/chunk-hkxsewzk.js +2 -0
  89. package/dist/chunk-hrbbbtbn.js +2 -0
  90. package/dist/chunk-j03revz2.js +8 -0
  91. package/dist/chunk-j9qcrwbg.js +2 -0
  92. package/dist/chunk-jk4njz0w.js +2 -0
  93. package/dist/chunk-jmabeqfq.js +2 -0
  94. package/dist/chunk-jt0n43mk.js +2 -0
  95. package/dist/chunk-kjbv8a3m.js +2 -0
  96. package/dist/chunk-m1vdghnx.js +2 -0
  97. package/dist/chunk-m4sk62wb.js +5 -0
  98. package/dist/chunk-md8rqn48.js +30 -0
  99. package/dist/chunk-mepdnezf.js +17 -0
  100. package/dist/chunk-mhq0pjws.js +2 -0
  101. package/dist/chunk-mp6hy8g4.js +2 -0
  102. package/dist/chunk-ngc2wke4.js +3 -0
  103. package/dist/chunk-nn2vstke.js +2 -0
  104. package/dist/chunk-p2v2a68k.js +2 -0
  105. package/dist/{chunk-qn5srnj3.js → chunk-pbh4smw3.js} +16 -16
  106. package/dist/chunk-pdt69hpb.js +2 -0
  107. package/dist/chunk-pgzvyrv6.js +29 -0
  108. package/dist/chunk-pj1wg7jg.js +2 -0
  109. package/dist/chunk-pqxzp1bb.js +3 -0
  110. package/dist/chunk-px7fvbj6.js +3 -0
  111. package/dist/chunk-q4c06e8x.js +20 -0
  112. package/dist/chunk-q6vrb2pe.js +2 -0
  113. package/dist/chunk-q7qchkvk.js +2 -0
  114. package/dist/chunk-q9bdh4s5.js +8 -0
  115. package/dist/chunk-qet5gc6s.js +2033 -0
  116. package/dist/chunk-qz519eyp.js +2 -0
  117. package/dist/chunk-r3f9jcf7.js +5 -0
  118. package/dist/chunk-rs4v4fha.js +4 -0
  119. package/dist/chunk-s2x4wcrz.js +2 -0
  120. package/dist/chunk-s5xezjps.js +3 -0
  121. package/dist/chunk-scezfp0w.js +30 -0
  122. package/dist/chunk-sd321bn3.js +2 -0
  123. package/dist/{chunk-eenk6s3t.js → chunk-sd47dzs0.js} +79 -79
  124. package/dist/chunk-se7mwqd1.js +2 -0
  125. package/dist/chunk-shr559s7.js +3 -0
  126. package/dist/chunk-syaw6b75.js +2 -0
  127. package/dist/chunk-t4hzprsm.js +3 -0
  128. package/dist/{chunk-s9za1vvd.js → chunk-t61vdbje.js} +89 -89
  129. package/dist/chunk-tfexmdkt.js +3 -0
  130. package/dist/chunk-thyt8ed8.js +6 -0
  131. package/dist/chunk-v091jft4.js +12 -0
  132. package/dist/chunk-v4vaqxrf.js +33 -0
  133. package/dist/chunk-vgvtnwxa.js +4 -0
  134. package/dist/chunk-x0q32ees.js +3 -0
  135. package/dist/chunk-x5bpeb4a.js +2 -0
  136. package/dist/chunk-x72tv2cg.js +3 -0
  137. package/dist/chunk-xfp7k0v8.js +64 -0
  138. package/dist/chunk-xtdw3692.js +6 -0
  139. package/dist/chunk-y1cmjvk3.js +43 -0
  140. package/dist/chunk-y5310237.js +311 -0
  141. package/dist/chunk-ya0qecph.js +27 -0
  142. package/dist/chunk-yazk54jr.js +8 -0
  143. package/dist/chunk-ydjfar14.js +2 -0
  144. package/dist/chunk-ym95v4nc.js +3 -0
  145. package/dist/chunk-ynvdvbat.js +18 -0
  146. package/dist/chunk-yvx1ap9b.js +3 -0
  147. package/dist/chunk-z0g9jvv0.js +40 -0
  148. package/dist/chunk-z6d0jmjb.js +2 -0
  149. package/dist/{chunk-fpwzacpm.js → chunk-zhxdpzga.js} +4 -4
  150. package/dist/cli.js +110 -110
  151. package/dist/craft-entry.js +7 -7
  152. package/dist/craft.js +7 -7
  153. package/dist/database.js +2 -2
  154. package/dist/image-optimization/component.js +4 -4
  155. package/dist/index.d.ts +2 -0
  156. package/dist/index.js +1 -0
  157. package/dist/media/image/component.js +5 -5
  158. package/dist/media/protected/component.js +2 -2
  159. package/dist/media/video/index.js +4 -4
  160. package/dist/native/bridge/protocol.d.ts +325 -0
  161. package/dist/native/bridge/protocol.js +219 -0
  162. package/dist/native/cli.d.ts +24 -0
  163. package/dist/native/cli.js +52 -0
  164. package/dist/native/compiler/bundle.d.ts +41 -0
  165. package/dist/native/compiler/bundle.js +90 -0
  166. package/dist/native/compiler/client-script.d.ts +8 -0
  167. package/dist/native/compiler/client-script.js +31 -0
  168. package/dist/native/compiler/codegen.d.ts +10 -0
  169. package/dist/native/compiler/codegen.js +145 -0
  170. package/dist/native/compiler/headwind-to-style.d.ts +395 -0
  171. package/dist/native/compiler/headwind-to-style.js +1163 -0
  172. package/dist/native/compiler/html-to-ir.d.ts +41 -0
  173. package/dist/native/compiler/html-to-ir.js +411 -0
  174. package/dist/native/compiler/icons.d.ts +220 -0
  175. package/dist/native/compiler/icons.js +208 -0
  176. package/dist/native/compiler/ir.d.ts +234 -0
  177. package/dist/native/compiler/ir.js +15 -0
  178. package/dist/native/compiler/parser.d.ts +88 -0
  179. package/dist/native/compiler/parser.js +753 -0
  180. package/dist/native/compiler/render-screen.d.ts +26 -0
  181. package/dist/native/compiler/render-screen.js +31 -0
  182. package/dist/native/components/primitives.d.ts +291 -0
  183. package/dist/native/components/primitives.js +22 -0
  184. package/dist/native/hot-reload/client.d.ts +62 -0
  185. package/dist/native/hot-reload/client.js +324 -0
  186. package/dist/native/index.d.ts +90 -0
  187. package/dist/native/index.js +34 -0
  188. package/dist/native/primitives/ActivityIndicator.stx +5 -0
  189. package/dist/native/primitives/Button.stx +5 -0
  190. package/dist/native/primitives/DatePicker.stx +5 -0
  191. package/dist/native/primitives/FlatList.stx +5 -0
  192. package/dist/native/primitives/Image.stx +5 -0
  193. package/dist/native/primitives/ImageBackground.stx +5 -0
  194. package/dist/native/primitives/KeyboardAvoidingView.stx +5 -0
  195. package/dist/native/primitives/Modal.stx +5 -0
  196. package/dist/native/primitives/Picker.stx +5 -0
  197. package/dist/native/primitives/Pressable.stx +5 -0
  198. package/dist/native/primitives/RefreshControl.stx +5 -0
  199. package/dist/native/primitives/SafeAreaView.stx +5 -0
  200. package/dist/native/primitives/ScrollView.stx +5 -0
  201. package/dist/native/primitives/SectionList.stx +5 -0
  202. package/dist/native/primitives/Slider.stx +5 -0
  203. package/dist/native/primitives/StatusBar.stx +5 -0
  204. package/dist/native/primitives/Switch.stx +5 -0
  205. package/dist/native/primitives/Text.stx +5 -0
  206. package/dist/native/primitives/TextInput.stx +5 -0
  207. package/dist/native/primitives/TouchableHighlight.stx +5 -0
  208. package/dist/native/primitives/TouchableOpacity.stx +5 -0
  209. package/dist/native/primitives/View.stx +5 -0
  210. package/dist/native/runtime/craft.d.ts +75 -0
  211. package/dist/native/runtime/craft.js +0 -0
  212. package/dist/native/runtime/entry.d.ts +1 -0
  213. package/dist/native/runtime/entry.js +3 -0
  214. package/dist/native/runtime/index.d.ts +45 -0
  215. package/dist/native/runtime/index.js +165 -0
  216. package/dist/native/runtime/native-host.d.ts +33 -0
  217. package/dist/native/runtime/native-host.js +184 -0
  218. package/dist/native/runtime/screen.d.ts +43 -0
  219. package/dist/native/runtime/screen.js +808 -0
  220. package/dist/pwa/service-worker.js +1 -1
  221. package/dist/pwa/workbox.js +1 -1
  222. package/dist/pwa.js +8 -8
  223. package/dist/site-url.d.ts +1 -1
  224. package/dist/ssg.js +53 -53
  225. package/dist/visual-testing.js +42 -42
  226. package/dist/web-components/reactive-generator.js +2 -2
  227. package/package.json +9 -5
  228. package/dist/chunk-00g9x6w2.js +0 -2
  229. package/dist/chunk-04tgatyy.js +0 -2
  230. package/dist/chunk-097jnwd5.js +0 -2
  231. package/dist/chunk-0btmm4m2.js +0 -147
  232. package/dist/chunk-0c2h69k2.js +0 -4
  233. package/dist/chunk-0pkk226n.js +0 -2
  234. package/dist/chunk-0we9nw1d.js +0 -3
  235. package/dist/chunk-0y46fbkx.js +0 -3
  236. package/dist/chunk-18n1ftn0.js +0 -33
  237. package/dist/chunk-1a0v39k5.js +0 -3
  238. package/dist/chunk-1fs9jvpb.js +0 -2
  239. package/dist/chunk-1qq26zt0.js +0 -2
  240. package/dist/chunk-1te8k8gp.js +0 -3
  241. package/dist/chunk-1ws3xcea.js +0 -1199
  242. package/dist/chunk-213jwgpx.js +0 -3
  243. package/dist/chunk-24w86pek.js +0 -32
  244. package/dist/chunk-27fgag95.js +0 -4
  245. package/dist/chunk-2fw05hs2.js +0 -3
  246. package/dist/chunk-2tbez006.js +0 -2
  247. package/dist/chunk-38wvkv3s.js +0 -2
  248. package/dist/chunk-3rkejwjp.js +0 -2
  249. package/dist/chunk-3t65wb35.js +0 -2
  250. package/dist/chunk-3w6z6tw9.js +0 -2
  251. package/dist/chunk-4q1c6fw2.js +0 -7
  252. package/dist/chunk-50pszj17.js +0 -2
  253. package/dist/chunk-563shnkz.js +0 -3
  254. package/dist/chunk-5h104qh1.js +0 -2
  255. package/dist/chunk-5qjk7drw.js +0 -20
  256. package/dist/chunk-603x5gb2.js +0 -2
  257. package/dist/chunk-6kd5jjwc.js +0 -2
  258. package/dist/chunk-6kdrncsx.js +0 -30
  259. package/dist/chunk-6zggmce7.js +0 -4422
  260. package/dist/chunk-72rwcbp6.js +0 -3
  261. package/dist/chunk-76w34xne.js +0 -3
  262. package/dist/chunk-7dmgt8at.js +0 -2
  263. package/dist/chunk-82pd4b5w.js +0 -2
  264. package/dist/chunk-8d7nf67s.js +0 -2
  265. package/dist/chunk-8w2mqdnv.js +0 -2
  266. package/dist/chunk-90b2vt2n.js +0 -2
  267. package/dist/chunk-9e8t0twa.js +0 -3
  268. package/dist/chunk-9fqp72ze.js +0 -5
  269. package/dist/chunk-9xew0kgf.js +0 -2
  270. package/dist/chunk-a7bnvz91.js +0 -24
  271. package/dist/chunk-akwd34xt.js +0 -29
  272. package/dist/chunk-anydpa34.js +0 -3
  273. package/dist/chunk-aq1xq0r4.js +0 -16
  274. package/dist/chunk-bbt3tp6f.js +0 -499
  275. package/dist/chunk-bn1edb1y.js +0 -47
  276. package/dist/chunk-btd7ds3x.js +0 -2
  277. package/dist/chunk-c4511wng.js +0 -2
  278. package/dist/chunk-c4h579e3.js +0 -2
  279. package/dist/chunk-cj3adc77.js +0 -5
  280. package/dist/chunk-cs54ek9m.js +0 -6
  281. package/dist/chunk-ct1jwd4r.js +0 -2
  282. package/dist/chunk-cxrgxzxc.js +0 -2
  283. package/dist/chunk-de8t7sc9.js +0 -17
  284. package/dist/chunk-fcnrgxck.js +0 -2
  285. package/dist/chunk-fqzcft9d.js +0 -2
  286. package/dist/chunk-gbmeh7jg.js +0 -3
  287. package/dist/chunk-gc06g35w.js +0 -2
  288. package/dist/chunk-gs18069g.js +0 -194
  289. package/dist/chunk-gvbf1mhs.js +0 -930
  290. package/dist/chunk-h564hgzt.js +0 -2
  291. package/dist/chunk-h83jrhfq.js +0 -3
  292. package/dist/chunk-hj4vpyhp.js +0 -2
  293. package/dist/chunk-hrkvsj5c.js +0 -11
  294. package/dist/chunk-hyr4ag1k.js +0 -2
  295. package/dist/chunk-jxvmf02k.js +0 -2
  296. package/dist/chunk-k5ptvy0b.js +0 -4
  297. package/dist/chunk-k80sn8d1.js +0 -2
  298. package/dist/chunk-k8t2cmyd.js +0 -2
  299. package/dist/chunk-kmsyvaex.js +0 -8
  300. package/dist/chunk-kq4b6cwj.js +0 -2
  301. package/dist/chunk-kvmx7dnb.js +0 -2
  302. package/dist/chunk-kxc2h5vn.js +0 -5
  303. package/dist/chunk-mbxehgrq.js +0 -2
  304. package/dist/chunk-mgnq5de2.js +0 -2
  305. package/dist/chunk-mgrckqww.js +0 -2
  306. package/dist/chunk-mq5ewmz6.js +0 -2
  307. package/dist/chunk-mrahwn5v.js +0 -8
  308. package/dist/chunk-n2swas11.js +0 -3
  309. package/dist/chunk-n4299xgy.js +0 -2
  310. package/dist/chunk-naw4jt7j.js +0 -2
  311. package/dist/chunk-ny67c03k.js +0 -3
  312. package/dist/chunk-p4jb9v0w.js +0 -2
  313. package/dist/chunk-p4zrvt5f.js +0 -14
  314. package/dist/chunk-p5wp0ce6.js +0 -43
  315. package/dist/chunk-pcxp4r9n.js +0 -3
  316. package/dist/chunk-pjrn29gg.js +0 -2
  317. package/dist/chunk-prxwsp7n.js +0 -2
  318. package/dist/chunk-py2r6wtv.js +0 -2
  319. package/dist/chunk-q738pwv6.js +0 -2
  320. package/dist/chunk-q9n5swx7.js +0 -3
  321. package/dist/chunk-qmmp5kb5.js +0 -2
  322. package/dist/chunk-qqpqgwvb.js +0 -30
  323. package/dist/chunk-rcv2ehpq.js +0 -18
  324. package/dist/chunk-rq414kn5.js +0 -3
  325. package/dist/chunk-rz9f3zqz.js +0 -7
  326. package/dist/chunk-s6g8wksg.js +0 -2
  327. package/dist/chunk-s8jd13nb.js +0 -3
  328. package/dist/chunk-spxsw4mp.js +0 -2
  329. package/dist/chunk-strcy64y.js +0 -2
  330. package/dist/chunk-t1htzg9e.js +0 -4
  331. package/dist/chunk-t1tdjjht.js +0 -216
  332. package/dist/chunk-tat1cjec.js +0 -2
  333. package/dist/chunk-td08rnk3.js +0 -3
  334. package/dist/chunk-tgadbsd4.js +0 -2
  335. package/dist/chunk-tgrpp58r.js +0 -2
  336. package/dist/chunk-tkyrk66a.js +0 -3
  337. package/dist/chunk-tp8pzf94.js +0 -3
  338. package/dist/chunk-twz64kvy.js +0 -2
  339. package/dist/chunk-v3nwkveg.js +0 -12
  340. package/dist/chunk-vsbmc9kt.js +0 -2
  341. package/dist/chunk-vzgzaw66.js +0 -12
  342. package/dist/chunk-wc66mcn4.js +0 -4367
  343. package/dist/chunk-wkanrfb3.js +0 -2
  344. package/dist/chunk-x8f6wqxd.js +0 -2
  345. package/dist/chunk-xsng1mtq.js +0 -3
  346. package/dist/chunk-xwts5yky.js +0 -4
  347. package/dist/chunk-z5rwnnk1.js +0 -3
  348. package/dist/chunk-zcz9rs6p.js +0 -3
  349. package/dist/chunk-zpcnbdhn.js +0 -64
  350. package/dist/chunk-zq4ssxj9.js +0 -8
@@ -0,0 +1,2033 @@
1
+ // @bun
2
+ import{h,je,wt,Be,Fe,ee,M,le,X,d,ve,Ji,ds,r,n,K,Kn,i,T,ue}from"./chunk-69mc2np8.js";import{J,fn,re,_,At}from"./chunk-z0g9jvv0.js";import{H,e,Tt,ln,f}from"./chunk-h0atqq82.js";import{yn,ar,cr,lr,Qe,et,tt,nt,rt,st,Ce}from"./chunk-czxt605c.js";import{Pe,ni,se,C,ri,Sr,En,me,si,ie}from"./chunk-scezfp0w.js";import{Zt,Qt}from"./chunk-pqxzp1bb.js";import{Ot}from"./chunk-x72tv2cg.js";import{Me}from"./chunk-mepdnezf.js";import{o}from"./chunk-fzapbw9p.js";import{O}from"./chunk-px7fvbj6.js";async function Xn(t){try{let s=await Bun.file(t).text(),a=Gn(s),p=Jn(s,t),c=Yn(s,a),l=Qn(s,a);return{file:t,metrics:a,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Gn(t){let s=t.split(`
3
+ `),a=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(a?a[1]:"").split(`
4
+ `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,E=0;for(let R of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(R)&&!/@end/.test(R)&&!/@else/.test(R))E++,S=Math.max(S,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(R))E--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+b*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:c,complexity:x}}function Jn(t,s){let a=[],p=Xt(t,"if","endif");if(p>0)a.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Xt(t,"foreach","endforeach");if(c>0)a.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)a.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)a.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)a.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
+ `).filter((b)=>b.length>120);if(y.length>0)a.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)a.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return a}function Yn(t,s){let a=[];if(s.complexity>7)a.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)a.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)a.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)a.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)a.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)a.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)a.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return a}function Qn(t,s){let a=1;if(a+=s.directives.conditionals*0.1,a+=s.directives.loops*0.5,a+=s.directives.includes*2,a+=s.expressions*0.05,a+=s.components*1,s.scriptLines>10)a+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(a>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(a*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Xt(t,s,a){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${a}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Hs(t=["**/*.stx"],s){let a=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await Xn(l);a.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=Zn(a);return{results:a,summary:c}}function Zn(t){let s=t.length,a=t.reduce((g,b)=>g+b.metrics.lines,0),p=s>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/s:0,c=t.reduce((g,b)=>g+b.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let m=s>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:a,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as er,readFile as tr,readdir as nr,stat as Gt,writeFile as rr}from"fs/promises";import Ee from"path";function rn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var sn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Bt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function or(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ir(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function dr(t){let s=[];async function a(p){let c=await nr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await a(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await a(t),s}function pr(t,s){let a=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!a)return{};let p=a[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function ur(t,s){let a={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(y){throw Error(`${s}: failed to transpile <script client> (${y.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let y=u[1];if(sn.has(y))throw Error(`${s}: client ${rn(y)}`);let g=m.lastIndex,b=1,w="",S=!1,E=g;for(;E<l.length&&b>0;E++){let x=l[E];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${s}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";a[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return a}function fr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
6
+
7
+ `)}function yr(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function br(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function xr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function vr(t){let s=[],a=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(y)=>{if(p[y]!=="(")return null;let g=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let g=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>g)s.push(`out += ${JSON.stringify(y.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<y.length)s.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=c.exec(p)){u(p.slice(a,l.index)),a=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(a):null;if(g)a=g.end,c.lastIndex=g.end;let b=g?.expression;switch(l[1]){case"if":s.push(`if (${b}) {`);break;case"elseif":s.push(`} else if (${b}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${b})`:""))};`);break}let[,S,E,v]=w;s.push(E?`for (const [${E}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(a)),s.join(`
8
+ `)}function yt(t,s,a,p){if(t[s]!==a)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===a)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function jt(t,s,a){let p=a?"([{<":"([{",c=a?")]}>":")]}",l=[],m=0,u=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))m++;else if(c.includes(b))m--;if(m===0&&s.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function wr(t){let s=0,a=null;for(let p=0;p<t.length;p++){let c=t[p];if(a){if(c==="\\"){p++;continue}if(c===a)a=null;continue}if(c==="'"||c==='"'||c==="`"){a=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function Yt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function kr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let a=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=a.exec(t);k&&k.index<s.index;k=a.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=yt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let E="";if(y(),t[u]==="<"){let k=yt(t,u,"<",">");if(k===-1)return null;E=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=yt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=yt(t,u,"{","}");if(k===-1)return null;for(let[F,L]of Ht(t.slice(u,k)))l[F]=L;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let R=/^[A-Za-z_$][\w$]*$/.test(E)?E:void 0;if(E.startsWith("{"))for(let k of jt(E.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let F=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(F)c[F[1]]=F[2].trim()}if(x.startsWith("{"))for(let[k,F]of Ht(x)){if(m.push(k),!F.startsWith("{")){let L=Yt(F);if(L)c[k]=L;continue}for(let[L,j]of Ht(F))if(L==="default")l[k]=j;else if(L==="type"){let P=Yt(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of jt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of jt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let F=wr(k),j=(F===-1?k:k.slice(0,F)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),F!==-1)l[j]=k.slice(F+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:R}}function Ht(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),a=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",y=p;while(p<s.length){let b=s[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")m++;else if(b==="}"||b==="]"||b===")")m--;else if(b===","&&m===0)break;p++}let g=s.slice(y,p).trim();if(g)a.push([l[1],g]);p++}return a}function Tr(t,s,a){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],y={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(E,v,x,R)=>{let k=Ee.resolve(Ee.dirname(s),x),F=Ee.relative(a,k);return`${v}${F.startsWith(".")?F:`./${F}`}${R}`})),""});let b=kr(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(g,b.declared),l=l.replace(b.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let E=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),E.push(v[1]);w[S[1]]=E}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:y,declared:g}}function $r(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let y=c.toLowerCase();s.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Cr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Rr(t){let s=new Set;for(let a of t.matchAll(/<slot\b([^>]*)>/gi))s.add(a[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((a)=>({name:a}))}function Er(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function Pr(t,s,a){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await tr(p,"utf8"),l=pr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||sr(m),y=`${Bt(a.prefix||"stx")}-${Bt(m)}`,g=s.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!or(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([L,j])=>[L,en(L,j)])),S=$r(fr(c)),E=Cr(S.template),v=Tr(c,p,Ee.resolve(a.outputDir)),x=vr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=en(L,{type:yr(v.declared[L])??br(j),...j===void 0?{}:{default:xr(j)}})}let R=l.methods||{},k=s.methods||{},F=ur(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:Jt(c),shadowMode:ir(s.shadowDOM??l.shadowDOM??a.shadowDOM),progressive:s.progressive??l.progressive??a.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...R,...k,...F},eventTypes:S.eventTypes,bindings:E.bindings,slots:Rr(E.template),cssProperties:Er(Jt(c)),scope:v,render:x}}function Ar(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
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);
66
+ }
67
+ if (definition.shadowMode && this.attachShadow && !this.shadowRoot) {
68
+ this._closedRoot = this.attachShadow({ mode: definition.shadowMode });
69
+ }
70
+ }
71
+
72
+ get updateComplete() { return this._updateComplete || Promise.resolve(); }
73
+ get renderRoot() { return this._closedRoot || this.shadowRoot || this; }
74
+
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 }));
99
+ }
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
+
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();
117
+ }
118
+ }
119
+
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();
130
+ }
131
+ }
132
+
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
+ }
143
+
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
+ }
156
+
157
+ emit(name, detail, options = {}) {
158
+ return this.dispatchEvent(new CustomEvent(name, {
159
+ detail, bubbles: true, composed: true, ...options,
160
+ }));
161
+ }
162
+
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
+ }
169
+
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 Or(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),a=Object.entries(t.methods).map(([u,y])=>{if(sn.has(u))throw Error(`${t.sourcePath}: ${rn(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
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
+ ${a}${m}
327
+ }
328
+
329
+ defineComponent(${t.name}, ${s});
330
+ export default ${t.name};
331
+ `}function bt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Dr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${bt(m)}`).join(`
332
+ `),a=Object.entries(t.properties).map(([l,m])=>` ${l}: ${bt(m)}`).join(`
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
+ ${a}
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 Mr(t){return`declare global {
359
+ namespace JSX {
360
+ interface IntrinsicElements {
361
+ ${t.map((a)=>{let p=Object.entries(a.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${bt(m)}`).join(`
362
+ `),c=Object.keys(a.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${a.events[l].detailType||"unknown"}>) => void`).join(`
363
+ `);return` ${JSON.stringify(a.tag)}: {
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 _r(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([a,p])=>({kind:"field",name:a,description:p.description,type:{text:bt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Bt(a),reflects:p.reflect})),events:Object.entries(s.events).map(([a,p])=>({name:a,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
378
+ ${s}
379
+ }`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Lr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),a=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
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(${a}, '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 Vs(t){let s=Ee.resolve(t.inputDir),a=Ee.resolve(t.outputDir);if(!(await Gt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await dr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Pr(s,x,t)));l.sort((x,R)=>x.tag.localeCompare(R.tag));let m=l.filter((x,R)=>l.findIndex((k)=>k.tag===x.tag)!==R);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,R)=>l.findIndex((k)=>k.name===x.name)!==R);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await er(a,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(a,x);return await rr(k,R.endsWith(`
414
+ `)?R:`${R}
415
+ `,"utf8"),y.push(k),k};await g("runtime.js",Ar());for(let x of l){if(await g(`${x.tag}.js`,Or(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Dr(x));if(t.css!==!1&&x.styles){let R=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(R):R)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
416
+ `);if(await g("index.js",b),await g("ssr.js",Lr(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
417
+ `)),await g("custom-elements.d.ts",Mr(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
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(_r(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(tn).join(`
422
+
423
+ `);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(a,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(a,"index.js")],outdir:a,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(R){let k=R instanceof AggregateError?R.errors:[R],F=k.map((L)=>String(L).trim()).filter(Boolean).join(`
424
+ `);throw AggregateError(k,`Failed to bundle component library${F?`
425
+ ${F}`:""}`)}if(!x.success){let R=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
426
+ `);throw AggregateError(x.logs,`Failed to bundle component library${R?`
427
+ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await Gt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(a,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}var{serve:Wr}=globalThis.Bun;import zt from"fs";import dt from"path";function xt(){return`
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 vt(t){return`
478
+ <div class="theme-selector">
479
+ Theme:
480
+ <select id="themeSelector" onchange="changeTheme()">
481
+ ${t}
482
+ </select>
483
+ </div>`}function St(){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');
495
+ }
496
+ }
497
+
498
+ // Initialize theme on page load
499
+ document.addEventListener('DOMContentLoaded', changeTheme);`}function kt(t){if(Object.keys(t).length===0)return"";return`
500
+ <div class="frontmatter">
501
+ <h3>Frontmatter</h3>
502
+ ${Object.entries(t).map(([s,a])=>`
503
+ <div class="frontmatter-item">
504
+ <span class="frontmatter-label">${s}:</span>
505
+ <span>${Array.isArray(a)?a.join(", "):String(a)}</span>
506
+ </div>`).join("")}
507
+ </div>`}import on from"net";async function Ir(t){return new Promise((s)=>{let a=on.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"0.0.0.0")})}async function jr(t){return new Promise((s)=>{let a=on.createServer();a.once("error",()=>s(!1)),a.once("listening",()=>{a.close(()=>s(!0))}),a.listen(t,"::")})}async function Hr(t){if(!await Ir(t))return!1;return await jr(t)}async function Ye(t,s=20){t=Number(t);for(let a=0;a<s;a++){let p=t+a;if(await Hr(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Br={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Fr(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function lt(t,s={}){let a={...Br,...s},p=await Fr();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:a.title,width:a.width,height:a.height,darkMode:a.darkMode,hotReload:a.hotReload,titlebarHidden:a.titlebarHidden,nativeSidebar:a.nativeSidebar,sidebarWidth:a.sidebarWidth,sidebarConfig:a.sidebarConfig});if(c&&a.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function $t(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
508
+ ${l}
509
+ return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
510
+ `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let a=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(a)try{return JSON.parse(a[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ft(){console.log(`
511
+ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function zr(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ft()}function Nr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ze(t,s,a){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ft();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(a?.onQuit)a.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
512
+ `)){let l=p.trim().toLowerCase();p="",Ur(l,t,s,a)}})}function Ur(t,s,a,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Nr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),zr(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),a(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ft();break;default:break}}async function Nt(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=dt.resolve(t);if(!zt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await ue(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),E=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,v=E?.defaultTheme||"github-dark",x=["github-dark"],R=E?.additionalThemes||[],F=[...new Set([...x,...R])].map((L)=>`<option value="${L}"${L===v?" selected":""}>${L}</option>`).join(`
513
+ `);return l=`
514
+ <!DOCTYPE html>
515
+ <html lang="en">
516
+ <head>
517
+ <meta charset="UTF-8">
518
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
519
+ <title>${Vr(S.title||dt.basename(c))}</title>
520
+ <!-- Syntax highlighting styles -->
521
+ <style id="syntax-theme">
522
+ :root {
523
+ --shiki-color-text: #24292e;
524
+ --shiki-color-background: #ffffff;
525
+ --shiki-token-constant: #005cc5;
526
+ --shiki-token-string: #032f62;
527
+ --shiki-token-comment: #6a737d;
528
+ --shiki-token-keyword: #d73a49;
529
+ --shiki-token-parameter: #24292e;
530
+ --shiki-token-function: #6f42c1;
531
+ --shiki-token-string-expression: #032f62;
532
+ --shiki-token-punctuation: #24292e;
533
+ --shiki-token-link: #032f62;
534
+ }
535
+ pre {
536
+ background-color: var(--shiki-color-background);
537
+ padding: 1rem;
538
+ border-radius: 4px;
539
+ }
540
+ code {
541
+ color: var(--shiki-color-text);
542
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
543
+ }
544
+ .dark-mode {
545
+ --shiki-color-text: #e1e4e8;
546
+ --shiki-color-background: #24292e;
547
+ --shiki-token-constant: #79b8ff;
548
+ --shiki-token-string: #9ecbff;
549
+ --shiki-token-comment: #6a737d;
550
+ --shiki-token-keyword: #f97583;
551
+ --shiki-token-parameter: #e1e4e8;
552
+ --shiki-token-function: #b392f0;
553
+ --shiki-token-string-expression: #9ecbff;
554
+ --shiki-token-punctuation: #e1e4e8;
555
+ --shiki-token-link: #9ecbff;
556
+ }
557
+ </style>
558
+ <style>
559
+ body {
560
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
561
+ line-height: 1.6;
562
+ color: #333;
563
+ max-width: 800px;
564
+ margin: 0 auto;
565
+ padding: 2rem;
566
+ }
567
+ pre, code {
568
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
569
+ }
570
+ pre {
571
+ border-radius: 4px;
572
+ padding: 0;
573
+ margin: 1.5rem 0;
574
+ overflow-x: auto;
575
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
576
+ }
577
+ pre code {
578
+ display: block;
579
+ padding: 1rem;
580
+ overflow-x: auto;
581
+ }
582
+ /* Apply background color to code blocks based on theme */
583
+ pre.syntax-highlighter {
584
+ background-color: var(--shiki-color-background) !important;
585
+ }
586
+ .dark-mode pre.syntax-highlighter {
587
+ background-color: var(--shiki-color-background) !important;
588
+ }
589
+ code {
590
+ padding: 0.2rem 0.4rem;
591
+ border-radius: 3px;
592
+ }
593
+ h1, h2, h3, h4 {
594
+ margin-top: 2rem;
595
+ margin-bottom: 1rem;
596
+ }
597
+ h1 { color: #111; border-bottom: 1px solid #eee; padding-bottom: 0.5rem; }
598
+ h2 { color: #333; border-bottom: 1px solid #f0f0f0; padding-bottom: 0.3rem; }
599
+ h3 { color: #444; }
600
+ img {
601
+ max-width: 100%;
602
+ border-radius: 4px;
603
+ margin: 1rem 0;
604
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
605
+ }
606
+ blockquote {
607
+ border-left: 4px solid #ddd;
608
+ padding-left: 1rem;
609
+ margin-left: 0;
610
+ color: #555;
611
+ background: #f9f9f9;
612
+ padding: 0.5rem 1rem;
613
+ margin: 1.5rem 0;
614
+ }
615
+ table {
616
+ border-collapse: collapse;
617
+ width: 100%;
618
+ margin: 1.5rem 0;
619
+ }
620
+ th, td {
621
+ border: 1px solid #ddd;
622
+ padding: 0.5rem;
623
+ }
624
+ th {
625
+ background: #f0f0f0;
626
+ text-align: left;
627
+ }
628
+ tr:nth-child(even) {
629
+ background-color: #f8f8f8;
630
+ }
631
+ a {
632
+ color: #0066cc;
633
+ text-decoration: none;
634
+ }
635
+ a:hover {
636
+ text-decoration: underline;
637
+ }
638
+ hr {
639
+ border: 0;
640
+ border-top: 1px solid #eee;
641
+ margin: 2rem 0;
642
+ }
643
+ .frontmatter {
644
+ background: #f8f8f8;
645
+ border-radius: 4px;
646
+ padding: 1.5rem;
647
+ margin-bottom: 2rem;
648
+ font-size: 0.9rem;
649
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
650
+ border-left: 4px solid #ddd;
651
+ }
652
+ .frontmatter-item {
653
+ margin-bottom: 0.5rem;
654
+ display: flex;
655
+ }
656
+ .frontmatter-label {
657
+ font-weight: bold;
658
+ min-width: 100px;
659
+ color: #555;
660
+ }
661
+ ${xt()}
662
+ </style>
663
+ </head>
664
+ <body>
665
+ ${kt(S)}
666
+ ${vt(F)}
667
+
668
+ ${w}
669
+
670
+ <script>
671
+ ${St()}
672
+ </script>
673
+ </body>
674
+ </html>
675
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let y=a;try{if(y=await Ye(a),y!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let g=Wr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
676
+ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
677
+ ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
678
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
679
+ ${e.yellow}Routes:${e.reset}`);let b=dt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${b}${e.reset}`),console.log(`
680
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(g.url.toString(),()=>{if(p)zt.watch(dt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await lt(y,{title:dt.basename(c,".md")});if(p){let w=dt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=zt.watch(w,{recursive:!0},async(E,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function Vr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Kr}=globalThis.Bun;import Ne from"fs";import we from"path";class an{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,a=20;for(let p=0;p<a;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${a} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),a=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),a++}catch{this.clients.delete(p)}if(this.options.verbose&&a>0)console.log(`[HMR] Broadcast ${t.type} to ${a} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function qr(t,s={}){let{showOverlay:a=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
681
+ <script>
682
+ (function() {
683
+ // stx Hot Reload Client
684
+ var wsUrl = 'ws://' + window.location.hostname + ':${t}';
685
+ var reconnectAttempts = 0;
686
+ var maxAttempts = ${c};
687
+ var reconnectInterval = ${p};
688
+ var socket = null;
689
+ var overlay = null;
690
+ var wasConnected = false; // Track if we ever connected successfully
691
+
692
+ ${a?`
693
+ // Create connection status overlay
694
+ function createOverlay() {
695
+ overlay = document.createElement('div');
696
+ overlay.id = 'stx-hmr-overlay';
697
+ overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;padding:8px 16px;background:#f59e0b;color:#000;font-family:system-ui,sans-serif;font-size:14px;text-align:center;z-index:999999;display:none;';
698
+ document.body.appendChild(overlay);
699
+ }
700
+
701
+ function showOverlay(message, isError) {
702
+ // Only show overlay if we were previously connected (don't show during initial connection)
703
+ if (!wasConnected && !isError) return;
704
+ if (!overlay) createOverlay();
705
+ overlay.textContent = message;
706
+ overlay.style.background = isError ? '#ef4444' : '#f59e0b';
707
+ overlay.style.color = isError ? '#fff' : '#000';
708
+ overlay.style.display = 'block';
709
+ }
710
+
711
+ function hideOverlay() {
712
+ if (overlay) overlay.style.display = 'none';
713
+ }
714
+ `:`
715
+ function showOverlay() {}
716
+ function hideOverlay() {}
717
+ `}
718
+
719
+ function connect() {
720
+ try {
721
+ socket = new WebSocket(wsUrl);
722
+ }
723
+ catch (e) {
724
+ // Silent fail for initial connection attempts
725
+ if (wasConnected) {
726
+ scheduleReconnect();
727
+ }
728
+ return;
729
+ }
730
+
731
+ socket.onopen = function() {
732
+ // connected silently
733
+ wasConnected = true;
734
+ reconnectAttempts = 0;
735
+ hideOverlay();
736
+ };
737
+
738
+ socket.onmessage = function(event) {
739
+ try {
740
+ var msg = JSON.parse(event.data);
741
+
742
+ switch (msg.type) {
743
+ case 'reload':
744
+ console.log('[stx] Reloading...', msg.path || '');
745
+ // Use SPA router for progressive update instead of full page reload.
746
+ // Falls back to hard reload only when the router isn't available.
747
+ // Call the ROUTER directly, not window.navigate: the runtime helper
748
+ // takes (url, options) and silently dropped the third argument, so
749
+ // force never arrived and the same-URL early return made this a
750
+ // no-op on every page that had the router (#1807). pushState=false
751
+ // keeps the address bar untouched (this is a reload, not a
752
+ // navigation) and force=true bypasses the early return.
753
+ if (window.stxRouter && typeof window.stxRouter.navigate === 'function') {
754
+ window.stxRouter.navigate(window.location.pathname + window.location.search, false, true);
755
+ } else {
756
+ window.location.reload();
757
+ }
758
+ break;
759
+
760
+ case 'css-update':
761
+ console.log('[stx] CSS update:', msg.path);
762
+ updateCss(msg.path, msg.content);
763
+ break;
764
+
765
+ case 'error':
766
+ console.error('[stx] Error:', msg.content);
767
+ showOverlay('Build Error: ' + msg.content, true);
768
+ break;
769
+
770
+ case 'connected':
771
+ break;
772
+ }
773
+ }
774
+ catch (e) {
775
+ console.error('[stx] Invalid message:', e);
776
+ }
777
+ };
778
+
779
+ socket.onclose = function() {
780
+ socket = null;
781
+ // Only log and show overlay if we were previously connected
782
+ if (wasConnected) {
783
+ console.log('[stx] Connection closed, reconnecting...');
784
+ scheduleReconnect();
785
+ }
786
+ else {
787
+ // Silently retry initial connection
788
+ setTimeout(connect, reconnectInterval);
789
+ }
790
+ };
791
+
792
+ socket.onerror = function() {
793
+ // Errors are handled in onclose
794
+ };
795
+ }
796
+
797
+ function scheduleReconnect() {
798
+ if (reconnectAttempts < maxAttempts) {
799
+ reconnectAttempts++;
800
+ showOverlay('Reconnecting... (' + reconnectAttempts + '/' + maxAttempts + ')');
801
+ setTimeout(connect, reconnectInterval);
802
+ }
803
+ else {
804
+ showOverlay('Connection lost. Refresh to reconnect.', true);
805
+ }
806
+ }
807
+
808
+ // CSS hot update without full reload
809
+ function updateCss(path, content) {
810
+ // Try to find and update existing stylesheet
811
+ var links = document.querySelectorAll('link[rel="stylesheet"]');
812
+ for (var i = 0; i < links.length; i++) {
813
+ var href = links[i].getAttribute('href');
814
+ if (href && href.indexOf(path) !== -1) {
815
+ // Add cache-busting query param
816
+ var newHref = href.split('?')[0] + '?t=' + Date.now();
817
+ links[i].setAttribute('href', newHref);
818
+ return;
819
+ }
820
+ }
821
+
822
+ // If content provided, inject as style tag
823
+ if (content) {
824
+ var style = document.createElement('style');
825
+ style.setAttribute('data-stx-hmr', path);
826
+ style.textContent = content;
827
+
828
+ // Remove old injected style
829
+ var old = document.querySelector('style[data-stx-hmr="' + path + '"]');
830
+ if (old) old.remove();
831
+
832
+ document.head.appendChild(style);
833
+ }
834
+ }
835
+
836
+ // Start connection when DOM is ready
837
+ if (document.readyState === 'loading') {
838
+ document.addEventListener('DOMContentLoaded', connect);
839
+ }
840
+ else {
841
+ connect();
842
+ }
843
+
844
+ // Forward browser console to the dev server terminal
845
+ var _origLog = console.log;
846
+ var _origError = console.error;
847
+ var _origWarn = console.warn;
848
+ var _origInfo = console.info;
849
+
850
+ function _fwd(level, args) {
851
+ if (socket && socket.readyState === 1) {
852
+ try {
853
+ socket.send(JSON.stringify({
854
+ type: 'console',
855
+ level: level,
856
+ args: Array.prototype.slice.call(args).map(function(a) {
857
+ if (a === null) return 'null';
858
+ if (a === undefined) return 'undefined';
859
+ if (typeof a === 'object') { try { return JSON.stringify(a); } catch(e) { return String(a); } }
860
+ return String(a);
861
+ })
862
+ }));
863
+ } catch(e) {}
864
+ }
865
+ }
866
+
867
+ console.log = function() { _origLog.apply(console, arguments); _fwd('log', arguments); };
868
+ console.error = function() { _origError.apply(console, arguments); _fwd('error', arguments); };
869
+ console.warn = function() { _origWarn.apply(console, arguments); _fwd('warn', arguments); };
870
+ console.info = function() { _origInfo.apply(console, arguments); _fwd('info', arguments); };
871
+
872
+ // Expose for debugging
873
+ window.__stxHmr = {
874
+ reconnect: connect,
875
+ status: function() { return socket ? socket.readyState : -1; }
876
+ };
877
+ })();
878
+ </script>
879
+ `}function Xe(t,s,a={}){let p=qr(s,a),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function Ct(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Rt(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Et(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((a)=>a.test(t))}var pt=null;function Pt(t){if(!pt)pt=new an(t);return pt}function gt(){if(pt)pt.stop(),pt=null}import Dt from"path";var ut={name:"bun-plugin-stx",async setup(t){let a={...await i(),...t.config?.stx},p=new Set,c=a.webComponents?.enabled?`./${Dt.relative(Dt.dirname(t.config?.outdir||"dist"),a.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(a.webComponents?.enabled)try{let m=await Kn(a,p);if(l.push(...m),a.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(a.cache&&a.cachePath){let x=await Zt(m,a);if(x){if(a.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await re(()=>Bun.file(m).text(),"",(x)=>{throw new fn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=H.time("script-extraction",()=>{let x=y,R=ee(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],F="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",z=P.match(/<script\b([^>]*)>/i),G=z?z[1]:"";if(/\bserver\b/i.test(G))F=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:F,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:Dt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await re(()=>d(g,S,m),void 0,(x)=>{let R=new J(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),a.debug)throw R});let v=await H.timeAsync("directive-processing",async()=>await r(b,S,m,a,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-mhq0pjws.js"),R=x(w.join(`
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 X(v),u.forEach((x)=>p.add(x)),a.cache&&a.cachePath){if(await Qt(m,v,u,a),a.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new J(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),At.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),a.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:a.debug||O()?`<!DOCTYPE html>
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>
902
+
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>
910
+
911
+ ${y.stack?`
912
+ <div class="error-details">
913
+ <h3>Stack Trace</h3>
914
+ <pre class="error-code">${h(y.stack)}</pre>
915
+ </div>`:""}
916
+
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(Dt.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 wn(t,s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=we.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Nt(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=o(process.cwd(),"output");Ne.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let I={name:"public-assets",setup(Te){Te.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},z=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ut],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return console.error(`${e.red}Build failed:${e.reset}`,z.logs),!1;let G=z.outputs.find((Te)=>Te.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=we.dirname(u);await Tt(S);let E=a;try{if(E=await Ye(a),E!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||E+1;l=Pt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-48bwk47q.js"),z=await I();if(R=s.stxOptions?.serverApi??z.serverApi,z?.apiRouter)x=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){v=z.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:te}=await import("./chunk-dgdm3hy3.js"),Te=z.broadcasting;await G(Te);let he=Te.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=we.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let ae=await te(Oe);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:F}=await import("./chunk-5g3y8kym.js"),L=await k(process.cwd(),R);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Kr({port:E,async fetch(I){return Ot(I,await(async()=>{let z=new URL(I.url);if([y,we.dirname(u),we.join(process.cwd(),"public")].some((ae)=>F(we.join(ae,z.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(I);if(ae.status!==404)return ae}catch{}if(v[z.pathname])try{return await v[z.pathname](I)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(z.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let te=we.join(y,z.pathname);if(Ne.existsSync(te)&&Ne.statSync(te).isFile()){let ae=Bun.file(te),W=we.extname(te).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Te=we.dirname(u),he=we.join(Te,z.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let ae=Bun.file(he),W=we.extname(he).toLowerCase(),B="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}let Oe=we.join(process.cwd(),"public",z.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let ae=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),B="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await ae.text(),at=Ue.transformSync(qe);return new Response(at,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":B="text/html";break;case".css":B="text/css";break;case".js":B="text/javascript";break;case".json":B="application/json";break;case".png":B="image/png";break;case".jpg":case".jpeg":B="image/jpeg";break;case".gif":B="image/gif";break;case".svg":B="image/svg+xml";break;case".ico":B="image/x-icon";break;case".woff":B="font/woff";break;case".woff2":B="font/woff2";break;case".ttf":B="font/ttf";break;case".otf":B="font/otf";break;case".eot":B="application/vnd.ms-fontobject";break}return new Response(ae,{headers:{"Content-Type":B}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
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=we.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${P}${e.reset}`),console.log(`
947
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(j.url.toString(),()=>{if(p)Ne.watch(we.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),z=$t(I);await lt(E,{title:we.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!z,sidebarConfig:z})}if(p){let I=we.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let z=Ne.watch(I,{recursive:!0},async(G,te)=>{if(!te||Et(te))return;if(Rt(te)){console.log(`${e.yellow}File ${e.bright}${te}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K();let Te=await b();if(await ln(S),c&&l)if(Te)l.reload(te);else l.error("Build failed - check console for details")}else if(Ct(te)){if(console.log(`${e.cyan}CSS ${e.bright}${te}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(te)}});process.on("SIGINT",()=>{if(z.close(),l)gt();j.stop(),process.exit(0)})}return!0}var{serve:Xr}=globalThis.Bun;import ot from"fs";import Ae from"path";var cn=`
948
+ <script data-stx-helpers>
949
+ (function() {
950
+ 'use strict'
951
+
952
+ if (window.__stxHelpers) return
953
+ window.__stxHelpers = true
954
+
955
+ window.stx = window.stx || {}
956
+
957
+ // ===== FORMATTERS =====
958
+
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
+ }
965
+
966
+ stx.formatNumber = function(val, decimals, locale) {
967
+ var opts = {}
968
+ if (typeof decimals === 'number') {
969
+ opts.minimumFractionDigits = decimals
970
+ opts.maximumFractionDigits = decimals
971
+ }
972
+ return new Intl.NumberFormat(locale || 'en-US', opts).format(val)
973
+ }
974
+
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)
979
+
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)
991
+ }
992
+ return d.toLocaleDateString(locale)
993
+ }
994
+
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
1000
+ }
1001
+
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>'
1012
+ }
1013
+ return h
1014
+ }
1015
+
1016
+ // ===== BADGE SYSTEM =====
1017
+
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' },
1031
+ }
1032
+
1033
+ stx.registerBadgeMap = function(name, map) {
1034
+ badgeMaps[name] = Object.assign(badgeMaps[name] || {}, map)
1035
+ }
1036
+
1037
+ stx.badgeClass = function(value, mapName) {
1038
+ var map = badgeMaps[mapName || 'status'] || badgeMaps.status
1039
+ return map[value] || 'badge-slate'
1040
+ }
1041
+
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>\`
1044
+ }
1045
+
1046
+ // ===== DETAIL PANEL BUILDER =====
1047
+
1048
+ function esc(v) { return v != null ? v : '\\u2014' }
1049
+
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) })
1056
+ }
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
+ }
1082
+ }
1083
+ return \`
1084
+ <div class="detail-section">
1085
+ <div class="detail-label">\${label}</div>
1086
+ \${inner}
1087
+ </div>\`
1088
+ },
1089
+
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
+ },
1097
+
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] } })
1102
+
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('')
1110
+
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
+ },
1113
+
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
1118
+
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('')
1132
+
1133
+ return \`<div style="padding:0 1.5rem 1rem">\${entries}</div>\`
1134
+ },
1135
+
1136
+ open: function(html) {
1137
+ if (typeof openSlideOver === 'function') openSlideOver(html)
1138
+ },
1139
+ }
1140
+
1141
+ // ===== DATA TABLE HELPERS =====
1142
+
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 = []
1150
+
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
+ })
1161
+
1162
+ if (matchSearch && matchFilters) matched.push(row)
1163
+ else row.style.display = 'none'
1164
+ })
1165
+
1166
+ return matched
1167
+ },
1168
+
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
+ }
1181
+
1182
+ // ===== PAGINATION =====
1183
+
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
1191
+
1192
+ var start = (page - 1) * perPage
1193
+ var end = Math.min(start + perPage, total)
1194
+
1195
+ items.forEach(function(el, i) { el.style.display = (i >= start && i < end) ? '' : 'none' })
1196
+
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' : '' }
1202
+
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)
1208
+
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
+ }
1214
+
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
+ }
1231
+
1232
+ return { page: page, totalPages: totalPages, total: total, start: start, end: end }
1233
+ }
1234
+
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
+ }
1244
+
1245
+ // ===== UTILITIES =====
1246
+
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
+ }
1255
+
1256
+ })()
1257
+ </script>
1258
+ `;function pn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),a=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))a.push(c);else break}return a.join(Ae.sep)}async function xn(t,s={}){let a=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!ot.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=o(process.cwd(),"output");ot.mkdirSync(c,{recursive:!0});let l=pn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],y=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:F}=await ue(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,j=L?.defaultTheme||"github-dark",P=["github-dark"],I=L?.additionalThemes||[],G=[...new Set([...P,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
1259
+ `),te=`
1260
+ <!DOCTYPE html>
1261
+ <html lang="en">
1262
+ <head>
1263
+ <meta charset="UTF-8">
1264
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1265
+ <title>${dn(F.title||Ae.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>
1304
+ <style>
1305
+ body {
1306
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
1307
+ line-height: 1.6;
1308
+ 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
+ ${xt()}
1408
+ </style>
1409
+ </head>
1410
+ <body>
1411
+ ${kt(F)}
1412
+ ${vt(G)}
1413
+
1414
+ ${k}
1415
+
1416
+ <script>
1417
+ ${St()}
1418
+ </script>
1419
+ </body>
1420
+ </html>
1421
+ `,he=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:te,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(P){P.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},F;try{let P=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ut],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!P.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,Me(P.logs,x));continue}let I=P.outputs.find((z)=>z.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}F=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
1422
+ ${Me(P,x)}`);continue}let j=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=ar(j);u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:F,fileType:"stx"}}else m[j||"/"]={filePath:x,content:F,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,Me(v)),!1}};if(!await y())return!1;let b=a;try{if(b=await Ye(a),b!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Xr({port:b,async fetch(v){let x=new URL(v.url),R=Ae.join(process.cwd(),"public",x.pathname);if(ot.existsSync(R)&&ot.statSync(R).isFile()){let L=Bun.file(R),j=Ae.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),z=await L.text(),G=I.transformSync(z);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let L of u){let j=x.pathname.match(L.pattern);if(j){let P=m[L.routeTemplate];if(P){let I={};for(let te=0;te<L.paramNames.length;te++)I[L.paramNames[te]]=decodeURIComponent(j[te+1]);let z=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(z.includes("</head>"))z=z.replace("</head>",`${G}
1423
+ </head>`);else z=G+z;k={...P,content:z}}break}}if(k)return f(k.content).then((L)=>{if(L.includes("</head>"))L=L.replace("</head>",`${cn}
1424
+ </head>`);return new Response(L,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let F=Ae.join(c,x.pathname);if(ot.existsSync(F)&&ot.statSync(F).isFile()){let L=Bun.file(F),j=Ae.extname(F).toLowerCase(),P="text/plain";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),z=await L.text(),G=I.transformSync(z);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}if(x.pathname!=="/"&&m["/"]){let L=se(v);return f(m["/"].content).then((j)=>{if(L){let P=j.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(P){let I=j.match(/<title[^>]*>([\s\S]*?)<\/title>/i),z=I?I[1]:"",G=`<!DOCTYPE html><html><head><title>${dn(z)}</title></head><body><main>${P[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...C(),"Cache-Control":Pe,Pragma:"no-cache",Expires:"0"}})}}return new Response(j,{headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
1425
+ ${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:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");E.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(E.sort((v,x)=>v.route.localeCompare(x.route)),E.forEach((v,x)=>{let k=x===E.length-1?"\u2514\u2500 ":"\u251C\u2500 ",F=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${F}`)}),console.log(`
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(p)ot.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=ot.watch(l,{recursive:!0},async(x,R)=>{if(!R)return;if(R.endsWith(".stx")||R.endsWith(".js")||R.endsWith(".ts")||R.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${R}${e.yellow} changed, rebuilding...${e.reset}`),ve.clear(),K(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function dn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Gr}=globalThis.Bun;import be from"fs";import oe from"path";async function un(t){try{return wt(await Bun.file(t).text())}catch{return}}function Ut(t){let s=Bun.file(t),a=oe.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(a)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[a]||"application/octet-stream",...l}})}async function Sn(t=".",s={}){let a=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||a+1,u=oe.resolve(t),{loadStxConfig:y}=await import("./chunk-48bwk47q.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-5g3y8kym.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?oe.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",R=oe.join(v,x);if(!be.existsSync(R)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${R}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=M(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[R,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${R}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let F=g?._pluginPageDirs||[],L=[];for(let{dir:A,prefix:N}of F)if(be.existsSync(A)){let U=M(oe.dirname(A),{pagesDir:oe.basename(A)});for(let V of U){let xe=N==="/"?V.pattern:`${N}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:xe},prefix:N})}if(U.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${U.length}${e.blue} routes at ${e.cyan}${N}${e.reset}`)}let j=new Map,P=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await ri(u,s.stxOptions?.shell),I){if(P=await Sr(I,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let z=et();if(z.length>0)console.log(`${e.blue}Loaded ${e.bright}${z.length}${e.blue} middleware: ${e.dim}${z.join(", ")}${e.reset}`);let G={},te=null;try{let{loadStxConfig:A}=await import("./chunk-48bwk47q.js"),N=await A(u);if(N?.apiRouter)te=N?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(N?.apiRoutes){G=N.apiRoutes;let U=Object.keys(G).length;if(U>0)console.log(`${e.blue}Loaded ${e.bright}${U} API route${U>1?"s":""}${e.reset}`)}if(N?.broadcasting?.enabled)try{let{startBroadcasting:U,loadChannels:V}=await import("./chunk-dgdm3hy3.js"),xe=N.broadcasting;await U(xe);let We=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=oe.join(process.cwd(),"channels.ts");if(be.existsSync(Ge))try{let ne=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(U){console.warn(`${e.yellow}Broadcasting failed to start: ${U.message}${e.reset}`)}}catch{}let Te=o(u,"output");be.mkdirSync(Te,{recursive:!0});let he=new Map,Oe=new Set,ae=async(A)=>{let N=cr(R,A);if(!N)return null;try{let U=await Bun.build({entrypoints:[N],outdir:Te,plugins:[ut],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!U.success)return null;let V=U.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,B=async(A,N)=>{try{let{processDirectives:U,extractVariables:V,defaultConfig:xe,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-48bwk47q.js"),{checkCache:ne,cacheTemplate:Z,readFileCached:q,templateCache:Y}=await import("./chunk-s2x4wcrz.js"),Se=await We(u),Je=(ce)=>{if(!ce)return ce;if(oe.isAbsolute(ce))return ce;return oe.resolve(u,ce)},D={...xe,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)D.debug=!0;D.partialsDir=Je(D.partialsDir),D.componentsDir=Je(D.componentsDir),D.layoutsDir=Je(D.layoutsDir),D.storesDir=Je(D.storesDir||"stores"),D.cachePath=Je(D.cachePath)??o(u,"cache");let ye=!N&&!s.profile,de=D.cache!==!1;if(de&&ye){let ce=Y.get(A.filePath);if(ce)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=ce.mtime){let ze=!0;for(let Re of ce.dependencies){if(!be.existsSync(Re)){ze=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>ce.mtime){ze=!1;break}}if(ze){let Re=ce.output;if(P)Re=me(Re,{preserveHead:!0});let mt=W.get(A.filePath);return{route:A,content:Re,status:mt?.status??await un(A.filePath),headers:mt?.headers}}}}catch{}let Ie=await ne(A.filePath,D);if(Ie){let He=Ie;if(P)He=me(He,{preserveHead:!0});let ze=W.get(A.filePath);return{route:A,content:He,status:ze?.status??await un(A.filePath),headers:ze?.headers}}}let ge=de?await q(A.filePath):await Bun.file(A.filePath).text(),$e=wt(ge),{classifyAllScripts:Q}=await import("./chunk-48bwk47q.js"),Le=Q(ge),Ve=Le.server.map((ce)=>ce.content),pe=ge;for(let ce of Le.server)pe=pe.replace(ce.fullTag,"");let fe={__filename:A.filePath,__dirname:oe.dirname(A.filePath),__stx_options:D,params:N??{},__stx_runtime_head:{}};for(let ce of Ve)try{await V(ce,fe,A.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Ie?.message||Ie)}let Ke=new Set,De;if(s.profile){let ce=performance.now();De=await U(pe,fe,A.filePath,D,Ke);let Ie=performance.now()-ce,He=oe.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else De=await U(pe,fe,A.filePath,D,Ke);if(!P)De=await Ge(De,{router:D.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-mhq0pjws.js");De=De.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${ce(ze,fe)}</script>`})}if(P)De=me(De,{preserveHead:!0});if(de&&ye)await Z(A.filePath,De,Ke,D);let{extractStreamBoundaries:Vn}=await import("./chunk-bmt7w2pk.js"),ct=Vn(fe),ft=fe.__streamTemplates;if(ft&&typeof ft==="object"&&Object.keys(ft).length>0){let ce=fe.streamBoundaries||{},Ie={...D,autoShell:!1},He=Object.keys(ft).map((Re)=>({id:Re,render:async()=>{let mt=typeof ce[Re]==="function"?await ce[Re]():void 0;return U(ft[Re],{...fe,$boundary:mt},A.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));ct=[...(ct||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(ct&&ct.length>0)Oe.add(A.pattern);else ct=void 0;let qt=Be(fe),Kt=Fe(fe);if(ye)W.set(A.filePath,{status:qt,headers:Kt});return{route:A,content:De,status:qt??$e,headers:Kt,boundaries:ct}}catch(U){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,U),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let A=0;A<k.length;A+=Ue){let N=k.slice(A,A+Ue),U=await Promise.all(N.map((V)=>B(V)));for(let V of U)if(V)he.set(V.route.pattern,V)}for(let A=0;A<L.length;A+=Ue){let N=L.slice(A,A+Ue),U=await Promise.all(N.map(({route:V})=>B(V)));for(let V of U)if(V)j.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Tt(u);let it=a;try{if(it=await Ye(a),it!==a)console.log(`${e.yellow}Port ${a} is busy, using port ${it} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let A=s.hmrPort||it+1;l=Pt({wsPort:A,verbose:!1}),m=l.start(A)}let _t=(A,N)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(N).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Gr({port:it,async fetch(A){let N=new URL(A.url),U=g?.publicDir||"public",V=oe.join(u,U,N.pathname),xe=oe.join(u,N.pathname),We=oe.join(Te,N.pathname);if([V,xe,We].some((D)=>w(D,u,S)))return new Response("Not Found",{status:404});let[Ge,ne,Z]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(xe).catch(()=>null),be.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return Ut(V);if(ne?.isFile()&&!w(xe,u,S))return Ut(xe);if(Z?.isFile()&&!w(We,u,S))return Ut(We);if(N.pathname.startsWith("/_stx/component/")){let D=decodeURIComponent(N.pathname.slice(16));if(D)try{let ye=`<${D} />`,de={...buildConfig,autoShell:!1},ge=await processDirectives(ye,{},oe.join(u,"components",`${D}.stx`),de,new Set);return new Response(ge,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(N.pathname==="/_stx/img"){let{handleImageRequest:D}=await import("./chunk-q6vrb2pe.js"),ye=await D(A,{publicDir:oe.join(u,U),cacheDir:o(u,"cache","img")});if(ye)return ye}if(te)try{let D=await te.handleRequest(A);if(D.status!==404)return D}catch{}if(G[N.pathname])try{return await G[N.pathname](A)}catch(D){return new Response(JSON.stringify({error:D.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await E(A);if(q)return q;let Y=yn(N.pathname,k);if(Y){let D=he.get(Y.route.pattern),ye=Oe.has(Y.route.pattern);if(Y.route.isDynamic&&Object.keys(Y.params).length>0||ye){let de=await B(Y.route,Y.params);if(de)D=de}if(D){let de=D.status??200,ge=D.headers??{},$e=(Y.route.filePath?je(await Bun.file(Y.route.filePath).text().catch(()=>"")):null)??{};if($e.validate){if(!await $e.validate({params:Y.params})){let Ve=await ae(404);if(Ve){let pe=Ve;if(pe=await f(pe,u),c)pe=Xe(pe,m);return new Response(pe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if($e.middleware){let Le=nt(N.pathname,Y.params,$e,N.search),Ve=rt(Le,null,A,{isServer:!0}),pe=await st($e.middleware,Ve);if(pe.redirect){let fe=pe.redirect.path,Ke=pe.redirect.options.redirectCode||302,De=new Headers(pe.responseHeaders);return De.set("Location",fe),new Response(null,{status:Ke,headers:De})}if(pe.abort){let{statusCode:fe,message:Ke}=pe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(pe.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(pe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;D.content=D.content.replace("</head>",`${fe}</head>`)}}let Q=D.content;if(P&&si(A)){let Le=Ce(Q),Ve=le(Q),pe=Q.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=pe?ni(pe[1].trim()):"";if(Object.keys(Y.params).length>0)Q=_t(Q,Y.params);Q=await f(Q,u);let Ke=g?.router?.container||"main";return Q=ie(Q,Ke),new Response(Q,{status:de,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Ji]:ds(),...C(),"Cache-Control":Pe}})}if(P)Q=En(P,Q);if(Object.keys(Y.params).length>0)Q=_t(Q,Y.params);if(Q=await f(Q,u),c)Q=Xe(Q,m);if(s.native)if(Q.includes("<head>"))Q=Q.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Q="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Q;if(s.titlebarHidden)if(Q.includes("<head>"))Q=Q.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Q=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Q}`;if(D.boundaries&&D.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-bmt7w2pk.js");return Ve(Le(Q,D.boundaries,{timeoutMs:30000}),{status:de,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Q,{status:de,headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(L.length>0){let D=L.map((de)=>de.route),ye=yn(N.pathname,D);if(ye){let de=j.get(ye.route.pattern);if(de){let ge=de.content;if(P)ge=En(P,ge);if(Object.keys(ye.params).length>0)ge=_t(ge,ye.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:de.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:de}of F)if(de!=="/"&&N.pathname.startsWith(de)){let ge=j.get(de)||j.get(de+"/");if(ge){let $e=ge.content;if(P)$e=En(P,$e);if($e=await f($e,u),c)$e=Xe($e,m);return new Response($e,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}let Se=he.get("/");if(Se){let D=Se.content;if(D=await f(D,u),c)D=Xe(D,m);if(s.native)if(D.includes("<head>"))D=D.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else D="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+D;return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let D=Je;if(D=await f(D,u),c)D=Xe(D,m);return new Response(D,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let N=await ae(500);if(N)return new Response(N,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
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:${it}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
1433
+ ${e.yellow}Routes:${e.reset}`);let It=[...lr(k,u)];for(let{route:A}of L)It.push(`${A.pattern}`);if(It.forEach((A,N)=>{let V=N===It.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),console.log(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(l)gt();Lt.stop()}),s.native){let A,N=oe.join(R,"index.stx");if(be.existsSync(N)){let V=await Bun.file(N).text();A=$t(V)}let U=g?.app?.window??{};await lt(it,{title:g?.app?.head?.title||oe.basename(u)||"stx App",width:U.width,height:U.height,darkMode:U.darkMode,hotReload:U.hotReload,titlebarHidden:U.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ne)=>ne.startsWith("public/")||ne.startsWith("public\\"),N=(ne)=>{let Z=ne.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},U=new Map,V=()=>{let ne=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>oe.dirname(Z))??[]].filter((Z)=>be.existsSync(Z)).map((Z)=>be.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!be.existsSync(q))continue;let Y=be.realpathSync(q);if(![...ne].some((Se)=>Y===Se||Y.startsWith(`${Se}${oe.sep}`)))ne.add(Y)}for(let[Z,q]of U)if(!ne.has(Z))q.close(),U.delete(Z);for(let Z of ne)if(!U.has(Z)&&be.existsSync(Z))U.set(Z,be.watch(Z,{recursive:!0},(q,Y)=>{We(Z,q,Y).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},xe=Promise.resolve(),We=(ne,Z,q)=>(xe=xe.catch(()=>{}).then(()=>Ge(ne,Z,q)),xe),Ge=async(ne,Z,q)=>{if(!q||Et(q))return;if(Rt(q)){if(g._layerGraph){let Y=await y(u);Object.assign(g,Y),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:Y._layerPageDirs?[R,...Y._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(N(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-s2x4wcrz.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(I&&q){if(oe.resolve(ne,q)===I||oe.basename(I)===q){let Se=await Sr(I,s.stxOptions||{});if(Se)P=Se}}if(await qe(),await ln(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ve.clear(),K();try{let{invalidateFileCache:Y,templateCache:Se}=await import("./chunk-s2x4wcrz.js");Y(oe.resolve(ne,q)),Se.delete(oe.resolve(ne,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Ct(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let ne of U.values())ne.close();if(l)gt();Lt.stop(),process.exit(0)})}return!0}import Wt from"fs";import ht from"path";async function Jr(t){try{let a=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!a)return[];let p=a[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],y=m[2]||m[3]||m[4];if(!y)continue;let g={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let E=u.split(`
1435
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=E.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Yr(t){try{let s=await Bun.file(t).text(),a=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(a)return a[1].split(`
1436
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Qr(t,s=!1,a){let p=ht.basename(t,".stx"),c=await Jr(t),l=await Yr(t),m="";if(s&&a)m=`<${a}></${a}>`;else{let u=c.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
+ `);m=`<${p}
1438
+ ${u}
1439
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:a}}async function mn(t){try{if(!await n(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){let c=ht.join(t,p.name);if(p.isDirectory()){let l=await mn(c);a.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))a.push(c)}return a}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Zr(t,s){try{if(!await n(t))return[];let a=await mn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of a){let m=c.get(l),u=!!m,y=m?.tag,g=await Qr(l,u,y);p.push(g)}return p}catch(a){return console.error("Error generating component docs:",a),[]}}async function es(t){try{if(!await n(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),a=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=ht.join(t,p.name),l=await Bun.file(c).text(),m=ht.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
1440
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=b.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let E=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=E.exec(l))!==null)v.add(S[1]);a.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return a}catch(s){return console.error("Error generating template docs:",s),[]}}async function ts(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
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 a of t)s.push({name:a.name,description:a.description||"",hasEndTag:a.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function ns(t=[],s=[],a=[],p){let c=`# stx Documentation
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(a.length>0){c+=`## Directives
1491
+
1492
+ `,c+=`| Directive | Description | Has End Tag |
1493
+ `,c+=`| --------- | ----------- | ----------- |
1494
+ `;for(let l of a)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
1495
+ `;c+=`
1496
+ `;for(let l of a)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 rs(t=[],s=[],a=[],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;
1514
+ margin: 0 auto;
1515
+ padding: 2rem;
1516
+ }
1517
+ h1, h2, h3, h4 { margin-top: 2rem; }
1518
+ table {
1519
+ border-collapse: collapse;
1520
+ width: 100%;
1521
+ margin: 1rem 0;
1522
+ }
1523
+ th, td {
1524
+ text-align: left;
1525
+ padding: 0.5rem;
1526
+ border-bottom: 1px solid #ddd;
1527
+ }
1528
+ th { border-bottom: 2px solid #ddd; }
1529
+ pre {
1530
+ background: #f5f5f5;
1531
+ padding: 1rem;
1532
+ border-radius: 4px;
1533
+ overflow-x: auto;
1534
+ }
1535
+ code {
1536
+ background: #f5f5f5;
1537
+ padding: 0.2rem 0.4rem;
1538
+ border-radius: 4px;
1539
+ font-size: 0.9em;
1540
+ }
1541
+ </style>
1542
+ </head>
1543
+ <body>
1544
+ <h1>stx Documentation</h1>
1545
+ `;if(p)c+=`<div>${p}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
1546
+ <thead>
1547
+ <tr>
1548
+ <th>Name</th>
1549
+ <th>Type</th>
1550
+ <th>Required</th>
1551
+ <th>Default</th>
1552
+ <th>Description</th>
1553
+ </tr>
1554
+ </thead>
1555
+ <tbody>`;for(let m of l.props)c+=`<tr>
1556
+ <td>${m.name}</td>
1557
+ <td>${m.type||"any"}</td>
1558
+ <td>${m.required?"Yes":"No"}</td>
1559
+ <td>${m.default||"-"}</td>
1560
+ <td>${m.description||"-"}</td>
1561
+ </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(a.length>0){c+="<h2>Directives</h2>",c+=`<table>
1562
+ <thead>
1563
+ <tr>
1564
+ <th>Directive</th>
1565
+ <th>Description</th>
1566
+ <th>Has End Tag</th>
1567
+ </tr>
1568
+ </thead>
1569
+ <tbody>`;for(let l of a)c+=`<tr>
1570
+ <td>@${l.name}</td>
1571
+ <td>${l.description||"-"}</td>
1572
+ <td>${l.hasEndTag?"Yes":"No"}</td>
1573
+ </tr>`;c+="</tbody></table>";for(let l of a)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function ss(t=[],s=[],a=[],p){return JSON.stringify({components:t,templates:s,directives:a,extraContent:p||""},null,2)}async function os(t){try{let{componentsDir:s,templatesDir:a,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(a)console.log(`Templates directory: ${a}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await Zr(s,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&a)console.log("Generating template documentation..."),y=await es(a),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ts(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=ns(u,y,g,w),E="md";break;case"html":S=rs(u,y,g,w),E="html";break;case"json":S=ss(u,y,g,w),E="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=ht.join(m,`stx-docs.${E}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Us(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},a=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return os({componentsDir:a,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var hn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function gr(t,s={}){let a={...hn,...s};if(t.trim()==="")return`
1574
+ `;let p=t;if(a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=cs(p,a),p=fs(p,a),p=ls(p,a),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1575
+ `).replace(/\r/g,`
1576
+ `),!p.endsWith(`
1577
+ `))p+=`
1578
+ `;return p}function Ws(t,s={}){let a={...hn,...s};if(t.trim()==="")return`
1579
+ `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,y)=>{let g=u.split(`
1580
+ `),b=g.filter((x)=>x.trim().length>0);if(b.length===0)return c;let w=Math.min(...b.map((x)=>{let R=x.match(/^( *)/);return R?R[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1581
+ `),v=gr(S,a).trimEnd().split(`
1582
+ `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1583
+ `);return`${l}\`\`\`${m}
1584
+ ${v}
1585
+ ${l}\`\`\``}),a.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1586
+ `).replace(/\r/g,`
1587
+ `),!p.endsWith(`
1588
+ `))p+=`
1589
+ `;return p}function as(t){let s=t,a=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=a.length;return a.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1590
+ $1
1591
+ `),s=s.replace(/(@end\w+)/g,`
1592
+ $1
1593
+ `),s=s.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1594
+ $1
1595
+ `),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1596
+ $1
1597
+ `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let y=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&y.match(new RegExp(`^</${g}>`)))return c;return`
1598
+ ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,y)=>{let g=y.substring(Math.max(0,u-50),u),w=y.substring(u+c.length,Math.min(y.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1599
+ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&y.match(b))return c;return`${c}
1600
+ `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>a[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1601
+ `),s=s.split(`
1602
+ `).map((c)=>c.trim()).join(`
1603
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function cs(t,s){let p=as(t).split(`
1604
+ `),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let y=0;y<p.length;y++){let g=p[y],b=g.trim();if(b===""){c.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let E=b===">";if(gn(b)&&!b.startsWith("<")&&!b.startsWith("@")){c.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),R=b.startsWith("@")&&us(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),F=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!F&&!k,P=b.includes("/>")||ps(b),I=gn(b);if(L||v)l=Math.max(0,l-1);let z=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(z)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1605
+ `)}function ls(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(a,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(a,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(a,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(a,p)=>`{!! ${p.trim()} !!}`);return t}function ps(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let a=t.match(/<(\w+)/);if(a){let p=a[1];return s.includes(p.toLowerCase())}return!1}function gn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function us(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let a of s)if(t.startsWith(`@${a}`))return!t.includes(`@end${a}`);return!1}function fs(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(a,p,c)=>{if(!c.trim())return a;if(c.includes("<")||c.includes(`
1606
+ `)||c.includes("@"))return a;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,b)=>{if(g.name==="id")return-1;if(b.name==="id")return 1;if(g.name==="class")return-1;if(b.name==="class")return 1;return g.name.localeCompare(b.name)});let y=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import bn from"fs";import Vt from"path";async function qs(t="index.stx",s={}){try{let a=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!a)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!bn.existsSync(c))bn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=vn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=vn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(a){return console.error(`Error creating file: ${a instanceof Error?a.message:String(a)}`),!1}}function vn(t){switch(t){case"basic":return kn();case"component":return ms();case"layout":return gs();case"blog":return hs();case"api":return ys();case"app":return bs();default:return kn()}}function kn(){return`<script>
1607
+ const title = "My stx Page"
1608
+ const description = "A page built with stx"
1609
+ const features = [
1610
+ { name: "Single File Components", desc: "Script, style, and template in one .stx file" },
1611
+ { name: "Component System", desc: "Import components with @component('name', {})" },
1612
+ { name: "Blade Directives", desc: "@if, @foreach, @switch, @layout and more" }
1613
+ ]
1614
+ </script>
1615
+
1616
+ @section('content')
1617
+ <header>
1618
+ <h1>{{ title }}</h1>
1619
+ <p>{{ description }}</p>
1620
+ </header>
1621
+
1622
+ <main>
1623
+ <h2>Features</h2>
1624
+ @foreach(features as feature)
1625
+ <div class="card">
1626
+ <h3>{{ feature.name }}</h3>
1627
+ <p>{{ feature.desc }}</p>
1628
+ </div>
1629
+ @endforeach
1630
+ </main>
1631
+ @endsection`}function ms(){return`{{-- Component: Card --}}
1632
+ {{-- Props: title, variant, collapsible --}}
1633
+ {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1634
+ <script>
1635
+ // Props with defaults
1636
+ const title = props.title || 'Card Title'
1637
+ const variant = props.variant || 'default'
1638
+ const collapsible = props.collapsible || false
1639
+ </script>
1640
+
1641
+ <div class="card card--{{ variant }}">
1642
+ <div class="card__header" onclick="this.parentElement.classList.toggle('collapsed')">
1643
+ <h3 class="card__title">{{ title }}</h3>
1644
+ @if(collapsible)
1645
+ <span class="card__toggle">\u25BC</span>
1646
+ @endif
1647
+ </div>
1648
+ <div class="card__body">
1649
+ {{ slot }}
1650
+ </div>
1651
+ </div>
1652
+
1653
+ <style scoped>
1654
+ .card {
1655
+ border-radius: 8px;
1656
+ background: #fff;
1657
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
1658
+ overflow: hidden;
1659
+ }
1660
+ .card--primary { border-top: 3px solid #3498db; }
1661
+ .card--success { border-top: 3px solid #2ecc71; }
1662
+ .card--warning { border-top: 3px solid #f39c12; }
1663
+ .card--danger { border-top: 3px solid #e74c3c; }
1664
+ .card__header {
1665
+ padding: 1rem;
1666
+ background: #f8f9fa;
1667
+ display: flex;
1668
+ justify-content: space-between;
1669
+ align-items: center;
1670
+ }
1671
+ .card__title { margin: 0; font-size: 1.1rem; }
1672
+ .card__toggle { transition: transform 0.2s; }
1673
+ .card.collapsed .card__toggle { transform: rotate(-90deg); }
1674
+ .card__body { padding: 1rem; }
1675
+ .card.collapsed .card__body { display: none; }
1676
+ </style>`}function gs(){return`<!DOCTYPE html>
1677
+ <html lang="en">
1678
+ <head>
1679
+ <meta charset="UTF-8">
1680
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1681
+ <title>@yield('title', 'My App')</title>
1682
+ @yield('head')
1683
+ <style>
1684
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1685
+ body {
1686
+ font-family: system-ui, sans-serif;
1687
+ min-height: 100vh;
1688
+ display: flex;
1689
+ flex-direction: column;
1690
+ }
1691
+ header, footer {
1692
+ background: #2c3e50;
1693
+ color: white;
1694
+ padding: 1rem 2rem;
1695
+ }
1696
+ main {
1697
+ flex: 1;
1698
+ padding: 2rem;
1699
+ max-width: 1200px;
1700
+ margin: 0 auto;
1701
+ width: 100%;
1702
+ }
1703
+ nav a { color: white; margin-right: 1rem; text-decoration: none; }
1704
+ nav a:hover { text-decoration: underline; }
1705
+ </style>
1706
+ @yield('styles')
1707
+ </head>
1708
+ <body>
1709
+ <header>
1710
+ <nav>
1711
+ <a href="/">Home</a>
1712
+ <a href="/about">About</a>
1713
+ <a href="/contact">Contact</a>
1714
+ </nav>
1715
+ </header>
1716
+
1717
+ <main>
1718
+ {{ slot }}
1719
+ </main>
1720
+
1721
+ <footer>
1722
+ <p>&copy; {{ new Date().getFullYear() }} My App</p>
1723
+ </footer>
1724
+
1725
+ @yield('scripts')
1726
+ </body>
1727
+ </html>`}function hs(){return`<script>
1728
+ // Article metadata
1729
+ const title = "My Blog Post"
1730
+ const author = "Your Name"
1731
+ const date = new Date().toLocaleDateString('en-US', {
1732
+ year: 'numeric',
1733
+ month: 'long',
1734
+ day: 'numeric'
1735
+ })
1736
+ const tags = ["stx", "tutorial", "web development"]
1737
+ const readingTime = "5 min read"
1738
+ </script>
1739
+
1740
+ @layout('layouts/blog')
1741
+
1742
+ @section('title')
1743
+ {{ title }}
1744
+ @endsection
1745
+
1746
+ @section('content')
1747
+ <article class="blog-post">
1748
+ <header class="blog-post__header">
1749
+ <h1>{{ title }}</h1>
1750
+ <div class="blog-post__meta">
1751
+ <span class="author">By {{ author }}</span>
1752
+ <span class="date">{{ date }}</span>
1753
+ <span class="reading-time">{{ readingTime }}</span>
1754
+ </div>
1755
+ <div class="blog-post__tags">
1756
+ @foreach(tags as tag)
1757
+ <span class="tag">#{{ tag }}</span>
1758
+ @endforeach
1759
+ </div>
1760
+ </header>
1761
+
1762
+ <div class="blog-post__content">
1763
+ <p>Your content goes here...</p>
1764
+
1765
+ <h2>Introduction</h2>
1766
+ <p>Start writing your blog post content.</p>
1767
+
1768
+ <h2>Conclusion</h2>
1769
+ <p>Wrap up your thoughts here.</p>
1770
+ </div>
1771
+ </article>
1772
+ @endsection`}function ys(){return`<script>
1773
+ // API endpoint configuration
1774
+ const endpoint = "/api/data"
1775
+ const method = "GET"
1776
+
1777
+ // Mock data - replace with actual data fetching
1778
+ const data = {
1779
+ success: true,
1780
+ message: "Data retrieved successfully",
1781
+ items: [
1782
+ { id: 1, name: "Item 1" },
1783
+ { id: 2, name: "Item 2" },
1784
+ { id: 3, name: "Item 3" }
1785
+ ],
1786
+ meta: {
1787
+ total: 3,
1788
+ page: 1,
1789
+ perPage: 10
1790
+ }
1791
+ }
1792
+
1793
+ // For error responses
1794
+ const error = null
1795
+ </script>
1796
+
1797
+ @if(error)
1798
+ {
1799
+ "success": false,
1800
+ "error": {
1801
+ "code": "{{ error.code || 'UNKNOWN_ERROR' }}",
1802
+ "message": "{{ error.message || 'An error occurred' }}"
1803
+ }
1804
+ }
1805
+ @else
1806
+ {{ JSON.stringify(data, null, 2) }}
1807
+ @endif`}function bs(){return`<!DOCTYPE html>
1808
+ <html lang="en">
1809
+ <head>
1810
+ <meta charset="UTF-8">
1811
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1812
+ <title>{{ title }} - stx App</title>
1813
+ <script>
1814
+ const title = "My App"
1815
+ </script>
1816
+ <style>
1817
+ :root {
1818
+ --bg: #1a1a2e;
1819
+ --bg-dark: #16213e;
1820
+ --fg: #eaeaea;
1821
+ --primary: #e94560;
1822
+ --secondary: #0f3460;
1823
+ --success: #00d9ff;
1824
+ --border: #2a2a4a;
1825
+ }
1826
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1827
+ body {
1828
+ font-family: system-ui, -apple-system, sans-serif;
1829
+ background: var(--bg);
1830
+ color: var(--fg);
1831
+ min-height: 100vh;
1832
+ }
1833
+ .container { max-width: 800px; margin: 0 auto; padding: 2rem; }
1834
+ .header { text-align: center; margin-bottom: 2rem; }
1835
+ .header h1 { color: var(--primary); margin-bottom: 0.5rem; }
1836
+ .card {
1837
+ background: var(--bg-dark);
1838
+ border: 1px solid var(--border);
1839
+ border-radius: 12px;
1840
+ padding: 1.5rem;
1841
+ margin-bottom: 1rem;
1842
+ }
1843
+ .btn {
1844
+ background: var(--primary);
1845
+ color: white;
1846
+ border: none;
1847
+ padding: 0.75rem 1.5rem;
1848
+ border-radius: 8px;
1849
+ cursor: pointer;
1850
+ font-size: 1rem;
1851
+ transition: opacity 0.2s;
1852
+ }
1853
+ .btn:hover { opacity: 0.9; }
1854
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
1855
+ .btn--secondary { background: var(--secondary); }
1856
+ .btn--success { background: var(--success); color: var(--bg); }
1857
+ .input {
1858
+ width: 100%;
1859
+ background: var(--bg);
1860
+ border: 1px solid var(--border);
1861
+ color: var(--fg);
1862
+ padding: 0.75rem 1rem;
1863
+ border-radius: 8px;
1864
+ font-size: 1rem;
1865
+ margin-bottom: 1rem;
1866
+ }
1867
+ .input:focus { outline: none; border-color: var(--primary); }
1868
+ .flex { display: flex; gap: 1rem; align-items: center; }
1869
+ .flex-between { justify-content: space-between; }
1870
+ .text-muted { color: #888; }
1871
+ .text-success { color: var(--success); }
1872
+ .mb-1 { margin-bottom: 1rem; }
1873
+ .hidden { display: none; }
1874
+ </style>
1875
+ </head>
1876
+ <body>
1877
+ <div class="container">
1878
+ <header class="header">
1879
+ <h1>{{ title }}</h1>
1880
+ <p class="text-muted">Built with stx</p>
1881
+ </header>
1882
+
1883
+ <!-- Counter Example -->
1884
+ <div class="card">
1885
+ <h2 class="mb-1">Counter Example</h2>
1886
+ <div class="flex flex-between">
1887
+ <span id="counterDisplay">Count: 0</span>
1888
+ <div class="flex">
1889
+ <button class="btn btn--secondary" onclick="window.app?.decrement()">-</button>
1890
+ <button class="btn" onclick="window.app?.increment()">+</button>
1891
+ <button class="btn btn--success" onclick="window.app?.reset()">Reset</button>
1892
+ </div>
1893
+ </div>
1894
+ </div>
1895
+
1896
+ <!-- Todo List Example -->
1897
+ <div class="card">
1898
+ <h2 class="mb-1">Todo List</h2>
1899
+ <div class="flex mb-1">
1900
+ <input
1901
+ type="text"
1902
+ id="todoInput"
1903
+ class="input"
1904
+ placeholder="Add a new todo..."
1905
+ onkeypress="if(event.key==='Enter') window.app?.addTodo()"
1906
+ style="margin-bottom:0"
1907
+ />
1908
+ <button class="btn" onclick="window.app?.addTodo()">Add</button>
1909
+ </div>
1910
+ <div id="todoList"></div>
1911
+ <p id="todoCount" class="text-muted">0 items</p>
1912
+ </div>
1913
+
1914
+ <!-- Toggle Example -->
1915
+ <div class="card">
1916
+ <h2 class="mb-1">Toggle Example</h2>
1917
+ <button
1918
+ id="toggleBtn"
1919
+ class="btn btn--secondary"
1920
+ onclick="window.app?.toggle()"
1921
+ >Inactive</button>
1922
+ <div id="toggleContent" class="mt-1" style="margin-top:1rem;display:none">
1923
+ <p class="text-success">This content is visible when active!</p>
1924
+ </div>
1925
+ </div>
1926
+ </div>
1927
+
1928
+ <!-- Simple Store Implementation -->
1929
+ <script>
1930
+ (function() {
1931
+ // Create a simple reactive store
1932
+ function createStore(initialState) {
1933
+ let state = { ...initialState };
1934
+ const listeners = [];
1935
+ return {
1936
+ get() { return state; },
1937
+ set(newState) {
1938
+ state = { ...state, ...newState };
1939
+ listeners.forEach(fn => fn(state));
1940
+ },
1941
+ subscribe(fn) {
1942
+ listeners.push(fn);
1943
+ fn(state); // Call immediately
1944
+ return () => listeners.splice(listeners.indexOf(fn), 1);
1945
+ }
1946
+ };
1947
+ }
1948
+
1949
+ // Initialize app store
1950
+ const appStore = createStore({
1951
+ count: 0,
1952
+ todos: [],
1953
+ isActive: false
1954
+ });
1955
+
1956
+ // App methods
1957
+ window.app = {
1958
+ increment() {
1959
+ const { count } = appStore.get();
1960
+ appStore.set({ count: count + 1 });
1961
+ },
1962
+ decrement() {
1963
+ const { count } = appStore.get();
1964
+ appStore.set({ count: Math.max(0, count - 1) });
1965
+ },
1966
+ reset() {
1967
+ appStore.set({ count: 0 });
1968
+ },
1969
+ toggle() {
1970
+ const { isActive } = appStore.get();
1971
+ appStore.set({ isActive: !isActive });
1972
+ },
1973
+ addTodo() {
1974
+ const input = document.getElementById('todoInput');
1975
+ const text = input.value.trim();
1976
+ if (!text) return;
1977
+ const { todos } = appStore.get();
1978
+ appStore.set({ todos: [...todos, { id: Date.now(), text, done: false }] });
1979
+ input.value = '';
1980
+ },
1981
+ toggleTodo(id) {
1982
+ const { todos } = appStore.get();
1983
+ appStore.set({
1984
+ todos: todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
1985
+ });
1986
+ },
1987
+ deleteTodo(id) {
1988
+ const { todos } = appStore.get();
1989
+ appStore.set({ todos: todos.filter(t => t.id !== id) });
1990
+ }
1991
+ };
1992
+
1993
+ // Update UI based on state
1994
+ function updateUI(state) {
1995
+ // Update counter
1996
+ const counterDisplay = document.getElementById('counterDisplay');
1997
+ if (counterDisplay) counterDisplay.textContent = 'Count: ' + state.count;
1998
+
1999
+ // Update todo count
2000
+ const todoCount = document.getElementById('todoCount');
2001
+ if (todoCount) todoCount.textContent = state.todos.length + ' items';
2002
+
2003
+ // Update toggle button
2004
+ const toggleBtn = document.getElementById('toggleBtn');
2005
+ if (toggleBtn) {
2006
+ toggleBtn.textContent = state.isActive ? 'Active' : 'Inactive';
2007
+ toggleBtn.className = 'btn ' + (state.isActive ? 'btn--success' : 'btn--secondary');
2008
+ }
2009
+
2010
+ // Show/hide toggle content
2011
+ const toggleContent = document.getElementById('toggleContent');
2012
+ if (toggleContent) toggleContent.style.display = state.isActive ? 'block' : 'none';
2013
+
2014
+ // Render todo list
2015
+ const list = document.getElementById('todoList');
2016
+ if (list) {
2017
+ list.innerHTML = state.todos.map(todo => \`
2018
+ <div style="display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0;border-bottom:1px solid var(--border)">
2019
+ <input type="checkbox" \${todo.done ? 'checked' : ''} onchange="window.app?.toggleTodo(\${todo.id})" />
2020
+ <span style="\${todo.done ? 'text-decoration:line-through;opacity:0.5' : ''}">\${todo.text}</span>
2021
+ <button onclick="window.app?.deleteTodo(\${todo.id})" style="margin-left:auto;background:none;border:none;color:var(--primary);cursor:pointer">\xD7</button>
2022
+ </div>
2023
+ \`).join('');
2024
+ }
2025
+ }
2026
+
2027
+ // Subscribe to store changes
2028
+ appStore.subscribe(updateUI);
2029
+ })();
2030
+ </script>
2031
+ </body>
2032
+ </html>`}var Xs="f9c3713";function Mo(t){return t}function No(t){return t}function zs(t,s){let a=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)a.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))a.push(m),c++}}return a}import _e from"fs";import ke from"path";function Dn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let a=Math.max(0,Math.round((s-t)/1000));if(a<60)return`${a}s ago`;if(a<3600)return`${Math.round(a/60)}m ago`;return`${Math.round(a/3600)}h ago`}function Oi(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Mn(t,s="stx"){let a=ke.resolve(t);for(let p=0;p<10;p++){let c=ke.join(a,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=ke.dirname(a);if(l===a)break;a=l}return null}var _n=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=_e.readFileSync(ke.join(t,"package.json"),"utf8"),a=JSON.parse(s)?.version;return typeof a==="string"?a:null}catch{return null}}function Mi(t,s=6){let a=ke.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of _n){let S=ke.join(u,w),E=Di(S);if(E!==null)p.push({name:w,version:E,dir:ke.relative(a,S)||S,nested:y>0})}let b;try{b=_e.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=ke.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=ke.join(S,x.name,"node_modules");if(_e.existsSync(R))l(R,y+1)}continue}let E=ke.join(S,"node_modules");if(_e.existsSync(E))l(E,y+1)}}let m=ke.join(a,"node_modules");if(_e.existsSync(m))l(m,0);return p}function _i(t){let s=[];for(let a of _n){let p=t.filter((m)=>m.name===a);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${a} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${a} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${a}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${a}/package.json' -exec grep -H '"version"' {} +`})}return s}async function mr(t={}){let s=t.cwd?ke.resolve(t.cwd):process.cwd(),a=t.resolve??Oi,p=Date.now(),c=[],l=a("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=a("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of _i(Mi(s)))c.push(y);let u=Mn(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=ke.join(u,"src/signals.ts"),g=[ke.join(u,"dist/index.js"),ke.join(u,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,b=Dn(y),w=g?Dn(g):null;if(b==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(b,p)}, dist ${Mt(w,p)})`});let S=ke.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=_e.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(y){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:c,ok:!c.some((y)=>y.status==="error")}}function hr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},a=["stx runtime resolution:"];for(let p of t.checks)if(a.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)a.push(` \u2192 ${p.fix}`);return a.push(""),a.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),a.join(`
2033
+ `)}export{zs,Hs,Vs,Us,gr,Ws,qs,Xs,Mo,No,mr,hr,wn,xn,Sn};