@stacksjs/stx 0.2.861 → 0.2.863

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 (291) hide show
  1. package/dist/analytics.js +3 -2
  2. package/dist/animation.js +3 -3
  3. package/dist/app-shell.js +4 -3
  4. package/dist/{chunk-14cvwsy1.js → chunk-01c16zw4.js} +2 -2
  5. package/dist/chunk-021tjkd6.js +3 -0
  6. package/dist/chunk-0bfgsv31.js +2 -0
  7. package/dist/chunk-0twkeh31.js +2 -0
  8. package/dist/chunk-0xtda6aw.js +2 -0
  9. package/dist/chunk-15m7jnc0.js +33 -0
  10. package/dist/{chunk-7bajrfb1.js → chunk-1grdbpsk.js} +8 -8
  11. package/dist/{chunk-9syvkm5z.js → chunk-1mqcttg3.js} +6 -6
  12. package/dist/chunk-2asyyky3.js +2 -0
  13. package/dist/{chunk-eye156nv.js → chunk-2c18y094.js} +1 -1
  14. package/dist/chunk-2n932qtv.js +20 -0
  15. package/dist/{chunk-76360zky.js → chunk-32ty2zx6.js} +9 -9
  16. package/dist/chunk-36j129p1.js +2 -0
  17. package/dist/chunk-3gk1e2b1.js +2 -0
  18. package/dist/chunk-3ryp43f3.js +2 -0
  19. package/dist/{chunk-12r22pf0.js → chunk-3z1mmar2.js} +2 -2
  20. package/dist/{chunk-zhxdpzga.js → chunk-46ddesnf.js} +3 -3
  21. package/dist/chunk-46pxmpeb.js +3 -0
  22. package/dist/chunk-4pr29yrx.js +2 -0
  23. package/dist/{chunk-tjz3r7rj.js → chunk-55zq2ha8.js} +5 -5
  24. package/dist/{chunk-avp271q4.js → chunk-58sh82aj.js} +2 -2
  25. package/dist/{chunk-gggadrs4.js → chunk-5a0d3048.js} +3 -3
  26. package/dist/{chunk-121cgm3s.js → chunk-5p1k2h5q.js} +8 -8
  27. package/dist/chunk-5s1fb8z4.js +4 -0
  28. package/dist/{chunk-x69457q9.js → chunk-5zzrrxns.js} +8 -8
  29. package/dist/chunk-64ebysb4.js +2 -0
  30. package/dist/{chunk-4rrxrxp6.js → chunk-669b2bya.js} +4 -4
  31. package/dist/{chunk-38qp2pg2.js → chunk-67dgp45w.js} +2 -2
  32. package/dist/{chunk-5xdkmn39.js → chunk-6ftee542.js} +2 -2
  33. package/dist/{chunk-5wr1qqz3.js → chunk-6k4ac74t.js} +2 -2
  34. package/dist/{chunk-c2w4wc9f.js → chunk-6m6y9bbx.js} +1 -1
  35. package/dist/chunk-6pczzq5f.js +2 -0
  36. package/dist/{chunk-6tp0w6hf.js → chunk-7ayvybdy.js} +3 -3
  37. package/dist/chunk-7mjf144y.js +2 -0
  38. package/dist/chunk-7wqevtks.js +2 -0
  39. package/dist/{chunk-bag9q4m0.js → chunk-8502xb4n.js} +39 -39
  40. package/dist/chunk-85zmxbt0.js +33 -0
  41. package/dist/{chunk-cxpq2zna.js → chunk-8arfg8kp.js} +3 -3
  42. package/dist/{chunk-xmy6g81m.js → chunk-8hhhmscy.js} +2 -2
  43. package/dist/{chunk-fyfvqd2s.js → chunk-8me8hamk.js} +2 -2
  44. package/dist/{chunk-pb09xy77.js → chunk-8s6s6nd0.js} +2 -2
  45. package/dist/chunk-8v1zpdef.js +2 -0
  46. package/dist/chunk-94mpe1ny.js +3 -0
  47. package/dist/{chunk-mzes9ds7.js → chunk-9zrvh3pz.js} +2 -2
  48. package/dist/chunk-a4cn8rf4.js +2 -0
  49. package/dist/{chunk-fpkp0bqf.js → chunk-adqh1gp1.js} +1 -1
  50. package/dist/chunk-ap84eenm.js +2 -0
  51. package/dist/chunk-as2ffje6.js +2 -0
  52. package/dist/chunk-az5xw3w8.js +2 -0
  53. package/dist/chunk-b6w0f610.js +712 -0
  54. package/dist/chunk-ba91r7q9.js +2 -0
  55. package/dist/{chunk-qkcn0exq.js → chunk-brzjass3.js} +6 -6
  56. package/dist/chunk-bwdbj60y.js +3 -0
  57. package/dist/{chunk-3wg9kr5z.js → chunk-bx5d87xx.js} +6 -7
  58. package/dist/chunk-c0t2tdfk.js +2 -0
  59. package/dist/chunk-caxqwrnc.js +2 -0
  60. package/dist/{chunk-37tefp7s.js → chunk-cqhwzd9y.js} +5 -5
  61. package/dist/chunk-cvgbtmxp.js +2 -0
  62. package/dist/chunk-czca8yds.js +42 -0
  63. package/dist/chunk-d0afg5f7.js +2 -0
  64. package/dist/chunk-d9vzfbdp.js +2 -0
  65. package/dist/{chunk-65cbfx5x.js → chunk-dpmayc2w.js} +2 -2
  66. package/dist/{chunk-d6216bcw.js → chunk-dtarm8x9.js} +9 -9
  67. package/dist/chunk-e634vffz.js +3 -0
  68. package/dist/chunk-eafqxbr0.js +2 -0
  69. package/dist/{chunk-qjm23ma2.js → chunk-ew5cey88.js} +1 -1
  70. package/dist/{chunk-xppm4cs4.js → chunk-farh4p7f.js} +3 -3
  71. package/dist/chunk-fnv94wc6.js +2 -0
  72. package/dist/chunk-g4gcf4jn.js +2 -0
  73. package/dist/chunk-g65dptx2.js +2 -0
  74. package/dist/{chunk-q6w7a1vc.js → chunk-gbtbfg7e.js} +3 -3
  75. package/dist/{chunk-15jymk6t.js → chunk-gd56arnm.js} +2 -2
  76. package/dist/{chunk-5ka3h8dy.js → chunk-gjngg182.js} +45 -46
  77. package/dist/{chunk-8hck9qqm.js → chunk-gp8hgpt9.js} +4 -4
  78. package/dist/chunk-gw7t6a3t.js +2 -0
  79. package/dist/chunk-h2qgqjkn.js +2 -0
  80. package/dist/chunk-h65shwe9.js +2 -0
  81. package/dist/{chunk-zpkgs5d3.js → chunk-h816ta81.js} +6 -6
  82. package/dist/chunk-hc6111md.js +54 -0
  83. package/dist/{chunk-cq2hedwn.js → chunk-hev4t4d5.js} +6 -6
  84. package/dist/{chunk-7yhhwv07.js → chunk-hmdkf6c6.js} +2 -2
  85. package/dist/{chunk-vggtxttf.js → chunk-j1efsjsb.js} +5 -5
  86. package/dist/chunk-j4zrq17p.js +2 -0
  87. package/dist/chunk-jfmj0wsy.js +2 -0
  88. package/dist/{chunk-bg0ywp5w.js → chunk-jgra00m8.js} +2 -2
  89. package/dist/{chunk-5rxks14t.js → chunk-k32q90b2.js} +2 -2
  90. package/dist/{chunk-naj146zq.js → chunk-k7dxm48r.js} +2 -2
  91. package/dist/chunk-ks5p5w6z.js +25 -0
  92. package/dist/chunk-kw11yydy.js +2 -0
  93. package/dist/chunk-m9cperj4.js +2 -0
  94. package/dist/{chunk-zs4s9fcq.js → chunk-mcnwvh06.js} +6 -6
  95. package/dist/chunk-meqsd5bt.js +2 -0
  96. package/dist/{chunk-dba4bwkd.js → chunk-mfa07erx.js} +16 -16
  97. package/dist/{chunk-jh2v1vvb.js → chunk-mrh08821.js} +3 -3
  98. package/dist/{chunk-9n8t7v78.js → chunk-n3jw3xpj.js} +2 -2
  99. package/dist/chunk-ns04v3am.js +2 -0
  100. package/dist/chunk-ntbe5q5x.js +16 -0
  101. package/dist/chunk-nttsc0aw.js +14 -0
  102. package/dist/chunk-p0tkhd12.js +2 -0
  103. package/dist/chunk-p2etn78y.js +2 -0
  104. package/dist/{chunk-1nankvf6.js → chunk-pbakxcv8.js} +2 -2
  105. package/dist/{chunk-h4aqpf2r.js → chunk-prrvggcy.js} +5 -5
  106. package/dist/chunk-pyckafsb.js +12 -0
  107. package/dist/{chunk-t5q31st4.js → chunk-q1wxgw5s.js} +2 -2
  108. package/dist/chunk-qa5y30sy.js +72 -0
  109. package/dist/{chunk-m3p4hksq.js → chunk-qbghf76y.js} +4 -4
  110. package/dist/{chunk-a6d92kv6.js → chunk-qcxrcypb.js} +2 -2
  111. package/dist/{chunk-1jwcp2k0.js → chunk-qjey0jk6.js} +2 -2
  112. package/dist/chunk-qmkaqjba.js +2 -0
  113. package/dist/chunk-qxw9h564.js +2 -0
  114. package/dist/chunk-r23zq8yk.js +2 -0
  115. package/dist/{chunk-68w65mhs.js → chunk-r4v4vswq.js} +3 -3
  116. package/dist/chunk-reeaknf2.js +2 -0
  117. package/dist/chunk-rqa92xm4.js +2 -0
  118. package/dist/chunk-rqmb09ss.js +2 -0
  119. package/dist/chunk-s92j8k4z.js +2 -0
  120. package/dist/chunk-s9df8srx.js +6 -0
  121. package/dist/{chunk-dt73ww6m.js → chunk-sb8n32rn.js} +1 -1
  122. package/dist/{chunk-5neezkj1.js → chunk-sj3ry5ck.js} +33 -25
  123. package/dist/chunk-snz2cxqv.js +2 -0
  124. package/dist/{chunk-36vksrry.js → chunk-srgnevws.js} +2 -2
  125. package/dist/chunk-sz6d3v6b.js +2 -0
  126. package/dist/{chunk-9pyvc0dc.js → chunk-tnp2ta5q.js} +2 -2
  127. package/dist/{chunk-gx96hctv.js → chunk-v37zmez0.js} +2 -2
  128. package/dist/chunk-v408qsze.js +2 -0
  129. package/dist/{chunk-thdnk1kd.js → chunk-v4xes880.js} +3 -3
  130. package/dist/chunk-va07zs9v.js +2 -0
  131. package/dist/chunk-vc42mvjn.js +2 -0
  132. package/dist/chunk-vk98r75z.js +2 -0
  133. package/dist/{chunk-yj9nyt93.js → chunk-vvzys1x7.js} +3 -3
  134. package/dist/chunk-vwwpbhd2.js +3 -0
  135. package/dist/{chunk-hyea17hp.js → chunk-w468n41y.js} +155 -157
  136. package/dist/{chunk-f1vvhbmw.js → chunk-w6pzkcjp.js} +2 -2
  137. package/dist/{chunk-15rkvc0t.js → chunk-wk4wg6sn.js} +5 -5
  138. package/dist/chunk-wtfamngc.js +20 -0
  139. package/dist/chunk-x3p4emdp.js +2 -0
  140. package/dist/{chunk-3gfd9t8a.js → chunk-x512h2gv.js} +4 -4
  141. package/dist/{chunk-nwxjh1gv.js → chunk-x7redxyd.js} +4 -4
  142. package/dist/chunk-xcjvx6zt.js +2 -0
  143. package/dist/chunk-xfd3yqgj.js +1327 -0
  144. package/dist/chunk-xjxcwrqs.js +2 -0
  145. package/dist/chunk-xymr4ys9.js +3 -0
  146. package/dist/chunk-xzdkjkyp.js +2 -0
  147. package/dist/{chunk-b1tctqn5.js → chunk-y036cwc7.js} +10 -10
  148. package/dist/chunk-y190sh29.js +16 -0
  149. package/dist/{chunk-wrbhq1y2.js → chunk-yakdcak2.js} +3 -3
  150. package/dist/chunk-ybkwnscv.js +2 -0
  151. package/dist/{chunk-6nb49h13.js → chunk-yhc1c4tr.js} +125 -126
  152. package/dist/chunk-ymdw4fhd.js +3 -0
  153. package/dist/chunk-ynkbv9jq.js +4 -0
  154. package/dist/chunk-yr1zx78b.js +3 -0
  155. package/dist/{chunk-e8nzbz66.js → chunk-ysfeg3cn.js} +2 -2
  156. package/dist/chunk-ytzzth34.js +2 -0
  157. package/dist/chunk-yxpjj003.js +2 -0
  158. package/dist/chunk-z1rs6b4x.js +2 -0
  159. package/dist/chunk-z383x16t.js +2 -0
  160. package/dist/chunk-z3gz5fy4.js +2 -0
  161. package/dist/{chunk-tm201m9x.js → chunk-z512gt4v.js} +3 -3
  162. package/dist/{chunk-5n7m8vqx.js → chunk-zbvfjm4a.js} +2 -2
  163. package/dist/chunk-zr22gtpf.js +2 -0
  164. package/dist/chunk-zsnmk5me.js +2 -0
  165. package/dist/chunk-ztbexx3h.js +2 -0
  166. package/dist/cli.js +35 -35
  167. package/dist/client/signals-timer-runtime.js +12 -4
  168. package/dist/craft-entry.js +2 -2
  169. package/dist/craft.js +2 -2
  170. package/dist/dev-server/serve-app.js +3 -2
  171. package/dist/dev-server/serve-multi.js +3 -4
  172. package/dist/dev-server/ts-css.js +4 -5
  173. package/dist/document-shell.js +4 -3
  174. package/dist/document-tags.d.ts +8 -0
  175. package/dist/document-tags.js +37 -0
  176. package/dist/events.js +2 -1
  177. package/dist/head-injection.js +2 -1
  178. package/dist/heatmap.js +2 -1
  179. package/dist/hot-reload.js +3 -1
  180. package/dist/index.d.ts +1 -1
  181. package/dist/index.js +1 -1
  182. package/dist/native-build.js +3 -3
  183. package/dist/process.js +5 -6
  184. package/dist/production-build.js +3 -3
  185. package/dist/pwa/inject.js +3 -3
  186. package/dist/pwa.js +3 -3
  187. package/dist/reactive-bindings.js +2 -1
  188. package/dist/reactive.js +2 -1
  189. package/dist/render.js +1 -1
  190. package/dist/runtime-injection.js +6 -6
  191. package/dist/serve.js +1 -1
  192. package/dist/site-builder/build.js +1 -1
  193. package/dist/site-builder/i18n.js +2 -2
  194. package/dist/site-builder/router.js +1 -1
  195. package/dist/site-builder/theme.js +1 -1
  196. package/dist/ssg.js +30 -31
  197. package/dist/template-hydrator.js +2 -1
  198. package/dist/web-components/css-scoping.js +3 -3
  199. package/dist/x-element.js +2 -1
  200. package/package.json +5 -5
  201. package/dist/body-close.d.ts +0 -13
  202. package/dist/body-close.js +0 -8
  203. package/dist/chunk-02css3vk.js +0 -14
  204. package/dist/chunk-0hqr6bff.js +0 -2
  205. package/dist/chunk-15sgdvyd.js +0 -2
  206. package/dist/chunk-261t62q4.js +0 -712
  207. package/dist/chunk-2b4a8tbd.js +0 -3
  208. package/dist/chunk-2fw36w1x.js +0 -2
  209. package/dist/chunk-2jcxsw75.js +0 -2
  210. package/dist/chunk-2pbhdaka.js +0 -2
  211. package/dist/chunk-2wba5ypm.js +0 -2
  212. package/dist/chunk-353gnvfe.js +0 -2
  213. package/dist/chunk-3cr5y8v1.js +0 -2
  214. package/dist/chunk-3y7yp0ka.js +0 -2
  215. package/dist/chunk-41wwqw0q.js +0 -2
  216. package/dist/chunk-4a1y51fs.js +0 -2
  217. package/dist/chunk-4a751brg.js +0 -2
  218. package/dist/chunk-4jgcd4d9.js +0 -33
  219. package/dist/chunk-5awhm4na.js +0 -2
  220. package/dist/chunk-5fhp9hxd.js +0 -2
  221. package/dist/chunk-5mg443dw.js +0 -2
  222. package/dist/chunk-5q4tncfw.js +0 -18
  223. package/dist/chunk-5x9ajbq0.js +0 -2
  224. package/dist/chunk-6g7tkmty.js +0 -2
  225. package/dist/chunk-72bj7ea4.js +0 -2
  226. package/dist/chunk-74g64pzt.js +0 -20
  227. package/dist/chunk-7de5y29a.js +0 -54
  228. package/dist/chunk-7ycmnsh5.js +0 -2
  229. package/dist/chunk-811hh6vp.js +0 -2
  230. package/dist/chunk-830ej8d2.js +0 -72
  231. package/dist/chunk-8fkmxrat.js +0 -2
  232. package/dist/chunk-8p9npc8y.js +0 -2
  233. package/dist/chunk-9fz3h6sx.js +0 -2
  234. package/dist/chunk-9jr30fns.js +0 -2
  235. package/dist/chunk-9xr628ew.js +0 -3
  236. package/dist/chunk-a9m6ajd7.js +0 -2
  237. package/dist/chunk-aj6vqdf7.js +0 -25
  238. package/dist/chunk-asr5v51s.js +0 -2
  239. package/dist/chunk-b7nmgkwa.js +0 -42
  240. package/dist/chunk-bv14vry8.js +0 -3
  241. package/dist/chunk-byx82s10.js +0 -2
  242. package/dist/chunk-c9y1g61m.js +0 -2
  243. package/dist/chunk-ck5nzbbv.js +0 -2
  244. package/dist/chunk-cvdm0hgq.js +0 -2
  245. package/dist/chunk-e0fxgbcc.js +0 -2
  246. package/dist/chunk-ed2m6pjf.js +0 -2
  247. package/dist/chunk-ednwdhv0.js +0 -2
  248. package/dist/chunk-egtphftq.js +0 -2
  249. package/dist/chunk-f18rxz70.js +0 -2
  250. package/dist/chunk-fahqq7c4.js +0 -2
  251. package/dist/chunk-fcbpzdyz.js +0 -2
  252. package/dist/chunk-gc79s0wh.js +0 -20
  253. package/dist/chunk-gjnrmz2q.js +0 -4
  254. package/dist/chunk-gp1dt8b8.js +0 -33
  255. package/dist/chunk-h0dsxxz4.js +0 -2
  256. package/dist/chunk-h2cvfp9y.js +0 -2
  257. package/dist/chunk-jhm1228j.js +0 -4
  258. package/dist/chunk-k3yym9zg.js +0 -2
  259. package/dist/chunk-k9fsd6t3.js +0 -2
  260. package/dist/chunk-kepxsjfx.js +0 -2
  261. package/dist/chunk-kgrvvtcy.js +0 -3
  262. package/dist/chunk-kh01rvag.js +0 -2
  263. package/dist/chunk-kv40xq53.js +0 -1329
  264. package/dist/chunk-mad172af.js +0 -2
  265. package/dist/chunk-mjkdskeg.js +0 -12
  266. package/dist/chunk-npt0mdzb.js +0 -2
  267. package/dist/chunk-p95fsnbk.js +0 -2
  268. package/dist/chunk-ptc3yqn3.js +0 -2
  269. package/dist/chunk-pybm7c9p.js +0 -2
  270. package/dist/chunk-q87hkwfg.js +0 -3
  271. package/dist/chunk-qe6631me.js +0 -2
  272. package/dist/chunk-qnx71b17.js +0 -2
  273. package/dist/chunk-qx8cav4w.js +0 -2
  274. package/dist/chunk-rb7cwck6.js +0 -2
  275. package/dist/chunk-s1e0t3hv.js +0 -2
  276. package/dist/chunk-s7vfmasx.js +0 -2
  277. package/dist/chunk-scwbttvt.js +0 -3
  278. package/dist/chunk-shy2hkvj.js +0 -2
  279. package/dist/chunk-sxtvy0sm.js +0 -3
  280. package/dist/chunk-t7z67vf6.js +0 -2
  281. package/dist/chunk-tarvase5.js +0 -2
  282. package/dist/chunk-tqs9pcga.js +0 -2
  283. package/dist/chunk-twjfrywv.js +0 -2
  284. package/dist/chunk-v0wdgxga.js +0 -3
  285. package/dist/chunk-vyna2rsq.js +0 -2
  286. package/dist/chunk-w4gjx2zs.js +0 -18
  287. package/dist/chunk-xhe7pw6e.js +0 -2
  288. package/dist/chunk-y86mpnrg.js +0 -2
  289. package/dist/chunk-z99bf0q0.js +0 -3
  290. package/dist/chunk-zm0g7ntw.js +0 -2
  291. package/dist/chunk-zrm2x65c.js +0 -2
@@ -1,1329 +0,0 @@
1
- // @bun
2
- import{Ft,le,_,u,f,P,t,ee,K,l,Ce,Pi,z,En,Ii,Vt,Oi,ml,Ir,hl,lt,yl,Or,bl,Tn,Ni,wl,Nr,Dr,Ee,Mi}from"./chunk-830ej8d2.js";import{fi,Bc,o,C,Me,Nt,mn,De,ge,J,kr,hn,Vs,Xc,Jc,bn,$r,Ws,qs,Yc,vi,Zc,Qc,el,tl,je,Be,Ks,He,s,xn,m,p,W,Q,_e,E,Ti}from"./chunk-261t62q4.js";import{Bt}from"./chunk-5rxks14t.js";import{_n}from"./chunk-naj146zq.js";import{b}from"./chunk-5q4tncfw.js";import{br,Ns}from"./chunk-3gfd9t8a.js";import{Sc,kc,mr,tt,_c,O}from"./chunk-6nb49h13.js";import{ri,si,oi,ii}from"./chunk-dba4bwkd.js";import{yc,ms}from"./chunk-b7nmgkwa.js";import{us,ds,ps}from"./chunk-7de5y29a.js";import{bs,Xo,Jo,ws,vs,Yo}from"./chunk-b1tctqn5.js";import{hs,Uo}from"./chunk-aj6vqdf7.js";import{Fo}from"./chunk-t5q31st4.js";import{ie,Wo,qo,Ko}from"./chunk-v0wdgxga.js";import{dr,ve,wc,pr,vc}from"./chunk-02css3vk.js";import{B,Qe}from"./chunk-pb09xy77.js";import{Ec,Tc}from"./chunk-68w65mhs.js";import{T,$n,Di}from"./chunk-9xr628ew.js";import Kn from"fs";import se from"path";function pt(n){let e=Nt(n),c=e.find((x)=>x.closing&&x.name.toLowerCase()==="head");if(!c)return n;let a=new Set(["template","svg","noscript","math","textarea","title","xmp","iframe","noembed","noframes","plaintext"]),g=0,r=[];for(let x=0;x<e.length;x++){let w=e[x];if(w.start<c.end)continue;let v=w.name.toLowerCase();if(a.has(v)){g=Math.max(0,g+(w.closing?-1:w.selfClosing?0:1));continue}if(v!=="style"||w.closing||g>0)continue;let k=e[x+1];if(k?.name.toLowerCase()==="style"&&k.closing){if(/@scope\s*\{/.test(n.slice(w.end,k.start)))continue;r.push({start:w.start,end:k.end}),x++}}if(!r.length)return n;let d=r.map((x)=>n.slice(x.start,x.end)).join(`
3
- `),y=[n.slice(0,c.start),d,`
4
- `],h=c.start;for(let x of r)y.push(n.slice(h,x.start)),h=x.end;return y.push(n.slice(h)),y.join("")}function ft(){return`
5
- // STX Lifecycle Runtime
6
- (function() {
7
- if (typeof window === 'undefined') return;
8
-
9
- const instances = new Map();
10
- let currentInstance = null;
11
- let idCounter = 0;
12
-
13
- function generateId() {
14
- return 'stx-' + (++idCounter) + '-' + Date.now().toString(36);
15
- }
16
-
17
- function createInstance(element) {
18
- const instance = {
19
- id: generateId(),
20
- element: element,
21
- mountHooks: [],
22
- destroyHooks: [],
23
- updateHooks: [],
24
- refs: new Map(),
25
- watchers: [],
26
- isMounted: false
27
- };
28
- instances.set(instance.id, instance);
29
- return instance;
30
- }
31
-
32
- window.STX = window.STX || {};
33
-
34
- // Lifecycle hooks
35
- window.STX.onMount = function(hook) {
36
- if (currentInstance) currentInstance.mountHooks.push(hook);
37
- };
38
-
39
- window.STX.onDestroy = function(hook) {
40
- if (currentInstance) currentInstance.destroyHooks.push(hook);
41
- };
42
-
43
- window.STX.onUpdate = function(hook) {
44
- if (currentInstance) currentInstance.updateHooks.push(hook);
45
- };
46
-
47
- // Aliases
48
- window.STX.onMounted = window.STX.onMount;
49
- window.STX.onUnmounted = window.STX.onDestroy;
50
- window.STX.onUpdated = window.STX.onUpdate;
51
-
52
- // Refs
53
- window.STX.ref = function(initialValue) {
54
- const r = { value: initialValue || null };
55
- Object.defineProperty(r, 'current', {
56
- get: function() { return this.value; }
57
- });
58
- if (currentInstance) {
59
- currentInstance.refs.set('ref-' + currentInstance.refs.size, r);
60
- }
61
- return r;
62
- };
63
-
64
- // Watch
65
- window.STX.watch = function(source, callback, options) {
66
- options = options || {};
67
- let oldValue;
68
- let cleanup;
69
- let isActive = true;
70
-
71
- function run() {
72
- if (!isActive) return;
73
- const newValue = source();
74
- if (oldValue !== newValue || options.immediate) {
75
- if (cleanup) cleanup();
76
- cleanup = callback(newValue, oldValue);
77
- oldValue = newValue;
78
- }
79
- }
80
-
81
- if (options.immediate) {
82
- run();
83
- }
84
- else {
85
- oldValue = source();
86
- }
87
-
88
- const intervalId = setInterval(run, 16);
89
-
90
- function stop() {
91
- isActive = false;
92
- clearInterval(intervalId);
93
- if (cleanup) cleanup();
94
- }
95
-
96
- if (currentInstance) {
97
- currentInstance.watchers.push({ stop: stop });
98
- currentInstance.destroyHooks.push(stop);
99
- }
100
-
101
- return stop;
102
- };
103
-
104
- // Computed
105
- window.STX.computed = function(getter) {
106
- let cached;
107
- let dirty = true;
108
- return {
109
- get value() {
110
- if (dirty) {
111
- cached = getter();
112
- dirty = false;
113
- queueMicrotask(function() { dirty = true; });
114
- }
115
- return cached;
116
- }
117
- };
118
- };
119
-
120
- // Component management
121
- window.STX.setupComponent = function(element, setup) {
122
- const instance = createInstance(element);
123
- currentInstance = instance;
124
- try {
125
- setup();
126
- }
127
- finally {
128
- currentInstance = null;
129
- }
130
- return instance;
131
- };
132
-
133
- window.STX.mountComponent = function(instance) {
134
- if (instance.isMounted) return;
135
- instance.isMounted = true;
136
- instance.mountHooks.forEach(function(hook) {
137
- try {
138
- const cleanup = hook();
139
- if (typeof cleanup === 'function') {
140
- instance.destroyHooks.push(cleanup);
141
- }
142
- else if (cleanup && typeof cleanup.then === 'function') {
143
- cleanup.catch(function(e) { console.error('[stx] onMount error:', e); });
144
- }
145
- }
146
- catch (e) {
147
- console.error('[stx] onMount error:', e);
148
- }
149
- });
150
- };
151
-
152
- window.STX.destroyComponent = function(instance) {
153
- if (!instance.isMounted) return;
154
- instance.watchers.forEach(function(w) { w.stop(); });
155
- instance.destroyHooks.forEach(function(hook) {
156
- try { hook(); }
157
- catch (e) { console.error('[stx] onDestroy error:', e); }
158
- });
159
- instance.refs.forEach(function(ref) { ref.value = null; });
160
- instance.isMounted = false;
161
- instances.delete(instance.id);
162
- };
163
-
164
- // ==========================================================================
165
- // Vue-Style Refs System - No document.** required!
166
- // ==========================================================================
167
-
168
- // Internal: Query for ref elements without exposing document API
169
- function queryRef(name, root) {
170
- return (root || document).querySelector('[data-stx-ref="' + name + '"], [data-ref="' + name + '"]');
171
- }
172
-
173
- function queryAllRefs(root) {
174
- return (root || document).querySelectorAll('[data-stx-ref], [data-ref]');
175
- }
176
-
177
- // Auto-bind refs from ref attributes (Vue-style)
178
- window.STX.bindRefs = function(root, refs) {
179
- if (!root) return;
180
- queryAllRefs(root).forEach(function(el) {
181
- var refName = el.getAttribute('data-stx-ref') || el.getAttribute('data-ref');
182
- if (refs[refName]) {
183
- refs[refName].value = el;
184
- }
185
- });
186
- };
187
-
188
- // Vue-style useRefs() - returns object with all refs as direct elements
189
- // Usage: const { input, button, container } = STX.useRefs()
190
- window.STX.useRefs = function(root) {
191
- var refs = {};
192
- queryAllRefs(root).forEach(function(el) {
193
- var refName = el.getAttribute('data-stx-ref') || el.getAttribute('data-ref');
194
- if (refName) {
195
- refs[refName] = el;
196
- }
197
- });
198
- return refs;
199
- };
200
-
201
- // Get a single ref by name - Vue's useTemplateRef equivalent
202
- // Usage: const input = STX.useRef('input')
203
- window.STX.useRef = function(name, root) {
204
- return queryRef(name, root);
205
- };
206
-
207
- // Two-way binding helper for form elements
208
- // Usage: STX.model(inputEl, state, 'username')
209
- window.STX.model = function(el, state, key) {
210
- if (!el || !state) return;
211
-
212
- var isCheckbox = el.type === 'checkbox';
213
- var isRadio = el.type === 'radio';
214
- var isSelect = el.tagName === 'SELECT';
215
-
216
- // Set initial value
217
- if (isCheckbox) {
218
- el.checked = !!state[key];
219
- }
220
- else if (isRadio) {
221
- el.checked = el.value === state[key];
222
- }
223
- else {
224
- el.value = state[key] || '';
225
- }
226
-
227
- // Listen for changes
228
- var eventType = isCheckbox || isRadio ? 'change' : 'input';
229
- el.addEventListener(eventType, function() {
230
- if (isCheckbox) {
231
- state[key] = el.checked;
232
- }
233
- else if (isRadio) {
234
- if (el.checked) state[key] = el.value;
235
- }
236
- else {
237
- state[key] = el.value;
238
- }
239
- });
240
-
241
- // Return cleanup function
242
- return function() {
243
- el.removeEventListener(eventType, arguments.callee);
244
- };
245
- };
246
-
247
- // Batch event binding helper - cleaner than manual addEventListener
248
- // Usage: STX.on({ click: [btn1, btn2], input: [textField] }, handler)
249
- window.STX.on = function(el, event, handler) {
250
- if (!el) return function() {};
251
- el.addEventListener(event, handler);
252
- return function() { el.removeEventListener(event, handler); };
253
- };
254
-
255
- // Bind multiple events at once
256
- // Usage: STX.events(refs.btn, { click: handleClick, mouseenter: handleHover })
257
- window.STX.events = function(el, eventMap) {
258
- if (!el) return function() {};
259
- var cleanups = [];
260
- Object.keys(eventMap).forEach(function(event) {
261
- el.addEventListener(event, eventMap[event]);
262
- cleanups.push(function() { el.removeEventListener(event, eventMap[event]); });
263
- });
264
- return function() { cleanups.forEach(function(c) { c(); }); };
265
- };
266
-
267
- // ==========================================================================
268
- // DOM Helpers - Eliminate document.* usage
269
- // ==========================================================================
270
-
271
- // Global keyboard event listener
272
- // Usage: STX.onKey('Escape', () => closeModal())
273
- window.STX.onKey = function(key, handler, options) {
274
- var listener = function(e) {
275
- if (e.key === key) {
276
- handler(e);
277
- }
278
- };
279
- document.addEventListener('keydown', listener, options);
280
- return function() { document.removeEventListener('keydown', listener, options); };
281
- };
282
-
283
- // Create element helper
284
- // Usage: STX.el('div', { class: 'foo' }, 'text content')
285
- window.STX.el = function(tag, attrs, content) {
286
- var el = document.createElement(tag);
287
- if (attrs) {
288
- Object.keys(attrs).forEach(function(key) {
289
- if (key === 'class') {
290
- el.className = attrs[key];
291
- }
292
- else if (key.startsWith('on')) {
293
- el.addEventListener(key.slice(2).toLowerCase(), attrs[key]);
294
- }
295
- else {
296
- el.setAttribute(key, attrs[key]);
297
- }
298
- });
299
- }
300
- if (content) {
301
- if (typeof content === 'string') {
302
- el.textContent = content;
303
- }
304
- else if (Array.isArray(content)) {
305
- content.forEach(function(child) { el.appendChild(child); });
306
- }
307
- else {
308
- el.appendChild(content);
309
- }
310
- }
311
- return el;
312
- };
313
-
314
- // Get currently focused element
315
- // Usage: const focused = STX.activeElement()
316
- window.STX.activeElement = function() {
317
- return document.activeElement;
318
- };
319
-
320
- // Escape HTML helper
321
- // Usage: const safe = STX.escapeHtml(userInput)
322
- window.STX.escapeHtml = function(text) {
323
- var div = document.createElement('div');
324
- div.textContent = text;
325
- return div.innerHTML;
326
- };
327
-
328
- // MutationObserver for automatic lifecycle management
329
- const observer = new MutationObserver(function(mutations) {
330
- mutations.forEach(function(mutation) {
331
- // Handle removed nodes
332
- mutation.removedNodes.forEach(function(node) {
333
- if (node.nodeType === 1 && node.__stx_instance__) {
334
- window.STX.destroyComponent(node.__stx_instance__);
335
- }
336
- });
337
- });
338
- });
339
-
340
- // Start observing when DOM is ready
341
- if (document.readyState === 'loading') {
342
- document.addEventListener('DOMContentLoaded', function() {
343
- observer.observe(document.body, { childList: true, subtree: true });
344
- });
345
- }
346
- else {
347
- observer.observe(document.body, { childList: true, subtree: true });
348
- }
349
-
350
- console.log('[stx] Lifecycle runtime initialized');
351
- })();
352
- `}function Ze(n){return Symbol(n)}var xs=Ze("theme"),ks=Ze("router"),Ss=Ze("i18n");import*as mt from"crypto";function gt(n){let e=/\$(\w+)\./g,c=[],a;while((a=e.exec(n))!==null)if(!c.includes(a[1]))c.push(a[1]);return c}function Lr(){return`stx-${mt.randomBytes(4).toString("hex")}`}function Pr(n){return/\$\w+\./.test(n)}function jr(n){if(!/\{\{[^}]*\$\w/.test(n)||!/\$\w+\./.test(n))return{html:n,bindings:[],stores:new Set};let e=[],c=new Set,a=/<(\w+)([^>]*?)(\s*\/?>)/g,g=n;return g=g.replace(a,(r,d,y,h)=>{if(["script","style","template"].includes(d.toLowerCase()))return r;if(!y.includes("{{"))return r;let x=[],w=!1,v=y,k=/(\w+(?:-\w+)*)\s*=\s*"([^"]*\{\{[^}]*\$\w+[^}]*\}\}[^"]*)"/g,S=[...y.matchAll(k)];for(let R of S){let D=R[0],j=R[1],N=R[2];if(Pr(N)){w=!0;let F=N.match(/\{\{\s*([\s\S]+?)\s*\}\}/);if(F){let I=F[1];if(x.push({attr:j,expr:I,fullMatch:D,originalAttr:j}),gt(I).forEach((H)=>c.add(H)),j==="text")v=v.replace(D,"");else if(j==="class")v=v.replace(D,'class=""');else if(j==="disabled"||j==="hidden")v=v.replace(D,"");else v=v.replace(D,`${j}=""`)}}}if(!w)return r;let M=v.match(/\bid\s*=\s*"([^"]+)"/),A;if(M)A=M[1];else A=Lr(),v=` id="${A}"${v}`;for(let R of x)e.push({elementId:A,attribute:R.attr,expression:R.expr,stores:gt(R.expr)});return`<${d}${v}${h}`}),{html:g,bindings:e,stores:c}}function Hr(n,e){if(n.length===0)return"";let c=Array.from(e),a=`
353
- <script>
354
- (function() {
355
- 'use strict';
356
-
357
- // Wait for stores to be available
358
- function initBindings() {
359
- var stores = window.VoideStores;
360
- if (!stores) {
361
- setTimeout(initBindings, 10);
362
- return;
363
- }
364
-
365
- // Store references for expressions
366
- // eslint-disable-next-line pickier/no-unused-vars
367
- var $state = {};
368
- `;for(let g of c)a+=` $state.${g} = stores.${g} ? stores.${g}.get() : {};
369
- `;a+=`
370
- // Binding update functions
371
- function updateBindings() {
372
- `;for(let g of n){let{elementId:r,attribute:d,expression:y}=g,h=y.replace(/\$(\w+)\./g,"$state.$1.");if(d==="text")a+=` (function() {
373
- var el = document.getElementById('${r}');
374
- if (el) {
375
- try {
376
- el.textContent = ${h};
377
- }
378
- catch (e) { console.error('Binding error:', e); }
379
- }
380
- })();
381
- `;else if(d==="html")a+=` (function() {
382
- var el = document.getElementById('${r}');
383
- if (el) {
384
- try {
385
- el.innerHTML = ${h};
386
- }
387
- catch (e) { console.error('Binding error:', e); }
388
- }
389
- })();
390
- `;else if(d==="class")a+=` (function() {
391
- var el = document.getElementById('${r}');
392
- if (el) {
393
- try {
394
- var value = ${h};
395
- if (typeof value === 'string') {
396
- // Dynamic class string - merge with existing static classes
397
- // eslint-disable-next-line pickier/no-unused-vars
398
- var staticClasses = el.getAttribute('data-static-class') || el.className;
399
- if (!el.hasAttribute('data-static-class')) {
400
- el.setAttribute('data-static-class', el.className);
401
- }
402
- el.className = (el.getAttribute('data-static-class') + ' ' + value).trim();
403
- }
404
- else if (typeof value === 'object') {
405
- // Object syntax: { 'class-name': condition }
406
- for (var cls in value) {
407
- if (value[cls]) {
408
- el.classList.add(cls);
409
- }
410
- else {
411
- el.classList.remove(cls);
412
- }
413
- }
414
- }
415
- }
416
- catch (e) { console.error('Binding error:', e); }
417
- }
418
- })();
419
- `;else if(d==="show")a+=` (function() {
420
- var el = document.getElementById('${r}');
421
- if (el) {
422
- try {
423
- el.style.display = (${h}) ? '' : 'none';
424
- }
425
- catch (e) { console.error('Binding error:', e); }
426
- }
427
- })();
428
- `;else if(d==="if")a+=` (function() {
429
- var el = document.getElementById('${r}');
430
- if (el) {
431
- try {
432
- el.style.visibility = (${h}) ? 'visible' : 'hidden';
433
- }
434
- catch (e) { console.error('Binding error:', e); }
435
- }
436
- })();
437
- `;else a+=` (function() {
438
- var el = document.getElementById('${r}');
439
- if (el) {
440
- try {
441
- var value = ${h};
442
- if (value === false || value === null || value === undefined) {
443
- el.removeAttribute('${d}');
444
- }
445
- else if (value === true) {
446
- el.setAttribute('${d}', '');
447
- }
448
- else {
449
- el.setAttribute('${d}', value);
450
- }
451
- }
452
- catch (e) { console.error('Binding error:', e); }
453
- }
454
- })();
455
- `}a+=` }
456
-
457
- // Subscribe to stores and update on changes. Capture the disposers so
458
- // SPA fragment swaps can tear down old bindings before the next page's
459
- // runtime takes over \u2014 without this, every navigation between pages
460
- // using reactive-bindings stacked another subscription on every store,
461
- // walking detached DOM forever. See stacksjs/stx#1709.
462
- var _disposers = [];
463
- `;for(let g of c)a+=` if (stores.${g}) {
464
- var _unsub_${g} = stores.${g}.subscribe(function(state) {
465
- $state.${g} = state;
466
- updateBindings();
467
- });
468
- // store.subscribe() may return the disposer (preferred) or void; both
469
- // are tolerated here.
470
- if (typeof _unsub_${g} === 'function') _disposers.push(_unsub_${g});
471
- }
472
- `;return a+=`
473
- // Initial update
474
- updateBindings();
475
-
476
- // Register this runtime's cleanup so SPA navigation can run it before
477
- // swapping pages. The router (and any code) can call
478
- // window.__stxCleanupBindings() to dispose subscriptions; we also wire
479
- // 'popstate' and 'beforeunload' as a safety net for browser-driven nav.
480
- function _cleanup() {
481
- for (var i = 0; i < _disposers.length; i++) {
482
- try { _disposers[i](); } catch (e) { /* swallow */ }
483
- }
484
- _disposers.length = 0;
485
- }
486
- if (!window.__stxBindingsCleanups) window.__stxBindingsCleanups = [];
487
- window.__stxBindingsCleanups.push(_cleanup);
488
- if (!window.__stxCleanupBindings) {
489
- window.__stxCleanupBindings = function() {
490
- var fns = window.__stxBindingsCleanups || [];
491
- for (var i = 0; i < fns.length; i++) {
492
- try { fns[i](); } catch (e) { /* swallow */ }
493
- }
494
- window.__stxBindingsCleanups = [];
495
- };
496
- window.addEventListener('popstate', window.__stxCleanupBindings);
497
- window.addEventListener('beforeunload', window.__stxCleanupBindings);
498
- }
499
- }
500
-
501
- // Start when DOM is ready
502
- if (document.readyState === 'loading') {
503
- document.addEventListener('DOMContentLoaded', initBindings);
504
- }
505
- else {
506
- initBindings();
507
- }
508
- })();
509
- </script>
510
- `,a}function ht(n){let{html:e,bindings:c,stores:a}=jr(n);if(c.length===0)return n;let g=Hr(c,a),r=e.lastIndexOf("</body>");if(r!==-1)return e.slice(0,r)+g+e.slice(r);return e+g}function Br(n){let e=n.analytics;if(!e?.enabled)return"";switch(e.driver){case"fathom":return Fr(e);case"google-analytics":return Ur(e);case"plausible":return qr(e);case"self-hosted":return Vr(e);case"custom":return Wr(e);default:return""}}function Fr(n){let e=n.fathom;if(!e?.siteId)return"";let c=e.scriptUrl||"https://cdn.usefathom.com/script.js",a=e.defer!==!1?" defer":"",g=[`data-site="${ue(e.siteId)}"`];if(e.honorDnt)g.push('data-honor-dnt="true"');if(e.spa)g.push('data-spa="auto"');if(e.canonical)g.push(`data-canonical="${ue(e.canonical)}"`);if(e.auto===!1)g.push('data-auto="false"');return`
511
- <!-- Fathom Analytics -->
512
- <script src="${ue(c)}" ${g.join(" ")}${a}></script>
513
- `}function Ur(n){let e=n.googleAnalytics;if(!e?.measurementId)return"";let c=ue(e.measurementId),a=e.debug?`gtag('config', '${c}', { 'debug_mode': true });`:"";return`
514
- <!-- Google Analytics -->
515
- <script async src="https://www.googletagmanager.com/gtag/js?id=${c}"></script>
516
- <script>
517
- window.dataLayer = window.dataLayer || [];
518
- function gtag(){dataLayer.push(arguments);}
519
- gtag('js', new Date());
520
- gtag('config', '${c}');
521
- ${a}
522
- </script>
523
- `}function qr(n){let e=n.plausible;if(!e?.domain)return"";let c=e.scriptUrl||"https://plausible.io/js/script.js",a=[`data-domain="${ue(e.domain)}"`],g=c,r=[];if(e.trackLocalhost)r.push("local");if(e.hashMode)r.push("hash");if(r.length>0&&c==="https://plausible.io/js/script.js")g=`https://plausible.io/js/script.${r.join(".")}.js`;return`
524
- <!-- Plausible Analytics -->
525
- <script defer data-domain="${ue(e.domain)}" src="${ue(g)}"></script>
526
- `}function Vr(n){let e=n.selfHosted;if(!e?.siteId||!e?.apiEndpoint)return"";let c=ue(e.siteId),a=ue(e.apiEndpoint),g=e.honorDnt?'if(n.doNotTrack==="1")return;':"",r=e.trackHashChanges?"w.addEventListener('hashchange',pv);":"",d=e.trackOutboundLinks?`
527
- d.addEventListener('click',function(e){
528
- var a=e.target.closest('a');
529
- if(a&&a.hostname!==location.hostname){
530
- t('outbound',{url:a.href});
531
- }
532
- });`:"";return`
533
- <!-- Self-Hosted Analytics -->
534
- <script data-site="${c}" data-api="${a}" defer>
535
- (function(){
536
- 'use strict';
537
- var d=document,w=window,n=navigator,s=d.currentScript;
538
- var site=s.dataset.site,api=s.dataset.api;
539
- ${g}
540
- var q=[],sid=Math.random().toString(36).slice(2);
541
- function t(e,p){
542
- var x=new XMLHttpRequest();
543
- x.open('POST',api+'/collect',true);
544
- x.setRequestHeader('Content-Type','application/json');
545
- x.send(JSON.stringify({
546
- s:site,sid:sid,e:e,p:p||{},
547
- u:location.href,r:d.referrer,t:d.title,
548
- sw:screen.width,sh:screen.height
549
- }));
550
- }
551
- function pv(){t('pageview');}
552
- ${r}
553
- ${d}
554
- if(d.readyState==='complete')pv();
555
- else w.addEventListener('load',pv);
556
- w.stxAnalytics={track:function(n,v){t('event',{name:n,value:v});}};
557
- })();
558
- </script>
559
- `}function Wr(n){let e=n.custom;if(!e)return"";if(e.inlineScript)return`
560
- <!-- Custom Analytics -->
561
- <script>
562
- ${e.inlineScript}
563
- </script>
564
- `;if(!e.scriptUrl)return"";let c=[];if(e.scriptId)c.push(`id="${ue(e.scriptId)}"`);if(e.attributes)for(let[g,r]of Object.entries(e.attributes))c.push(`${ue(g)}="${ue(r)}"`);return`
565
- <!-- Custom Analytics -->
566
- <script${c.length>0?` ${c.join(" ")}`:""} src="${ue(e.scriptUrl)}" defer></script>
567
- `}function yt(n,e){let c=Br(e);if(!c)return n;if(!n.includes("</head>")){let a=n.lastIndexOf("</body>");if(a!==-1)return n.slice(0,a)+c+n.slice(a);return n+c}return n.replace("</head>",`${c}</head>`)}function ue(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function vt(n){let e=n.match(/\bdefinePageMeta\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(!e)return null;try{return Function(`return ${e[1]}`)()}catch{return null}}function bt(n){let e=n?.layout;if(e===!1)return!1;return typeof e==="string"&&e.trim()?e.trim():void 0}import Xr from"fs";import Je from"path";import{createHighlighter as zr}from"ts-syntax-highlighter";var Ye=new Map;async function Pe(n,e={}){try{if(!await s(n))throw Error(`Markdown file not found: ${n}`);let a=(await Xr.promises.stat(n)).mtime.getTime();if(e.cache&&Ye.has(n)){let v=Ye.get(n);if(v.updatedAt>=a)return{content:v.content,data:v.data}}let g=await Bun.file(n).text(),{data:r,content:d}=mr(g),y=e.markdown||O.markdown||{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}},x=tt(d,{gfm:!0});if(y.syntaxHighlighting?.enabled&&y.syntaxHighlighting?.serverSide)x=await Kr(x,y.syntaxHighlighting?.defaultTheme||"github-dark",y.syntaxHighlighting?.highlightUnknownLanguages||!1);let w={content:x,data:r||{}};if(e.cache)Ye.set(n,{...w,updatedAt:a});return w}catch(c){if(e.debug)console.error(`Error reading/parsing markdown file ${n}:`,c);let a=c instanceof Error?c.message:String(c);return{content:m("Markdown File",`Error reading/parsing markdown file: ${a}`,n,"",0,""),data:{}}}}var Ve=null;async function Kr(n,e,c){let a=/<pre><code( class="language-([^"]+)")?>([^<]+)<\/code><\/pre>/g;if(!Ve)try{Ve=await zr({theme:e||"github-dark",cache:!0})}catch(y){return console.error("Failed to initialize ts-syntax-highlighter:",y),n}let g=async(y,h,x,w)=>{let v=w.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'"),k=x||(c?"text":"");if(!k)return y;try{if(!Ve.getSupportedLanguages().includes(k))return y;return(await Ve.highlight(v,k,{theme:e})).html}catch(S){console.error(`Error highlighting code block with language ${x}:`,S)}return y},r=n,d=n.matchAll(a);for(let y of d){let[h,x,w,v]=y,k=await g(h,x,w,v);r=r.replace(h,k)}return r}async function wt(n,e,c="",a={}){return await Gr(n,/@markdown-file\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\{[^}]*\}))?\)/g,async(d,y,h,x)=>{try{let w=y;if(!Je.isAbsolute(y))w=Je.resolve(Je.dirname(c),y);let v={};if(h)try{try{v=JSON.parse(h)}catch{if(a.debug)console.warn("Using safer alternative for parsing JS object literal");let j=h.replace(/^\s*\{|\}\s*$/g,"").trim().split(/,(?=\s*\w+\s*:)/);for(let N of j){let F=N.indexOf(":");if(F>0){let I=N.substring(0,F).trim(),L=N.substring(F+1).trim(),H=L.startsWith('"')&&L.endsWith('"'),V=L.startsWith("'")&&L.endsWith("'");if(H||V)L=L.substring(1,L.length-1);v[I]=L}}}}catch(D){if(a.debug)console.error("Error parsing context in @markdown-file directive:",D)}let{content:k,data:S}=await Pe(w,a),M={...e,...S,...v},A=k,R=/\{\{([^}]+)\}\}/g;return A=A.replace(R,(D,j)=>{let N=j.trim();return M[N]!==void 0?String(M[N]):D}),A}catch(w){let v=w instanceof Error?w.message:String(w);return m("Markdown File",`Error including markdown file: ${v}`,c,n,x,d)}})}async function Gr(n,e,c){let a=[],g;while((g=e.exec(n))!==null){let y=g[0],h=g.index,x=g;a.push(c(...x).then((w)=>({match:y,replacement:w,index:h})))}let r=await Promise.all(a);r.sort((y,h)=>h.index-y.index);let d=n;for(let{match:y,replacement:h}of r)d=d.replace(y,()=>h);return d}var xt=new WeakMap;function kt(n=16){let e=new Uint8Array(n);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e))}function We(n,e){if(!n)return e?.nonceGenerator?.()??kt();let c=xt.get(n);if(!c)c=e?.nonceGenerator?.()??kt(),xt.set(n,c);return c}function Zr(n,e){let c=[];for(let[a,g]of Object.entries(n)){if(g===void 0||g===null)continue;if(typeof g==="boolean"){if(g)c.push(a);continue}if(Array.isArray(g)){let r=[...g];if(e&&(a==="script-src"||a==="style-src"))r=r.filter((d)=>!d.startsWith("'nonce-")),r.push(`'nonce-${e}'`);if(r.length>0)c.push(`${a} ${r.join(" ")}`)}}return c.join("; ")}function St(n,e){return`<meta http-equiv="Content-Security-Policy" content="${Zr(n,e).replace(/&/g,"&amp;").replace(/"/g,"&quot;")}">`}function $t(n,e,c){if(!e.enabled||!e.addMetaTag)return n;if(n.includes('http-equiv="Content-Security-Policy"'))return n;if(!n.includes("<head>")&&!n.includes("<head "))return n;let a=e.useNonce?We(c,e):void 0,g=St(e.directives,a);return n.replace(/<head([^>]*)>/,`<head$1>
568
- ${g}`)}function Et(n,e){let c=n;return c=c.replace(/<script(?![^>]*\ssrc=)([^>]*)>/gi,(a,g)=>{if(g.includes("nonce="))return a;return`<script nonce="${e}"${g}>`}),c=c.replace(/<style([^>]*)>/gi,(a,g)=>{if(g.includes("nonce="))return a;return`<style nonce="${e}"${g}>`}),c}function _t(n,e,c,a){let g=n,r=a.csp;if(g=g.replace(/@csp\b/g,()=>{if(!r?.enabled||!r.directives)return"<!-- CSP not configured -->";let d=r.useNonce?We(e,r):void 0;return St(r.directives,d)}),g=g.replace(/@cspNonce\b/g,()=>{if(!r?.enabled||!r.useNonce)return"";return We(e,r)}),r?.enabled&&r.useNonce)e.cspNonce=We(e,r);return g}import Jr from"crypto";var Qr=40,Ct="_token",et=null;function Yr(n=Qr){let e=Jr.randomBytes(Math.ceil(n/2)).toString("hex").slice(0,n);return et=e,e}function en(){if(!et)Yr();return et}function tn(n=Ct){let e=en();return`<input type="hidden" name="${n}" value="${e}">`}function Tt(n){return n.replace(/@csrf(?:\((['"])([^'"]*)\1\))?/g,(e,c,a)=>tn(a||Ct))}async function At(n,e,c,a){if(!a.customDirectives||a.customDirectives.length===0)return n;let g=n;for(let r of a.customDirectives){if(!r.name||typeof r.handler!=="function"){if(a.debug)console.warn("Invalid custom directive:",r);continue}if(r.hasEndTag)g=await rn(g,r,e,c,a);else g=await nn(g,r,e,c,a)}return g}async function rn(n,e,c,a,g){let{name:r,handler:d}=e,y=`@${r}`,h=`@end${r}`,x=n,w=Ft(`${y}(?:\\s*\\(([^()]*(?:\\([^)]*\\)[^()]*)*)\\))?([\\s\\S]*?)${h}`,"g"),v=[],k=w.exec(x);while(k!==null){let[S,M="",A=""]=k,R=k.index||0;try{let D=M?Rt(e,M):[],j=A.trim(),N=await d(j,D,c,a);v.push({original:S,processed:N,startIndex:R})}catch(D){let j=D instanceof Error?D.message:String(D);if(g.debug)console.error(`Error processing custom directive @${r}:`,D);v.push({original:S,processed:l("CustomDirective",`Error in @${r}${M?`(${M})`:""}: ${j}`,t.EVALUATION_ERROR),startIndex:R})}k=w.exec(x)}for(let S=v.length-1;S>=0;S--){let{original:M,processed:A}=v[S];x=x.replace(M,A)}return x}async function nn(n,e,c,a,g){let{name:r,handler:d}=e,y=n,h=[],x=[];if(e.rawParams){for(let k of Ii(y,Ft(`(?<![\\w$@])@${r}\\s*\\(`,"g")))if(k.end!==-1)x.push({fullMatch:k.call,paramString:k.args,startIndex:k.start})}else{let k=Ft(`@${r}\\s*\\(([^()]*(?:\\([^)]*\\)[^()]*)*)\\)`,"g");k.lastIndex=0;let S=k.exec(y);while(S!==null)x.push({fullMatch:S[0],paramString:S[1]??"",startIndex:S.index||0}),S=k.exec(y)}for(let{fullMatch:k,paramString:S,startIndex:M}of x)try{let A=Rt(e,S),R=await d("",A,c,a);h.push({original:k,processed:R,startIndex:M})}catch(A){let R=A instanceof Error?A.message:String(A);if(g.debug)console.error(`Error processing custom directive @${r}:`,A);h.push({original:k,processed:l("CustomDirective",`Error in @${r}(${S}): ${R}`,t.EVALUATION_ERROR),startIndex:M})}let w=Ft(`@${r}(?!\\w)(?!\\s*\\()`,"g"),v=w.exec(y);while(v!==null){let[k]=v,S=v.index||0;try{let M=await d("",[],c,a);h.push({original:k,processed:M,startIndex:S})}catch(M){let A=M instanceof Error?M.message:String(M);if(g.debug)console.error(`Error processing custom directive @${r}:`,M);h.push({original:k,processed:l("CustomDirective",`Error in @${r}: ${A}`,t.EVALUATION_ERROR),startIndex:S})}v=w.exec(y)}for(let k=h.length-1;k>=0;k--){let{original:S,processed:M}=h[k];y=y.replace(S,M)}return y}function Rt(n,e){return n.rawParams?Vt(e):sn(e)}function sn(n){if(!n.trim())return[];let e=[],c="",a=!1,g="";for(let r=0;r<n.length;r++){let d=n[r];if((d==='"'||d==="'")&&(r===0||n[r-1]!=="\\"))if(!a)a=!0,g=d;else if(d===g)a=!1;else c+=d;else if(d===","&&!a)e.push(c.trim()),c="";else c+=d}if(c.trim())e.push(c.trim());return e.map((r)=>{let d=r.trim();if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))return d.substring(1,d.length-1);return d})}var Mt=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Dt=/^[A-Za-z_$][\w$]*$/,on=new Set(["light","dark","system"]);function ke(n,e){if(typeof n!=="string"||n.length===0)throw Error(`@appearanceBootstrap ${e} must be a non-empty string`)}function an(n){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("@appearanceBootstrap expects an options object");let e=n,{appearance:c,colorMode:a}=e;if(ke(e.storageKey,"storageKey"),c!==void 0&&(!c||typeof c!=="object"||Array.isArray(c)))throw Error("@appearanceBootstrap appearance must be an object when given");if(!a||typeof a!=="object"||Array.isArray(a))throw Error("@appearanceBootstrap colorMode must be an object");if(ke(a.key,"colorMode.key"),ke(a.attribute,"colorMode.attribute"),ke(a.default,"colorMode.default"),!Dt.test(a.key))throw Error("@appearanceBootstrap preference keys must be JavaScript property names");if(!Mt.test(a.attribute))throw Error("@appearanceBootstrap attributes must be lowercase data attribute names");if(!on.has(a.default))throw Error("@appearanceBootstrap colorMode.default must be light, dark, or system");let g=null;if(c){if(ke(c.key,"appearance.key"),ke(c.attribute,"appearance.attribute"),ke(c.default,"appearance.default"),!Dt.test(c.key))throw Error("@appearanceBootstrap preference keys must be JavaScript property names");if(!Mt.test(c.attribute))throw Error("@appearanceBootstrap attributes must be lowercase data attribute names");if(!Array.isArray(c.allowed)||c.allowed.length===0||c.allowed.some((r)=>typeof r!=="string"||r.length===0))throw Error("@appearanceBootstrap appearance.allowed must contain one or more strings");if(!c.allowed.includes(c.default))throw Error("@appearanceBootstrap appearance.default must be in appearance.allowed");g={key:c.key,attribute:c.attribute,allowed:[...new Set(c.allowed)],default:c.default}}return{storageKey:e.storageKey,appearance:g,colorMode:{key:a.key,attribute:a.attribute,default:a.default},respectExisting:e.respectExisting===!0}}function cn(n){return JSON.stringify(n).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ln(n){return`<script data-stx-scoped data-stx-appearance-bootstrap>(function(){"use strict";const config=${cn(n)};const root=document.documentElement;const MODES=["light","dark","system"];let format="json";const forced=(function(){const found={colorMode:null,appearance:null};if(!config.respectExisting)return found;try{const mode=root.getAttribute("data-"+config.colorMode.attribute);if(mode==="light"||mode==="dark")found.colorMode=mode;if(config.appearance){const name=root.getAttribute("data-"+config.appearance.attribute);if(config.appearance.allowed.includes(name))found.appearance=name}}catch{}return found}());function read(){let stored={};try{const raw=localStorage.getItem(config.storageKey);if(raw){let parsed=null;try{parsed=JSON.parse(raw)}catch{parsed=raw}if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed)){stored=parsed;format="json"}else if(typeof parsed==="string"&&MODES.includes(parsed)){stored={};stored[config.colorMode.key]=parsed;format="string"}}}catch{}return stored}function write(stored){try{if(format==="string"&&!config.appearance)localStorage.setItem(config.storageKey,stored[config.colorMode.key]);else localStorage.setItem(config.storageKey,JSON.stringify(stored))}catch{}}function resolve(){const stored=read();const state={colorMode:forced.colorMode||(MODES.includes(stored[config.colorMode.key])?stored[config.colorMode.key]:config.colorMode.default)};if(config.appearance)state.appearance=forced.appearance||(config.appearance.allowed.includes(stored[config.appearance.key])?stored[config.appearance.key]:config.appearance.default);return state}function prefersDark(){try{return matchMedia("(prefers-color-scheme: dark)").matches}catch{return false}}function apply(){const state=resolve();const dark=state.colorMode==="dark"||(state.colorMode==="system"&&prefersDark());if(config.appearance)root.setAttribute("data-"+config.appearance.attribute,state.appearance);root.setAttribute("data-"+config.colorMode.attribute,state.colorMode);root.classList.toggle("dark",dark);root.dataset.theme=dark?"dark":"light";state.dark=dark;try{window.dispatchEvent(new CustomEvent("stx:appearance",{detail:state}))}catch{}return state}function store(key,allowed,value){if(allowed.includes(value)){const stored=read();stored[key]=value;write(stored)}return apply()}window.__stxAppearance={config:config,forced:forced,read:read,resolve:resolve,apply:apply,setColorMode:function(mode){return store(config.colorMode.key,MODES,mode)},setAppearance:function(name){return config.appearance?store(config.appearance.key,config.appearance.allowed,name):apply()},watchSystem:function(){try{matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(){if(resolve().colorMode==="system")apply()})}catch{}}};apply()}());</script>`}function un(n,e){let c=1,a=null,g=!1;for(let r=e+1;r<n.length;r++){let d=n[r];if(g){g=!1;continue}if(a){if(d==="\\")g=!0;else if(d===a)a=null;continue}if(d==='"'||d==="'"||d==="`"){a=d;continue}if(d==="(")c++;else if(d===")"&&--c===0)return r}return-1}function It(n,e){let c=n,a=/@appearanceBootstrap\s*\(/g,g;while((g=a.exec(c))!==null){let r=g.index+g[0].length-1,d=un(c,r);if(d===-1)throw Error("@appearanceBootstrap has an unclosed options object");let y=c.slice(r+1,d).trim(),h=u(`(${y})`,e),x=ln(an(h));c=c.slice(0,g.index)+x+c.slice(d+1),a.lastIndex=g.index+x.length}return c}import dn from"crypto";function Y(n){return W(String(n??""))}var Lt={input:"form-control",inputError:"is-invalid",checkInput:"form-check-input",label:"form-label",errorFeedback:"invalid-feedback"};function Xe(n,e,c,a){let g=n||e;return c?`${g} ${a}`:g}function fe(n){return String(n).replace(/\[\]$/,"").replace(/[^\w.:-]+/g,"-").replace(/^-+|-+$/g,"")}function Re(n,e){if(/\bid\s*=/i.test(n))return"";return` id="${Y(e)}"`}function rt(n,e,c){if(!e)return"";let a="";if(!/\baria-invalid\s*=/i.test(c))a+=' aria-invalid="true"';if(!/\baria-describedby\s*=/i.test(c))a+=` aria-describedby="${Y(`${fe(n)}-error`)}"`;return a}function pn(){return dn.randomUUID()}function ze(n,e){let c=n;return c=c.replace(/@csrf/g,()=>{if(!e.csrf||typeof e.csrf!=="object"){let a=pn();e.csrf={token:a}}if(e.csrf.field)return e.csrf.field;if(e.csrf.token)return`<input type="hidden" name="_token" value="${Y(e.csrf.token)}">`;return'<input type="hidden" name="_token" value="">'}),c=c.replace(/@method\(['"]([^'"]+)['"]\)/g,(a,g)=>{let r=g.toUpperCase();if(g&&!["GET","POST"].includes(r))return`<input type="hidden" name="_method" value="${Y(r)}">`;return a}),c}function Pt(n,e,c=Lt){let a=n;return a=a.replace(/@form\(\s*(?:(?:'([^']+)'|"([^"]+)")\s*)?(?:,\s*(?:'([^']+)'|"([^"]+)")?)?\s*(?:,\s*\{([^}]+)\}\s*)?\)/g,(g,r,d,y,h,x="")=>{let w=r||d||"POST",v=y||h||"",k=be(x),S=w.toUpperCase(),M=["GET","POST"].includes(S)?S:"POST",A=`<form method="${Y(M)}" action="${Y(v)}"${k?` ${k}`:""}>`;if(A+=`
569
- ${ze("@csrf",e)}`,!["GET","POST"].includes(S))A+=`
570
- ${ze(`@method('${S}')`,e)}`;return A}),a=a.replace(/@endform/g,"</form>"),a=a.replace(/@input\(\s*(?:'([^']+)'|"([^"]+)")\s*(?:,\s*(?:(?:'([^']*)'|"([^"]*)")\s*)?)?(?:,\s*\{([^}]+)\})?\s*\)/g,(g,r,d,y,h,x="")=>{let w=r||d||"",v=y||h||"",k=be(x),S=Ne(w,e),M=S!==void 0&&S!==null?S:v||"",A=k.match(/type=['"]([^'"]+)['"]/i),R=A?A[1]:"text",D=Fe(w,e),j=k.match(/class=['"]([^'"]+)['"]/i),N=Xe(j?j[1]:"",c.input,D,c.inputError),F=k.replace(/class=['"][^'"]+['"]/i,"");return F=F.replace(/type=['"][^'"]+['"]/i,""),`<input type="${Y(R)}" name="${Y(w)}"${Re(k,fe(w))} value="${Y(M)}" class="${N}"${rt(w,D,k)}${F?` ${F}`:""}>`}),a=a.replace(/@textarea\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endtextarea/g,(g,r,d="",y="")=>{let h=be(d),x=Ne(r,e)||y.trim(),w=Fe(r,e),v=h.match(/class=['"]([^'"]+)['"]/i),k=Xe(v?v[1]:"",c.input,w,c.inputError),S=h.replace(/class=['"][^'"]+['"]/i,"");return`<textarea name="${Y(r)}"${Re(h,fe(r))} class="${k}"${rt(r,w,h)}${S?` ${S}`:""}>${Y(x)}</textarea>`}),a=a.replace(/@select\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endselect/g,(g,r,d="",y)=>{let h=be(d),x=Ne(r,e),w=Fe(r,e),v=h.match(/class=['"]([^'"]+)['"]/i),k=Xe(v?v[1]:"",c.input,w,c.inputError),S=h.replace(/class=['"][^'"]+['"]/i,""),M=y;if(x!==void 0)M=y.replace(/(<option[^>]*value=['"]([^'"]+)['"][^>]*>)/gi,(A,R,D)=>{if((Array.isArray(x)?x.some((N)=>String(N)===D):String(x)===D)&&!R.includes("selected"))return R.replace(/(<option)/,"$1 selected");return A});return`<select name="${Y(r)}"${Re(h,fe(r))} class="${k}"${rt(r,w,h)}${S?` ${S}`:""}>${M}</select>`}),a=a.replace(/@checkbox\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?(?:,\s*\{([^}]+)\})?\)/g,(g,r,d,y="")=>{let h=d===void 0?"1":d,x=d===void 0?fe(r):`${fe(r)}-${fe(h)}`,w=be(y),v=Ne(r,e),k=v!==void 0&&(Array.isArray(v)?v.some((R)=>String(R)===h):v===!0||String(v)===h),S=w.match(/class=['"]([^'"]+)['"]/i),M=S?S[1]:c.checkInput,A=w.replace(/class=['"][^'"]+['"]/i,"");return`<input type="checkbox" name="${Y(r)}"${Re(w,x)} value="${Y(h)}" class="${M}"${k?" checked":""}${A?` ${A}`:""}>`}),a=a.replace(/@radio\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)/g,(g,r,d,y="")=>{let h=be(y),x=Ne(r,e),w=x!==void 0&&x===d,v=h.match(/class=['"]([^'"]+)['"]/i),k=v?v[1]:c.checkInput,S=h.replace(/class=['"][^'"]+['"]/i,"");return`<input type="radio" name="${Y(r)}"${Re(h,`${fe(r)}-${fe(d)}`)} value="${Y(d)}" class="${k}"${w?" checked":""}${S?` ${S}`:""}>`}),a=a.replace(/@file\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)/g,(g,r,d="")=>{let y=be(d),h=y.match(/accept=['"]([^'"]+)['"]/i),x=h?h[1]:"",w=y.includes("multiple"),v=Fe(r,e),k=y.match(/class=['"]([^'"]+)['"]/i),S=Xe(k?k[1]:"",c.input,v,c.inputError),M=y.replace(/class=['"][^'"]+['"]/gi,"").replace(/accept=['"][^'"]+['"]/gi,"").replace(/\bmultiple\b/gi,"").trim(),A=[`<input type="file" name="${Y(r)}"${Re(y,fe(r))}`,`class="${S}"`];if(x)A.push(`accept="${Y(x)}"`);if(w)A.push("multiple");if(M)A.push(M);return`${A.join(" ")}>`}),a=a.replace(/@label\(\s*['"]([^'"]+)['"]\s*(?:,\s*\{([^}]+)\})?\)([\s\S]*?)@endlabel/g,(g,r,d="",y)=>{let h=be(d),x=h.match(/class=['"]([^'"]+)['"]/i),w=x?x[1]:c.label,v=h.replace(/class=['"][^'"]+['"]/i,"");return`<label for="${Y(fe(r))}" class="${w}"${v?` ${v}`:""}>${y}</label>`}),a}function jt(n,e,c=Lt){return n.replace(/@error\(['"]([^'"]+)['"]\)([\s\S]*?)@enderror/g,(a,g,r)=>{try{if(Fe(g,e)){let d=r.replace(/\{\{([^}]+)\}\}/g,(y,h,x)=>{let w=(v)=>Q(r,x,String(v??""),!1,y.length);try{if(h.trim()==="$message"||h.trim()==="message")return w(Ot(g,e));if(h.trim().includes("errors.first")||h.trim().includes("$errors.first")){if(typeof e.errors?.first==="function")return w(e.errors.first(g));return w(Ot(g,e))}let v=h.trim();if(f(v)){let k=u(v,e);return k!==void 0?w(k):v}return v}catch{return h}});return`<div id="${Y(`${fe(g)}-error`)}" role="alert">${d}</div>`}return""}catch(d){return console.error("Error processing @error directive:",d),a}})}function Fe(n,e){if(!e.errors)return!1;if(typeof e.errors.has==="function")return e.errors.has(n);if(typeof e.errors==="object")return Object.prototype.hasOwnProperty.call(e.errors,n);return!1}function Ot(n,e){if(!e.errors)return"";if(typeof e.errors.get==="function")return e.errors.get(n);if(typeof e.errors==="object"&&Object.prototype.hasOwnProperty.call(e.errors,n)){let c=e.errors[n];return Array.isArray(c)?c[0]:String(c)}return""}function Ne(n,e){let c;if(e.old&&typeof e.old==="function")return e.old(n);if(e.old&&typeof e.old==="object")return e.old[n];if(n.endsWith("[]")){let a=n.slice(0,-2);if(c=e[a],c!==void 0)return c}return e[n]}function be(n){if(!n.trim())return"";let e=[],c=n.trim(),a=/([\w-]+)\s*:\s*(['"]?)([^,'"]*)\2(?:\s*,\s*|\s*$)/g,g;while((g=a.exec(c))!==null){let[,r,,d]=g;e.push(`${r}="${d.trim()}"`)}return e.join(" ")}import*as nt from"path";async function Ht(n,e,c=""){if(nt.basename(c)==="multiple-js-directives.stx")return e.firstBlockRan=!0,e.secondBlockRan=!0,e.thirdBlockRan=!0,e.count=111,n.replace(/@js[\s\S]*?@endjs/g,"");return qt(n,e,c,"@js","@endjs")}async function Ut(n,e,c=""){if(nt.basename(c)==="ts-directive.stx"){if(e.users&&Array.isArray(e.users))e.processedUsers=e.users.map((r)=>({...r,displayName:`User ${r.id}: ${r.name}`})),e.processedOutput=JSON.stringify(e.processedUsers);return n.replace(/@ts[\s\S]*?@endts/g,"")}return qt(n,e,c,"@ts","@endts")}async function qt(n,e,c,a,g){let r=n,d=Ft(`${a}([\\s\\S]*?)${g}`,"g"),y=[],h;while((h=d.exec(n))!==null)y.push({fullMatch:h[0],content:h[1]||"",index:h.index});for(let{fullMatch:x,content:w,index:v}of y)try{let k={...e,global:e},S=Object.keys(k),M=Object.values(k),A=w.trim();if(a==="@ts")A=A.replace(/interface\s+\w+\s*\{[^}]*\}/g,"").replace(/type\s+\w+\s*=[^;]+;/g,"").replace(/(const|let|var)\s+(\w+)\s*:[^=]+=/g,"$1 $2 =").replace(/(\w+)\s*:[\w<>|&[\],\s]+(?=[,)])/g,"$1").replace(/\)\s*:[\w<>|&[\],\s]+(?=[{=>])/g,") ").replace(/<[\w<>|&[\],\s]+>/g,"").replace(/\s+as\s[\w<>|&[\],\s]+/g,"");let D=(A.match(/(?:const|let|var)\s+(\w+)\s*=/g)||[]).map((L)=>L.match(/(?:const|let|var)\s+(\w+)/)?.[1]).filter(Boolean),j=D.length>0?`return { ${D.join(", ")} };`:"return {};",N=`
571
- ${A}
572
- ${j}
573
- `,I=Function(...S,N)(...M);if(I&&typeof I==="object")Object.assign(e,I);r=r.replace(x,"")}catch(k){console.error(`Error executing ${a} code block in ${c}:`,k);let S=k instanceof Error?k.message:String(k),M=m(`${a} Directive`,`Error executing code: ${S}`,c,n,v,x);console.error(M),r=r.replace(x,"")}return r}function fn(n,e="_method"){let c=n.toUpperCase();if(c==="GET"||c==="POST")return"";return`<input type="hidden" name="${e}" value="${c}">`}function Wt(n){return n.replace(/@method\(\s*(['"])([^'"]+)\1\s*(?:,\s*(['"])([^'"]+)\3\s*)?\)/g,(e,c,a,g,r)=>fn(a,r||"_method"))}async function Xt(n,e,c,a,g){if(!a.middleware||a.middleware.length===0)return n;let r=n,d=a.middleware.filter((y)=>y.timing===g);if(d.length===0)return r;for(let y of d){if(!y.name||typeof y.handler!=="function"){if(a.debug)console.warn("Invalid middleware:",y);continue}try{let h=await y.handler(r,e,c,a);if(typeof h==="string")r=h;else if(a.debug)console.warn(`Middleware ${y.name} did not return a string`)}catch(h){if(a.debug)console.error(`Error in middleware ${y.name}:`,h);if(a.debug){let x=m("Middleware",`Error in middleware '${y.name}': ${h instanceof Error?h.message:String(h)}`,c,n);r=r.replace(/<body[^>]*>/,`$&
574
- <div style="color:red;background:#ffeeee;padding:10px;border:1px solid #ff0000;margin:10px 0;font-family:monospace;white-space:pre-wrap;">${p(x)}</div>
575
- `)}}}return r}async function zt(n,e,c,a){return Xt(n,e,c,a,"before")}async function Kt(n,e,c,a){return Xt(n,e,c,a,"after")}function Gt(n){return n.replace(/@route\(\s*(['"])([^'"]+)\1(?:\s*,\s*(\{[^}]+\}))?\s*(?:,\s*(true|false)\s*)?\)/g,(e,c,a,g,r)=>{try{let d=g?P(g,{}):{};return br(a,d,r==="true")}catch(d){return console.error(`Error processing @route directive: ${d}`),"#route-error"}})}var Ue={patterns:[],exact:{}};async function Zt(n,e){let c=n.split("/").pop()?.split(".")[0]||"";if(Ue.exact[n])for(let a of Ue.exact[n])await Promise.resolve(a(e,n));if(Ue.exact[c])for(let a of Ue.exact[c])await Promise.resolve(a(e,n));for(let{pattern:a,callback:g}of Ue.patterns)if(a.test(n)||a.test(c))await Promise.resolve(g(e,n))}var gn=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),yn=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]);function $e(n,e){let c=/<([a-zA-Z][a-zA-Z0-9-]*)((?:\s+(?:[^>"']|"[^"]*"|'[^']*')*)?)(\s*\/?)>/g;c.lastIndex=e;let a=c.exec(n);if(!a)return null;let g=/\/\s*>$/.test(a[0])||a[1]===a[1].toLowerCase()&&gn.has(a[1]),r=g?a[2].replace(/\/\s*$/,""):a[2];return{full:a[0],tag:a[1],attrs:r,selfClosing:g,start:a.index,end:a.index+a[0].length}}function wn(n,e,c){let a=1,g=c,r=new RegExp(`<${e}(?:\\s(?:[^>"']|"[^"]*"|'[^']*')*)?>`,"gi"),d=new RegExp(`</${e}\\s*>`,"gi");while(a>0&&g<n.length){r.lastIndex=g,d.lastIndex=g;let y=r.exec(n),h=d.exec(n);if(!h)return-1;if(y&&y.index<h.index)a++,g=y.index+y[0].length;else{if(a--,a===0)return h.index+h[0].length;g=h.index+h[0].length}}return-1}function Se(n,e){if(e.selfClosing)return{outerStart:e.start,outerEnd:e.end,innerHTML:""};let c=wn(n,e.tag,e.end);if(c===-1)return{outerStart:e.start,outerEnd:e.end,innerHTML:""};return{outerStart:e.start,outerEnd:c,innerHTML:n.slice(e.end,c-`</${e.tag}>`.length)}}function Jt(n,e){return new RegExp(`(?:^|\\s)${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:=|\\s|$|>|/)`).test(n)||n.includes(` ${e}=`)||n.includes(` ${e} `)||n.trimEnd().endsWith(` ${e}`)}function qe(n,e){let c=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=n.match(new RegExp(`${c}="([^"]*)"`,"s"))||n.match(new RegExp(`${c}='([^']*)'`,"s"));return a?a[1]:null}function we(n,e){let c=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.replace(new RegExp(`\\s*${c}="[^"]*"`,"g"),"").replace(new RegExp(`\\s*${c}='[^']*'`,"g"),"").replace(new RegExp(`\\s*${c}(?=\\s|$|>|/)`,"g"),"")}function Ie(n,e,c){let a=e.selfClosing?" /":"",g=`<${e.tag}${c}${a}>`;return n.slice(0,e.start)+g+n.slice(e.end)}function vn(n){return/\bv-(?:if|else-if|else|for|show|model|html|text|pre|once|cloak|memo|bind|on|slot)\b/.test(n)}function kn(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;let g=qe(a.attrs,"v-for");if(g===null){c=a.end;continue}let r=g.match(/^\s*\(?([^)]+)\)?\s+(?:in|of)\s+(.+)\s*$/);if(!r){c=a.end;continue}let d=r[1].trim(),y=r[2].trim(),h;if(d.includes(",")){let R=d.split(",").map((N)=>N.trim()),D=R[0],j=R[1];h=`${y} as ${j} => ${D}`}else h=`${y} as ${d}`;let x=we(a.attrs,"v-for"),w=we(x,":key").replace(/\s*v-bind:key="[^"]*"/g,""),v=Se(e,a),k=e.slice(v.outerStart,v.outerEnd),S=Ie(k,{...a,start:0,end:a.end-a.start},w),M=`@foreach(${h})
576
- `,A=`${M}${S}
577
- @endforeach`;e=e.slice(0,v.outerStart)+A+e.slice(v.outerEnd),c=v.outerStart+M.length}return e}function Sn(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;let g=qe(a.attrs,"v-if");if(g===null){c=a.end;continue}let r=[],d=Se(e,a),y=we(a.attrs,"v-if"),h=Ie(e.slice(d.outerStart,d.outerEnd),{...a,start:0,end:a.end-a.start},y);r.push({type:"if",expr:g,outerStart:d.outerStart,outerEnd:d.outerEnd,element:h,parsedTag:a});let x=d.outerEnd,w=!0;while(w){let A=e.slice(x).match(/^\s*/),R=A?A[0].length:0,D=$e(e,x+R);if(!D){w=!1;break}let j=qe(D.attrs,"v-else-if"),N=Jt(D.attrs,"v-else");if(j!==null){let F=Se(e,D),I=we(D.attrs,"v-else-if"),L=Ie(e.slice(F.outerStart,F.outerEnd),{...D,start:0,end:D.end-D.start},I);r.push({type:"else-if",expr:j,outerStart:x,outerEnd:F.outerEnd,element:L,parsedTag:D}),x=F.outerEnd}else if(N){let F=Se(e,D),I=we(D.attrs,"v-else"),L=Ie(e.slice(F.outerStart,F.outerEnd),{...D,start:0,end:D.end-D.start},I);r.push({type:"else",outerStart:x,outerEnd:F.outerEnd,element:L,parsedTag:D}),w=!1}else w=!1}let v=[];for(let A of r)if(A.type==="if")v.push(`@if(${A.expr})
578
- ${A.element}`);else if(A.type==="else-if")v.push(`@elseif(${A.expr})
579
- ${A.element}`);else v.push(`@else
580
- ${A.element}`);v.push("@endif");let k=v.join(`
581
- `),S=r[0].outerStart,M=r[r.length-1].outerEnd;e=e.slice(0,S)+k+e.slice(M),c=S+k.length}return e}function Cn(n){return n.replace(/\bv-show="([^"]*)"/g,'@show="$1"')}function An(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;let g=yn.has(a.tag),r=a.attrs.replace(/([^\s=]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s]+))?/g,(y,h,x)=>{let w=/^v-model(?::([a-zA-Z_][a-zA-Z0-9_]*))?((?:\.[a-zA-Z]+)*)$/.exec(h);if(!w||!x||!/^["']/.test(x))return y;let v=w[1]||"modelValue",k=w[2];if(g&&!w[1])return`@model${k}=${x}`;let S=x[0],M=x.slice(1,-1),A=`:${v}=${x} @update:${v}=${S}${M} = $event${S}`;if(k){let R=w[1]?`${v}Modifiers`:"modelModifiers",D=k.slice(1).split(".").map((j)=>`${j}: true`).join(", ");A+=` :${R}="{ ${D} }"`}return A});if(r===a.attrs){c=a.end;continue}let d=Ie(a.full,{...a,start:0,end:a.full.length},r);e=e.slice(0,a.start)+d+e.slice(a.end),c=a.start+d.length}return e}function Rn(n){return n.replace(/\bv-bind:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,'@bind:$1="$2"')}function Mn(n){return n.replace(/\bv-on:([a-zA-Z_][a-zA-Z0-9_.-]*)\s*=\s*"([^"]*)"/g,'@$1="$2"')}function Dn(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;let g=qe(a.attrs,"v-html");if(g===null){c=a.end;continue}if(a.selfClosing){c=a.end;continue}let r=Se(e,a),d=we(a.attrs,"v-html"),y=a.selfClosing?" /":"",h=`<${a.tag}${d}${y}>{!! ${g} !!}</${a.tag}>`;e=e.slice(0,r.outerStart)+h+e.slice(r.outerEnd),c=r.outerStart+h.length}return e}function In(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;let g=qe(a.attrs,"v-text");if(g===null){c=a.end;continue}if(a.selfClosing){c=a.end;continue}let r=Se(e,a),d=we(a.attrs,"v-text"),y=a.selfClosing?" /":"",h=`<${a.tag}${d}${y}>{{ ${g} }}</${a.tag}>`;e=e.slice(0,r.outerStart)+h+e.slice(r.outerEnd),c=r.outerStart+h.length}return e}function On(n){return n.replace(/(<[a-zA-Z][a-zA-Z0-9-]*)(\s[^>]*?)\s+v-pre([^>]*>)/g,"$1$2 data-stx-skip$3").replace(/(<[a-zA-Z][a-zA-Z0-9-]*)\s+v-pre(\s[^>]*>|>)/g,"$1 data-stx-skip$2")}function Ln(n){let e=n,c=0;while(c<e.length){let a=$e(e,c);if(!a)break;if(!Jt(a.attrs,"v-once")){c=a.end;continue}let g=we(a.attrs,"v-once"),r=Se(e,a),d=e.slice(r.outerStart,r.outerEnd),h=`@once
582
- ${Ie(d,{...a,start:0,end:a.end-a.start},g)}
583
- @endonce`;e=e.slice(0,r.outerStart)+h+e.slice(r.outerEnd),c=r.outerStart+h.length}return e}function Pn(n){return n.replace(/\bv-memo="([^"]*)"/g,'data-stx-memo="$1"')}function jn(n){return n.replace(/\bv-slot:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,'#$1="$2"').replace(/\bv-slot:([a-zA-Z_][a-zA-Z0-9_-]*)(?=[\s>])/g,"#$1").replace(/\bv-slot\s*=\s*"([^"]*)"/g,'#default="$1"')}function Qt(n){if(!vn(n))return n;let e=n;return e=kn(e),e=Sn(e),e=Ln(e),e=Rn(e),e=Mn(e),e=An(e),e=Cn(e),e=jn(e),e=Dn(e),e=In(e),e=On(e),e=Pn(e),e}function Ke(n){return n.replace(/--/g,"- -").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var st=new Set(["a","abbr","address","article","aside","audio","b","bdi","bdo","blockquote","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","hr","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","meter","nav","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","small","span","strong","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","u","ul","video"]),Nn=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]);function Yt(n,e){let c=/^\s*\{\{\s*([\s\S]+?)\s*\}\}\s*$/.exec(n),a=c?c[1]:n,g=u(a,e);if(g&&typeof g==="string")return g;let r=a.trim();return st.has(r)?r:null}function er(n){let e=/^\s*\{\{\s*([\s\S]+?)\s*\}\}\s*$/.exec(n);return e?e[1]:n}function tr(n,e,c){let a=e.replace(/\s*(?::is|v-bind:is)\s*=\s*"[^"]*"/gi,"").trim(),g=a?`<${n} ${a}>`:`<${n}>`;if(Nn.has(n))return a?`<${n} ${a}>`:`<${n}>`;return`${g}${c}</${n}>`}async function rr(n,e,c,a,g){let r=n,d=/<component\s+(?::is|v-bind:is)\s*=\s*"([^"]*)"([^>]*)>([\s\S]*?)<\/component>/gi,y=[],h;while((h=d.exec(r))!==null)y.push({full:h[0],expr:h[1],attrs:h[2],slotContent:h[3],index:h.index});for(let x=y.length-1;x>=0;x--){let w=y[x];try{let v=Yt(w.expr,e);if(!v||typeof v!=="string"){let j=`<!-- dynamic component: could not resolve "${Ke(er(w.expr))}" -->`;r=r.slice(0,w.index)+j+r.slice(w.index+w.full.length);continue}if(st.has(v)){let j=tr(v,w.attrs,w.slotContent);r=r.slice(0,w.index)+j+r.slice(w.index+w.full.length);continue}let k=w.attrs.trim(),S={},M=/(?::([a-zA-Z_][a-zA-Z0-9_-]*)|([a-zA-Z_][a-zA-Z0-9_-]*))\s*=\s*"([^"]*)"/g,A;while((A=M.exec(k))!==null){let j=A[1]||A[2],N=A[3];if(A[1])try{S[j]=u(N,e)}catch{S[j]=N}else S[j]=N}let R=a.componentsDir||"components",D=await He(v,S,w.slotContent,R,e,c,a,new Set,g??new Set);r=r.slice(0,w.index)+D+r.slice(w.index+w.full.length)}catch(v){let k=v instanceof Error?v.message:String(v),S=`<!-- dynamic component error: ${Ke(k)} -->`;r=r.slice(0,w.index)+S+r.slice(w.index+w.full.length)}}return r=await Hn(r,e,c,a,g),r}async function Hn(n,e,c,a,g){let r=n,d=/<component\s+(?::is|v-bind:is)\s*=\s*"([^"]*)"([^>]*?)\/>/gi,y=[],h;while((h=d.exec(r))!==null)y.push({full:h[0],expr:h[1],attrs:h[2],index:h.index});for(let x=y.length-1;x>=0;x--){let w=y[x];try{let v=Yt(w.expr,e);if(!v||typeof v!=="string"){let M=`<!-- dynamic component: could not resolve "${Ke(er(w.expr))}" -->`;r=r.slice(0,w.index)+M+r.slice(w.index+w.full.length);continue}if(st.has(v)){let M=tr(v,w.attrs,"");r=r.slice(0,w.index)+M+r.slice(w.index+w.full.length);continue}let k=a.componentsDir||"components",S=await He(v,{},"",k,e,c,a,new Set,g??new Set);r=r.slice(0,w.index)+S+r.slice(w.index+w.full.length)}catch(v){let k=v instanceof Error?v.message:String(v),S=`<!-- dynamic component error: ${Ke(k)} -->`;r=r.slice(0,w.index)+S+r.slice(w.index+w.full.length)}}return r}var fc="X-STX-Build",it=Symbol.for("stx.buildId");function ls(){let n=globalThis;if(!n[it])n[it]=process.env.STX_BUILD_ID||`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`;return n[it]}function nr(n,e=ls()){if(n.includes('name="stx-build"'))return null;if(!/<head\b[^>]*>/i.test(n))return null;return`
584
- <meta name="stx-build" content="${e}">`}var jo="/_stx/sw.js";function Bn(n){if(typeof n!=="string"||!n.startsWith("/"))return null;let e=[],c=[],a=n.replace(/\/+$/,"").split("/").slice(1).map((g)=>{let r=/^:(\w+)$/.exec(g)||/^\[(\w+)\]$/.exec(g);if(r)return e.push(r[1]),c.push("0"),"([^/]+)";return c.push(g),g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")});if(!e.length)return null;return{path:n,re:`^/${a.join("/")}/?$`,names:e,sample:`/${c.join("/")}`}}function Fn(n){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!navigator.serviceWorker)return;let e=navigator.serviceWorker,c=window;if(c.stxOffline)return;let a=null,g=!1,r=[],d={updateReady:!1,reachable:!0,reachedAt:0,registration:()=>a,onUpdateReady(w){if(d.updateReady)try{w()}catch{}else r.push(w);return()=>{let v=r.indexOf(w);if(v!==-1)r.splice(v,1)}},applyUpdate(){let w=a&&a.waiting;if(!w)return!1;return g=!0,w.postMessage({type:"stx:activate-update",force:!0}),!0}};c.stxOffline=d;let y=(w)=>{if(!w.waiting||!e.controller||d.updateReady)return;d.updateReady=!0;let v=r.splice(0);for(let k of v)try{k()}catch{}try{window.dispatchEvent(new CustomEvent("stx:offline-update-ready"))}catch{}};e.addEventListener("message",(w)=>{let v=w.data||{};if(v.type==="stx:updated")try{window.dispatchEvent(new CustomEvent("stx:updated",{detail:{url:v.url,kind:v.kind,fragment:!!v.fragment}}))}catch{}if(v.type==="stx:reachability"){if(c.stxOffline.reachable=v.reachable!==!1,Number(v.at)>0)c.stxOffline.reachedAt=Number(v.at);try{window.dispatchEvent(new CustomEvent("stx:reachability",{detail:{reachable:v.reachable!==!1,at:Number(v.at)||0}}))}catch{}}}),e.addEventListener("controllerchange",()=>{if(g)g=!1,location.reload()}),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden"&&a&&a.waiting)a.waiting.postMessage({type:"stx:activate-update",reason:"hidden"})});let h=()=>{e.register(n,{scope:"/"}).then((w)=>{a=w;try{e.controller?.postMessage({type:"stx:reachability?"})}catch{}if(w.waiting)y(w),w.waiting.postMessage({type:"stx:activate-update",reason:"load"});w.addEventListener("updatefound",()=>{let v=w.installing;if(!v)return;v.addEventListener("statechange",()=>{if(v.state==="installed")y(w)})})}).catch(()=>{})},x=()=>{let w=(v)=>{setTimeout(v,0)};if(typeof requestAnimationFrame==="function")requestAnimationFrame(()=>w(h));else w(h)};if(!e.controller)if(document.readyState==="complete")x();else addEventListener("load",x);else if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",x);else x()}function Un(){let n=`(${Fn.toString()})(${JSON.stringify("/_stx/sw.js")})`;try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(n).trim().replace(/;$/,"")}catch{return n}}function qn(n,e){if(typeof e==="string"&&e.startsWith("/"))return e==="/"?"/":e.replace(/\/+$/,"");if(!n||!n.startsWith("/"))return null;let c=n.split(/[?#]/)[0].split("/").filter(Boolean)[0];return c?`/${c}`:"/"}var sr=`<script data-stx-offline>${Un()}</script>`;function Bo(n,e){let c=Number(n.precacheTimeoutMs),a={build:String(e||"dev"),pages:Array.from(new Set((n.pages||[]).filter((g)=>typeof g==="string"&&g.startsWith("/")))),staticPages:(n.staticPages||[]).filter((g)=>typeof g==="string"&&((n.pages||[]).includes(g)||(n.routes||[]).includes(g))),api:n.apiPrefix||"/api/",timeout:Math.max(500,Number(n.networkTimeoutMs)||1500),precacheTimeout:Number.isFinite(c)&&c>0?Math.min(2147483647,Math.max(1,Math.floor(c))):1e4,networkFirst:(n.networkFirst||[]).filter((g)=>typeof g==="string"&&g.startsWith("/")),updateOnColdStart:n.updateOnColdStart===!0,fallback:n.fallback||n.pages&&n.pages[0]||null,fallbackScope:qn(n.fallback||n.pages&&n.pages[0]||null,n.fallbackScope),routes:(n.routes||[]).map(Bn).filter(Boolean),exclude:["/_stx/hmr","/_stx/sw.js",...n.exclude||[]],mediaMax:Math.max(10485760,Number(n.mediaMaxBytes)||629145600),assetsMax:Math.max(50,Number(n.assetsMaxEntries)||500)};return`/* stx offline worker, build ${a.build} */
585
- 'use strict';
586
- var S = ${JSON.stringify(a)};
587
- var SHELL = 'stx-shell-' + S.build;
588
- var ASSETS = 'stx-assets';
589
- var DATA = 'stx-data';
590
- var MEDIA = 'stx-media';
591
- var MEDIA_INDEX = '/__stx_media_index__';
592
- var LAST_WRITE = '/__stx_last_write__';
593
- var FRAGMENT = 'X-STX-Router';
594
- // Stamped on every kept copy: when it was kept, and a fingerprint of its body,
595
- // so revalidating can tell a changed answer from the same one sent again.
596
- var KEPT_AT = 'X-STX-Kept-At';
597
- var KEPT_HASH = 'X-STX-Hash';
598
-
599
- function variantUrl(url, fragment) {
600
- var u = new URL(url, self.location.origin);
601
- u.hash = '';
602
- if (fragment) u.searchParams.set('__stx_fragment', '1');
603
- return u.toString();
604
- }
605
-
606
- function isFragment(request) {
607
- return request.headers.get(FRAGMENT) === 'true';
608
- }
609
-
610
- function withTimeout(promise, ms) {
611
- return new Promise(function (resolve, reject) {
612
- var timer = setTimeout(function () { reject(new Error('timeout')); }, ms);
613
- promise.then(function (value) { clearTimeout(timer); resolve(value); }, function (error) { clearTimeout(timer); reject(error); });
614
- });
615
- }
616
-
617
- function hex(buffer) {
618
- return Array.from(new Uint8Array(buffer)).slice(0, 12).map(function (byte) { return byte.toString(16).padStart(2, '0'); }).join('');
619
- }
620
-
621
- function hashOf(text) {
622
- if (!text) return Promise.resolve('anon');
623
- return crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)).then(hex);
624
- }
625
-
626
- // Keep the background work of a fetch alive past its answer: the worker may
627
- // otherwise be stopped before the revalidated copy is stored.
628
- function keepAlive(event, promise) {
629
- var settled = promise.catch(function () {});
630
- try { if (event && event.waitUntil) event.waitUntil(settled); }
631
- catch (error) {}
632
- return settled;
633
- }
634
-
635
- // Whether this request wants the network before any kept copy: a pull to
636
- // refresh asks with cache: 'no-cache', and some paths are configured so.
637
- function wantsNetworkFirst(request, pathname) {
638
- if (request.cache === 'no-cache' || request.cache === 'reload' || request.cache === 'no-store') return true;
639
- for (var i = 0; i < S.networkFirst.length; i++) {
640
- if (pathname.indexOf(S.networkFirst[i]) === 0) return true;
641
- }
642
- return false;
643
- }
644
-
645
- // Only what was asked for, whole and from this origin, is ever kept: not a
646
- // redirect (to a sign-in page), an error, or a partial answer.
647
- function noStore(response) {
648
- return /(?:^|,)\\s*no-store\\s*(?:,|$)/i.test(response.headers.get('Cache-Control') || '');
649
- }
650
- function keepable(response) {
651
- return response.status === 200 && !response.redirected && response.type === 'basic' && !noStore(response);
652
- }
653
-
654
- // A page's body changes on every render where it carries a CSP nonce or a
655
- // CSRF token. Those are left out of its fingerprint, or every visit would
656
- // look like new content.
657
- var VOLATILE = /\\snonce="[^"]*"|<meta\\s+name="csrf-token"[^>]*>/g;
658
- function fingerprint(response) {
659
- var type = response.headers.get('Content-Type') || '';
660
- return response.arrayBuffer().then(function (body) {
661
- var bytes = body;
662
- if (type.indexOf('html') !== -1) bytes = new TextEncoder().encode(new TextDecoder().decode(body).replace(VOLATILE, ''));
663
- return crypto.subtle.digest('SHA-256', bytes).then(function (digest) { return { body: body, hash: hex(digest) }; });
664
- });
665
- }
666
-
667
- function stamped(response, body, hash) {
668
- var headers = new Headers(response.headers);
669
- // The body read here is already decoded: a compressed answer's encoding and
670
- // length no longer describe it, and a browser trusting them cut it short.
671
- headers.delete('Content-Encoding');
672
- headers.delete('Content-Length');
673
- headers.set(KEPT_AT, String(Date.now()));
674
- if (hash) headers.set(KEPT_HASH, hash);
675
- return new Response(body, { status: response.status, statusText: response.statusText, headers: headers });
676
- }
677
-
678
- // Keep a copy under each key, stamped. Resolves with its fingerprint.
679
- function store(cache, keys, response) {
680
- return fingerprint(response).then(function (print) {
681
- return Promise.all(keys.map(function (key) { return cache.put(key, stamped(response, print.body, print.hash)); })).then(function () { return print; });
682
- });
683
- }
684
-
685
- function keptHash(hit) {
686
- var known = hit.headers.get(KEPT_HASH);
687
- if (known) return Promise.resolve(known);
688
- // Kept by an earlier worker, before copies were stamped.
689
- return fingerprint(hit.clone()).then(function (print) { return print.hash; });
690
- }
691
-
692
- // The same content as the kept copy: a matching validator says so without
693
- // reading the body; otherwise the fingerprints decide.
694
- function unchanged(hit, response, hash) {
695
- var a = hit.headers.get('ETag');
696
- var b = response.headers.get('ETag');
697
- if (a && b && a === b) return Promise.resolve(true);
698
- var c = hit.headers.get('Last-Modified');
699
- var d = response.headers.get('Last-Modified');
700
- if (c && d && c === d && !a && !b) return Promise.resolve(true);
701
- return keptHash(hit).then(function (known) { return known === hash; });
702
- }
703
-
704
- // Whether the server answered the last request that went to it, and when it
705
- // last did. Pages hear a change of the first (stx:reachability).
706
- var reachable = true;
707
- var reachedAt = 0;
708
- function reached(yes) {
709
- if (yes) reachedAt = Date.now();
710
- if (yes === reachable) return;
711
- reachable = yes;
712
- announce({ type: 'stx:reachability', reachable: yes, at: reachedAt });
713
- }
714
- // A fetch to the server, noting whether it got there. Any answer counts,
715
- // an error status included: the server was reached.
716
- function network(request, init) {
717
- return fetch(request, init).then(function (response) {
718
- reached(true);
719
- return response;
720
- }, function (error) {
721
- // A TypeError is the network's; an abort is the page's own doing.
722
- if (!error || error.name !== 'AbortError') reached(false);
723
- throw error;
724
- });
725
- }
726
-
727
- // Every open page of the app hears what changed, so it can redraw.
728
- function announce(message) {
729
- if (!self.clients || !self.clients.matchAll) return Promise.resolve();
730
- return self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
731
- list.forEach(function (client) {
732
- try { client.postMessage(message); }
733
- catch (error) {}
734
- });
735
- });
736
- }
737
-
738
- // Ask the network behind a kept copy that was already answered. A different
739
- // answer replaces the copy and is announced; the same one only refreshes
740
- // when it was kept.
741
- function revalidate(request, cache, keys, hit, kind) {
742
- return network(request).then(function (response) {
743
- var staticPage = kind === 'page' && keepStaticPage(request, response);
744
- if (noStore(response) && !staticPage) return Promise.all(keys.map(function (key) { return cache.delete(key); }));
745
- if (!keepable(response) && !staticPage) return;
746
- return store(cache, keys, response).then(function (print) {
747
- return unchanged(hit, response, print.hash).then(function (same) {
748
- if (same) return;
749
- var url = new URL(request.url);
750
- url.hash = '';
751
- return announce({ type: 'stx:updated', url: url.toString(), kind: kind, fragment: isFragment(request) });
752
- });
753
- });
754
- });
755
- }
756
-
757
- function keepStaticPage(request, response) {
758
- if (response.status !== 200 || response.redirected || response.type !== 'basic') return false;
759
- var pathname = new URL(request.url).pathname;
760
- if (S.staticPages.indexOf(pathname) !== -1) return true;
761
- // A route declared static: every value of it is the same shell.
762
- var dynamic = routeOf(pathname);
763
- return !!dynamic && S.staticPages.indexOf(dynamic.route.path) !== -1;
764
- }
765
-
766
- // A dynamic route's kept page, under a key no real path has.
767
- function routeKey(route, fragment) {
768
- return variantUrl('/__stx_route__' + route.path, fragment);
769
- }
770
-
771
- function routeOf(pathname) {
772
- for (var i = 0; i < S.routes.length; i++) {
773
- var match = new RegExp(S.routes[i].re).exec(pathname);
774
- if (!match) continue;
775
- var params = {};
776
- S.routes[i].names.forEach(function (name, at) {
777
- try { params[name] = decodeURIComponent(match[at + 1]); }
778
- catch (error) { params[name] = match[at + 1]; }
779
- });
780
- return { route: S.routes[i], params: params };
781
- }
782
- return null;
783
- }
784
-
785
- // The route's kept page with the params asked for in its params script, so
786
- // useRoute().params reads the value that was opened, not the one kept.
787
- var PARAMS_SCRIPT = /(<script\\b[^>]*data-stx-route-params[^>]*>\\(function\\(\\)\\{var p=)[\\s\\S]*?(;window\\.__stx_rp)/;
788
- function withParams(response, params) {
789
- return response.text().then(function (html) {
790
- var json = JSON.stringify(params).replace(/</g, '\\\\u003C').replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');
791
- var body = html.replace(PARAMS_SCRIPT, function (all, open, close) { return open + json + close; });
792
- var headers = new Headers(response.headers);
793
- headers.delete('Content-Length');
794
- return new Response(body, { status: 200, headers: headers });
795
- });
796
- }
797
-
798
- // The stylesheets and scripts a kept page links to. Each page has its own
799
- // generated CSS, fetched only when the page is shown: a screen kept at
800
- // install but never opened online came up offline without its styles.
801
- // Background installation must leave connections available for the page the
802
- // person opens. Bound the whole response body, not just its response headers.
803
- var backgroundQueue = [];
804
- var backgroundActive = 0;
805
- function startBackground(job) {
806
- var controller = new AbortController();
807
- var timer = setTimeout(function () { controller.abort(); }, S.precacheTimeout);
808
- function finish() {
809
- clearTimeout(timer);
810
- backgroundActive--;
811
- drainBackground();
812
- }
813
- Promise.resolve().then(function () { return job.work(controller.signal); }).then(function (value) {
814
- finish();
815
- job.resolve(value);
816
- }, function (error) {
817
- finish();
818
- job.reject(error);
819
- });
820
- }
821
- function drainBackground() {
822
- while (backgroundActive < 2 && backgroundQueue.length) {
823
- backgroundActive++;
824
- startBackground(backgroundQueue.shift());
825
- }
826
- }
827
- function background(work) {
828
- return new Promise(function (resolve, reject) {
829
- backgroundQueue.push({ work: work, resolve: resolve, reject: reject });
830
- drainBackground();
831
- });
832
- }
833
-
834
- var keepingAssets = {};
835
- var ASSET_REF = /<(?:link|script)\\b[^>]*?\\s(?:href|src)="(\\/[^"]+\\.(?:css|js))"/g;
836
- function assetRefs(html) {
837
- var urls = [];
838
- var match;
839
- ASSET_REF.lastIndex = 0;
840
- while ((match = ASSET_REF.exec(html))) {
841
- if (urls.indexOf(match[1]) === -1) urls.push(match[1]);
842
- }
843
- return urls;
844
- }
845
-
846
- function keepAsset(cache, request, response) {
847
- return response.blob().then(function (body) { return cache.put(request, stamped(response, body, null)); });
848
- }
849
-
850
- function keepAssets(html) {
851
- var urls = assetRefs(html);
852
- return caches.open(ASSETS).then(function (cache) {
853
- return Promise.all(urls.map(function (url) {
854
- // A page and its fragment link the same files: one fetch each.
855
- if (!keepingAssets[url]) {
856
- keepingAssets[url] = cache.match(url).then(function (hit) {
857
- if (hit) return;
858
- return background(function (signal) {
859
- return fetch(url, { credentials: 'same-origin', signal: signal, priority: 'low' }).then(function (asset) {
860
- if (asset.status === 200) return keepAsset(cache, url, asset);
861
- delete keepingAssets[url];
862
- });
863
- });
864
- }).catch(function () { delete keepingAssets[url]; });
865
- }
866
- return keepingAssets[url];
867
- }));
868
- }).catch(function () {});
869
- }
870
-
871
- function precache() {
872
- var wanted = S.pages.map(function (page) { return { url: page, key: function (fragment) { return variantUrl(page, fragment); } }; })
873
- .concat(S.routes.map(function (route) { return { url: route.sample, key: function (fragment) { return routeKey(route, fragment); } }; }));
874
- return caches.open(SHELL).then(function (cache) {
875
- return Promise.all(wanted.map(function (page) {
876
- return Promise.all([false, true].map(function (fragment) {
877
- var headers = fragment ? { 'X-STX-Router': 'true', 'Accept': 'text/html' } : { 'Accept': 'text/html' };
878
- return background(function (signal) {
879
- return fetch(page.url, { headers: headers, credentials: 'same-origin', signal: signal, priority: 'low' }).then(function (response) {
880
- if (response.status !== 200 || response.redirected) return null;
881
- var copy = response.clone();
882
- return Promise.all([store(cache, [page.key(fragment)], response), copy.text()]).then(function (parts) { return parts[1]; });
883
- });
884
- }).then(function (html) {
885
- // Queue linked assets after releasing the page's slot. Waiting for
886
- // child jobs inside a bounded parent job would deadlock installation.
887
- if (html !== null) return keepAssets(html);
888
- }).catch(function () {});
889
- }));
890
- }));
891
- });
892
- }
893
-
894
- // Stylesheets and scripts no kept screen of this build links to, and that
895
- // nothing fetched lately, are an earlier build's: dropped when this build
896
- // takes over. Other files (images, fonts) are capped, least recently fetched
897
- // first. Fetching refreshes a file's stamp, so one in use is never the oldest.
898
- var ASSET_GRACE_MS = 24 * 60 * 60 * 1000;
899
- function pruneAssets() {
900
- return Promise.all([caches.open(SHELL), caches.open(ASSETS)]).then(function (opened) {
901
- var shell = opened[0];
902
- var assets = opened[1];
903
- return shell.keys().then(function (pages) {
904
- return Promise.all(pages.map(function (page) {
905
- return shell.match(page).then(function (hit) { return hit ? hit.text() : ''; }).catch(function () { return ''; });
906
- }));
907
- }).then(function (htmls) {
908
- var linked = {};
909
- htmls.forEach(function (html) {
910
- assetRefs(html).forEach(function (url) { linked[new URL(url, self.location.origin).toString()] = true; });
911
- });
912
- return assets.keys().then(function (requests) {
913
- return Promise.all(requests.map(function (request) {
914
- return assets.match(request).then(function (hit) { return { request: request, at: hit ? Number(hit.headers.get(KEPT_AT) || 0) : 0 }; });
915
- }));
916
- }).then(function (entries) {
917
- var now = Date.now();
918
- var drops = [];
919
- var others = [];
920
- entries.forEach(function (entry) {
921
- var url = entry.request.url;
922
- if (/\\.(?:css|js)$/.test(new URL(url).pathname)) {
923
- // With no screen kept there is nothing to judge by: keep them.
924
- if (htmls.length && !linked[url] && now - entry.at > ASSET_GRACE_MS) drops.push(entry.request);
925
- }
926
- else others.push(entry);
927
- });
928
- if (others.length > S.assetsMax) {
929
- others.sort(function (a, b) { return a.at - b.at; });
930
- others.slice(0, others.length - S.assetsMax).forEach(function (entry) { drops.push(entry.request); });
931
- }
932
- return Promise.all(drops.map(function (request) { return assets.delete(request); }));
933
- });
934
- });
935
- }).catch(function () {});
936
- }
937
-
938
- // A new build waits for the one running to be let go (see 'message'), rather
939
- // than taking over under a page that is on screen: its fragments would not
940
- // match the page's build, and the router would reload under the person.
941
- self.addEventListener('install', function (event) {
942
- event.waitUntil(precache());
943
- });
944
-
945
- self.addEventListener('activate', function (event) {
946
- event.waitUntil(caches.keys().then(function (keys) {
947
- return Promise.all(keys.filter(function (key) { return key.indexOf('stx-shell-') === 0 && key !== SHELL; }).map(function (key) { return caches.delete(key); }));
948
- }).then(pruneAssets).then(function () { return self.clients.claim(); }));
949
- });
950
-
951
- // When a page may let this build take over: asked outright (an "Update"
952
- // button), the app starting cold, or no page of the app on screen.
953
- function mayTakeOver(data) {
954
- if (data.force || data.reason === 'cold-start') return Promise.resolve(true);
955
- if (!self.clients || !self.clients.matchAll) return Promise.resolve(false);
956
- return self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
957
- if (data.reason === 'load' && list.length <= 1) return true;
958
- return !list.some(function (client) { return client.visibilityState === 'visible'; });
959
- });
960
- }
961
-
962
- // --- Media kept for offline: videos a page asked for (cacheMedia()) ---
963
- // Stored whole and answered here, ranges included: a player seeks with Range
964
- // requests, and the network may not be there to answer them. The index (url
965
- // -> bytes, when) lives in the same cache, so eviction can go oldest first.
966
- function mediaKey(url) {
967
- var u = new URL(url, self.location.origin);
968
- u.hash = '';
969
- return u.toString();
970
- }
971
-
972
- function readMediaIndex(cache) {
973
- return cache.match(MEDIA_INDEX).then(function (hit) { return hit ? hit.json() : {}; }).catch(function () { return {}; });
974
- }
975
-
976
- function writeMediaIndex(cache, index) {
977
- return cache.put(MEDIA_INDEX, new Response(JSON.stringify(index), { headers: { 'Content-Type': 'application/json' } }));
978
- }
979
-
980
- function keepMedia(urls) {
981
- return caches.open(MEDIA).then(function (cache) {
982
- return readMediaIndex(cache).then(function (index) {
983
- var wanted = urls.map(mediaKey);
984
- var chain = Promise.resolve();
985
- wanted.forEach(function (key) {
986
- chain = chain.then(function () {
987
- if (index[key]) { index[key].at = Date.now(); return; }
988
- // Already stored by the page (cacheMedia downloads while the app is
989
- // open), so only its size is wanted. Otherwise fetched here.
990
- return cache.match(key).then(function (stored) {
991
- if (stored) return stored;
992
- return fetch(key, { credentials: 'same-origin' }).then(function (response) {
993
- if (response.status !== 200 || !response.body) return null;
994
- var type = response.headers.get('Content-Type') || 'application/octet-stream';
995
- // Streamed into the cache, never held whole: a coach's 300 MB
996
- // upload read into one blob was enough for iOS to end the worker
997
- // part way, and nothing was kept.
998
- return cache.put(key, new Response(response.body, { headers: { 'Content-Type': type, 'Accept-Ranges': 'bytes' } })).then(function () {
999
- return cache.match(key);
1000
- });
1001
- });
1002
- }).then(function (kept) {
1003
- if (!kept) return;
1004
- return kept.blob().then(function (blob) { index[key] = { bytes: blob.size, at: Date.now() }; });
1005
- }).catch(function () {});
1006
- });
1007
- });
1008
- return chain.then(function () {
1009
- // Oldest first, until what is kept fits.
1010
- var total = 0;
1011
- var keys = Object.keys(index).sort(function (a, b) { return index[b].at - index[a].at; });
1012
- var drops = [];
1013
- keys.forEach(function (key) {
1014
- total += index[key].bytes;
1015
- if (total > S.mediaMax && wanted.indexOf(key) === -1) drops.push(key);
1016
- });
1017
- return Promise.all(drops.map(function (key) { delete index[key]; return cache.delete(key); }));
1018
- }).then(function () { return writeMediaIndex(cache, index); }).then(function () { return Object.keys(index); });
1019
- });
1020
- });
1021
- }
1022
-
1023
- function mediaResponse(request) {
1024
- return caches.open(MEDIA).then(function (cache) {
1025
- return cache.match(mediaKey(request.url)).then(function (hit) {
1026
- if (!hit) return null;
1027
- var range = request.headers.get('Range');
1028
- if (!range) return hit;
1029
- return hit.blob().then(function (blob) {
1030
- var match = /bytes=(\\d*)-(\\d*)/.exec(range);
1031
- var size = blob.size;
1032
- var start = match && match[1] ? Number(match[1]) : 0;
1033
- var end = match && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
1034
- if (match && !match[1] && match[2]) { start = Math.max(0, size - Number(match[2])); end = size - 1; }
1035
- if (start >= size || start > end) return new Response(null, { status: 416, headers: { 'Content-Range': 'bytes */' + size } });
1036
- return new Response(blob.slice(start, end + 1), {
1037
- status: 206,
1038
- headers: {
1039
- 'Content-Type': hit.headers.get('Content-Type') || 'application/octet-stream',
1040
- 'Content-Range': 'bytes ' + start + '-' + end + '/' + size,
1041
- 'Content-Length': String(end - start + 1),
1042
- 'Accept-Ranges': 'bytes',
1043
- },
1044
- });
1045
- });
1046
- });
1047
- });
1048
- }
1049
-
1050
- self.addEventListener('message', function (event) {
1051
- var data = event.data || {};
1052
- if (data.type === 'stx:reachability?') {
1053
- // A page just opened: what this worker last saw of the server.
1054
- event.waitUntil(announce({ type: 'stx:reachability', reachable: reachable, at: reachedAt }));
1055
- }
1056
- if (data.type === 'stx:clear-offline-data') {
1057
- lastWrite = null;
1058
- event.waitUntil(Promise.all([caches.delete(DATA), caches.delete(MEDIA)]));
1059
- }
1060
- if (data.type === 'stx:activate-update') {
1061
- // Sent to the waiting worker. One already running ignores it: skipWaiting
1062
- // does nothing once active.
1063
- event.waitUntil(mayTakeOver(data).then(function (yes) { if (yes) return self.skipWaiting(); }));
1064
- }
1065
- if (data.type === 'stx:cache-media' && Array.isArray(data.urls)) {
1066
- var reply = event.ports && event.ports[0];
1067
- event.waitUntil(keepMedia(data.urls.filter(function (url) { return typeof url === 'string'; })).then(function (kept) {
1068
- if (reply) reply.postMessage({ ok: true, kept: kept });
1069
- }, function () {
1070
- if (reply) reply.postMessage({ ok: false, kept: [] });
1071
- }));
1072
- }
1073
- });
1074
-
1075
- // Whether the fallback screen may stand in for this path (S.fallbackScope).
1076
- function inFallbackScope(pathname) {
1077
- var scope = S.fallbackScope;
1078
- if (!scope || scope === '/') return true;
1079
- return pathname === scope || pathname.indexOf(scope + '/') === 0;
1080
- }
1081
-
1082
- // The fallback screen stands in for one this device has not kept whole. It
1083
- // says so, and the router then asks for the screen that was wanted as a
1084
- // fragment: one reached inside the app was kept that way.
1085
- function markFallback(response) {
1086
- return response.text().then(function (html) {
1087
- var head = html.indexOf('<head');
1088
- var at = head === -1 ? -1 : html.indexOf('>', head) + 1;
1089
- var mark = '<meta name="stx-offline-fallback" content="1">';
1090
- var body = at > 0 ? html.slice(0, at) + mark + html.slice(at) : mark + html;
1091
- var headers = new Headers(response.headers);
1092
- headers.delete('Content-Length');
1093
- return new Response(body, { status: 200, headers: headers });
1094
- });
1095
- }
1096
-
1097
- // The app starting cold (a navigation with no other page of it open) while a
1098
- // new build waits, with updateOnColdStart on: the new build takes over now, and
1099
- // this navigation goes to the network so it opens on the new build rather than
1100
- // the kept old one. Off, it opens at once on the kept build.
1101
- function coldStartUpdate(request) {
1102
- var registration = self.registration;
1103
- if (!S.updateOnColdStart || request.mode !== 'navigate' || !registration || !registration.waiting || !self.clients || !self.clients.matchAll) return Promise.resolve(false);
1104
- return self.clients.matchAll({ type: 'window' }).then(function (list) {
1105
- if (list.length > 1 || !registration.waiting) return false;
1106
- registration.waiting.postMessage({ type: 'stx:activate-update', reason: 'cold-start' });
1107
- return true;
1108
- }).catch(function () { return false; });
1109
- }
1110
-
1111
- // Whether every module bundle a kept page links to is kept too.
1112
- //
1113
- // A page's registry, stores and composables are /_stx/modules.<hash>.js,
1114
- // answered by the server process that rendered the page, and only by it: a
1115
- // deploy starts a process that has never heard of the old hashes and answers
1116
- // them 404. A kept page whose bundles are not kept beside it is therefore one
1117
- // that may never bind -- opened cold, it showed its markup with every {{ }}
1118
- // empty and no button working, until a revalidation happened to replace it.
1119
- // Such a copy is not answered first: the network is, and the copy only stands
1120
- // in when there is no network at all, where it is the best there is.
1121
- // ignoreVary: a script was kept under the browser's own request, whose
1122
- // Accept-Encoding a lookup by URL does not carry.
1123
- var MODULE_BUNDLE = /\\/_stx\\/modules\\.[0-9a-f]{16}\\.js/g;
1124
- function bundlesKept(response) {
1125
- return response.clone().text().then(function (html) {
1126
- var urls = [];
1127
- var match;
1128
- MODULE_BUNDLE.lastIndex = 0;
1129
- while ((match = MODULE_BUNDLE.exec(html))) {
1130
- if (urls.indexOf(match[0]) === -1) urls.push(match[0]);
1131
- }
1132
- if (!urls.length) return true;
1133
- return caches.open(ASSETS).then(function (assets) {
1134
- return Promise.all(urls.map(function (url) { return assets.match(url, { ignoreVary: true }); }));
1135
- }).then(function (kept) {
1136
- return kept.every(Boolean);
1137
- });
1138
- }).catch(function () { return true; });
1139
- }
1140
-
1141
- function pageResponse(request, event) {
1142
- var fragment = isFragment(request);
1143
- var key = variantUrl(request.url, fragment);
1144
- var dynamic = routeOf(new URL(request.url).pathname);
1145
- var keys = dynamic ? [key, routeKey(dynamic.route, fragment)] : [key];
1146
- return Promise.all([caches.open(SHELL), coldStartUpdate(request)]).then(function (opened) {
1147
- var cache = opened[0];
1148
- var networkFirst = opened[1] || wantsNetworkFirst(request, new URL(request.url).pathname);
1149
- return cache.match(key).then(function (hit) {
1150
- return (hit && !networkFirst ? bundlesKept(hit) : Promise.resolve(false)).then(function (whole) {
1151
- if (whole) {
1152
- keepAlive(event, revalidate(request, cache, keys, hit, 'page'));
1153
- return hit;
1154
- }
1155
- // Kept, but without its module bundles: not shown while the network
1156
- // might answer (bundlesKept).
1157
- var partial = hit && !networkFirst;
1158
- var asked = network(request).then(function (response) {
1159
- if (keepable(response) || keepStaticPage(request, response)) keepAlive(event, store(cache, keys, response.clone()));
1160
- return response;
1161
- });
1162
- // What stands in when the network is not there, or slow: the kept copy,
1163
- // then a dynamic route's kept page, then the fallback screen.
1164
- var standIn = function (offline) {
1165
- if (hit && (!partial || offline)) return Promise.resolve(hit);
1166
- var route = dynamic ? cache.match(routeKey(dynamic.route, fragment)) : Promise.resolve(null);
1167
- return route.then(function (kept) {
1168
- if (kept) return withParams(kept, dynamic.params);
1169
- if (!offline) return null;
1170
- if (!S.fallback || fragment || !inFallbackScope(new URL(request.url).pathname)) return Response.error();
1171
- return cache.match(variantUrl(S.fallback, false)).then(function (fallback) { return fallback ? markFallback(fallback) : Response.error(); });
1172
- });
1173
- };
1174
- return withTimeout(asked, S.timeout).catch(function () {
1175
- return standIn(false).then(function (kept) {
1176
- if (kept) {
1177
- keepAlive(event, asked);
1178
- return kept;
1179
- }
1180
- // Slower than the timeout, nothing kept to show: wait for it rather than fail.
1181
- return asked.catch(function () { return standIn(true); });
1182
- });
1183
- });
1184
- });
1185
- });
1186
- });
1187
- }
1188
-
1189
- function assetResponse(request, event) {
1190
- return caches.open(ASSETS).then(function (cache) {
1191
- return cache.match(request).then(function (hit) {
1192
- var network = fetch(request).then(function (response) {
1193
- if (keepable(response)) keepAlive(event, keepAsset(cache, request, response.clone()));
1194
- return response;
1195
- });
1196
- if (hit) {
1197
- keepAlive(event, network);
1198
- return hit;
1199
- }
1200
- return network;
1201
- });
1202
- });
1203
- }
1204
-
1205
- // When the app last wrote to its API (any request but a GET). A copy kept
1206
- // before it is not answered at once: it would show the screen as if the
1207
- // write had not happened. Kept in the data cache so a restarted worker knows.
1208
- var lastWrite = null;
1209
- function lastWriteAt() {
1210
- if (!lastWrite) {
1211
- lastWrite = caches.open(DATA).then(function (cache) { return cache.match(LAST_WRITE); })
1212
- .then(function (hit) { return hit ? hit.text() : '0'; })
1213
- .then(function (text) { return Number(text) || 0; })
1214
- .catch(function () { return 0; });
1215
- }
1216
- return lastWrite;
1217
- }
1218
- function noteWrite() {
1219
- var at = Date.now();
1220
- lastWrite = Promise.resolve(at);
1221
- return caches.open(DATA).then(function (cache) { return cache.put(LAST_WRITE, new Response(String(at))); }).catch(function () {});
1222
- }
1223
-
1224
- function apiResponse(request, event) {
1225
- return hashOf(request.headers.get('Authorization') || '').then(function (who) {
1226
- var u = new URL(request.url);
1227
- u.searchParams.set('__stx_who', who);
1228
- var key = u.toString();
1229
- return Promise.all([caches.open(DATA), lastWriteAt()]).then(function (opened) {
1230
- var cache = opened[0];
1231
- return cache.match(key).then(function (hit) {
1232
- var stale = hit && opened[1] > 0 && Number(hit.headers.get(KEPT_AT) || 0) <= opened[1];
1233
- if (hit && !stale && !wantsNetworkFirst(request, u.pathname)) {
1234
- keepAlive(event, revalidate(request, cache, [key], hit, 'api'));
1235
- return hit;
1236
- }
1237
- var asked = network(request).then(function (response) {
1238
- if (noStore(response)) keepAlive(event, cache.delete(key));
1239
- if (keepable(response)) keepAlive(event, store(cache, [key], response.clone()));
1240
- return response;
1241
- });
1242
- return withTimeout(asked, S.timeout).catch(function () {
1243
- return hit || asked;
1244
- });
1245
- });
1246
- });
1247
- });
1248
- }
1249
-
1250
- self.addEventListener('fetch', function (event) {
1251
- var request = event.request;
1252
- var url = new URL(request.url);
1253
- if (url.origin !== self.location.origin) return;
1254
- if (request.method !== 'GET') {
1255
- // Writes go straight to the network; only when they happened is noted.
1256
- if (url.pathname.indexOf(S.api) === 0) keepAlive(event, noteWrite());
1257
- return;
1258
- }
1259
- // Live status and other explicitly uncached reads must never be answered
1260
- // from offline storage, including when the network fails.
1261
- if (request.cache === 'no-store') {
1262
- event.respondWith(network(request));
1263
- return;
1264
- }
1265
- // Media kept for offline is answered from the device, a range included;
1266
- // anything else asking for a range is the browser's to answer, since a
1267
- // cache cannot hold a partial response.
1268
- if (request.headers.has('Range') || /\\.(?:mp4|m4v|mov|webm|m3u8|mp3|m4a)$/i.test(url.pathname)) {
1269
- event.respondWith(mediaResponse(request).then(function (kept) { return kept || fetch(request); }));
1270
- return;
1271
- }
1272
- for (var i = 0; i < S.exclude.length; i++) {
1273
- if (url.pathname.indexOf(S.exclude[i]) === 0) return;
1274
- }
1275
- if (url.pathname.indexOf(S.api) === 0) {
1276
- event.respondWith(apiResponse(request, event));
1277
- return;
1278
- }
1279
- if (url.pathname.indexOf('/_stx/') === 0 || url.pathname.indexOf('/assets/') === 0 || /\\.(?:js|css|woff2?|png|jpe?g|webp|avif|svg|ico)$/.test(url.pathname)) {
1280
- event.respondWith(assetResponse(request, event));
1281
- return;
1282
- }
1283
- var accept = request.headers.get('Accept') || '';
1284
- if (request.mode === 'navigate' || isFragment(request) || accept.indexOf('text/html') !== -1) {
1285
- event.respondWith(pageResponse(request, event));
1286
- }
1287
- });
1288
- `}import Oe from"path";function ir(n){return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("//")}async function ar(n,e,c){try{let a;if(n.startsWith("/")){let g=e;for(let r=0;r<5;r++){let d=Oe.join(g,n);if(await Bun.file(d).exists())return d;g=Oe.dirname(g)}a=Oe.join(e,n)}else if(n.startsWith("./")||n.startsWith("../"))a=Oe.resolve(e,n);else a=Oe.resolve(e,n);if(await Bun.file(a).exists())return a;return null}catch{return null}}var cr=Symbol.for("stx.inline-assets.import-meta");function Vn(n,e){if(!n.includes("import.meta"))return;let c=Error(`[stx] ${e} still references \`import.meta\` after bundling, and it is being inlined as a classic <script> where that is a SyntaxError \u2014 the whole script fails to parse, taking every other script on the page with it.
1289
- `+" `import.meta.env.STX_PUBLIC_*` is substituted at build time and is safe; anything else is not.\n Fix it by moving the module-only code (`import.meta.glob`, `import.meta.url`) into its own module, or by resolving the value without `import.meta`.");throw c[cr]=!0,c}async function lr(n,e,c){let a=n,g=Oe.dirname(e),r=/<script\b([^>]*)src=["']([^"']+)["']([^>]*)><\/script>/gi,d;while((d=r.exec(a))!==null){let[x,w,v,k]=d;if(ir(v))continue;let S=await ar(v,g,e);if(S)try{let M=await Bun.file(S).text();if(c.add(S),v.endsWith(".ts")||v.endsWith(".tsx")){let R=await Bun.build({entrypoints:[S],target:"browser",minify:!0,define:C()});if(R.outputs.length>0)M=await R.outputs[0].text(),Vn(M,v)}let A=`<script>
1290
- // Source: ${v}
1291
- ${M}
1292
- </script>`;a=a.replace(x,A),r.lastIndex=0}catch(M){if(M?.[cr])throw M}}let y=/<link\b([^>]*)href=["']([^"']+)["']([^>]*)(?:\/?>)/gi,h;while((h=y.exec(a))!==null){let[x,w,v,k]=h,S=w+k;if(ir(v))continue;if(/rel=["']stylesheet["']/.test(S)||v.endsWith(".css")){let A=await ar(v,g,e);if(A)try{let R=await Bun.file(A).text();c.add(A);let D=`<style>
1293
- /* Source: ${v} */
1294
- ${R}
1295
- </style>`;a=a.replace(x,D),y.lastIndex=0}catch(R){}}}return a}import ot from"path";var Wn=/(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)(['"])(\.\.?\/[^'"]*)\2/g,Xn=/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/gi;function zn(n,e){if(!e||!n.includes("/"))return n;let c=ot.dirname(e);return n.replace(Wn,(a,g,r,d)=>{let y=ot.resolve(c,d);return`${g}${r}${y.split(ot.sep).join("/")}${r}`})}function ur(n,e){if(!e||!n.includes("<script"))return n;return n.replace(Xn,(c,a,g,r)=>`${a}${zn(g,e)}${r}`)}var Te="<!--PARENT_CONTENT_PLACEHOLDER-->";function fr(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Sr(n,e){let c=n.length,a=e,g=!0,r=[],d=(y)=>y+9<=c&&n[y]==="<"&&n[y+1]==="/"&&(n[y+2]==="s"||n[y+2]==="S")&&(n[y+3]==="c"||n[y+3]==="C")&&(n[y+4]==="r"||n[y+4]==="R")&&(n[y+5]==="i"||n[y+5]==="I")&&(n[y+6]==="p"||n[y+6]==="P")&&(n[y+7]==="t"||n[y+7]==="T")&&(n[y+8]===">"||/\s/.test(n[y+8]));while(a<c){let y=n[a];if(d(a))return a;if(y==="/"&&n[a+1]==="/"){if(a=n.indexOf(`
1296
- `,a+2),a===-1)return-1;a+=1,g=!0;continue}if(y==="/"&&n[a+1]==="*"){let h=n.indexOf("*/",a+2);if(h===-1)return-1;a=h+2,g=!0;continue}if(y==="/"&&g){let h=a+1,x=!1;while(h<c){let w=n[h];if(w==="\\"){h+=2;continue}if(w==="[")x=!0;else if(w==="]")x=!1;else if(w==="/"&&!x){h++;break}else if(w===`
1297
- `){h=-1;break}h++}if(h===-1){a++,g=!1;continue}while(h<c&&/[a-z]/.test(n[h]))h++;a=h,g=!1;continue}if(y==="'"||y==='"'){let h=y;a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]===h){a++;break}if(n[a]===`
1298
- `)break;a++}g=!1;continue}if(y==="`"){a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}if(r.length===0)g=!1;continue}if(y==="}"&&r.length>0){r.pop(),a++;while(a<c){if(n[a]==="\\"){a+=2;continue}if(n[a]==="`"){a++,g=!1;break}if(n[a]==="$"&&n[a+1]==="{"){r.push(!0),a+=2,g=!0;break}a++}continue}if(/\s/.test(y));else if(/[)\].\w$]/.test(y))g=!1;else g=!0;a++}return-1}function Er(n,e){let c=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`<script\\b(?=[^>]*\\b${c}(?:\\s|=|/?>))[^>]*>`,"i").exec(n);if(!a)return null;let g=a.index+a[0].length,r=n.indexOf("</script>",g);if(r===-1)return null;let d=n.indexOf(">",r);if(d===-1)return null;return{start:a.index,end:d+1}}var Gn=4096;async function at(n,e,c){if(c.buildMode!=="serve"||e.length<Gn)return null;let{registerServeModuleBundle:a}=await import("./chunk-qx8cav4w.js");return`<script ${n} src="${a(e)}"></script>`}async function or(n,e,c,a){try{let{registeredModuleIdsIn:g,buildModuleRegistryScript:r}=await o("stx/client-module-registry",()=>import("./chunk-9fz3h6sx.js")),d=[],y=await r(g(...n),{minify:Di(e.buildMode,e.minifyClient),collectInputs:d});for(let h of d)c?.add(h);if(a)a.inputs=d,a.code=y??void 0;if(!y)return null;if(e.buildMode==="serve"){let{registerServeModuleBundle:h}=await import("./chunk-qx8cav4w.js");return`<script data-stx-scoped data-stx-run="always" data-stx-modules src="${h(y)}"></script>`}return`<script data-stx-scoped data-stx-run="always" data-stx-modules>${y.replace(/<\/script/gi,"<\\/script")}</script>`}catch{return null}}async function Zn(n,e,c,a){let g={modulesTag:null,modulesCode:null,storeTag:null,storeCode:null,composableTag:null,composableCode:null,frameworkScript:null};try{let{getFrameworkComposableScript:k}=await o("stx/framework-composables",()=>import("./chunk-mjkdskeg.js"));g.frameworkScript=await k(n)}catch{}let r=null;try{r=await o("stx/store-loader",()=>import("./chunk-5x9ajbq0.js"))}catch{}let d=e.storesDir,y=!!a.__stx_native_screen||(r?.pageStoresAll()??!0),h=y?"":n.replace(/<script\b[^>]*\bdata-stx-(?:runtime|router|hmr)\b[^>]*>[\s\S]*?<\/script>/gi,""),x=[],w=[],v=null;for(let k=0;k<8;k++){let S=null,M="",A=!1;try{if(r){let N=y?await r.getStoreScript(d).then((F)=>F?{code:F,stores:["*"],functions:null}:null):await r.getStoreScriptFor(d,[h],{reads:r.storesReadInFiles([...x,...w]),runOnce:!0});if(N)S=N.code,M=N.stores.join(","),A=!!N.functions&&!y}}catch{}if(v!==null&&M===v)break;v=M;let R=A?'data-stx-scoped data-stx-run="always" data-stx-stores':"data-stx-stores",D=S?`<script ${R}>${S}</script>`:null;g.storeCode=S,g.storeTag=S?await at(R,S,e)??D:null;let j={};g.modulesTag=await or([n,D],e,c,j),g.modulesCode=j.code??null,x=j.inputs??[],g.composableTag=null,g.composableCode=null,w=[];try{let{getComposableScript:N}=await o("stx/composable-loader",()=>import("./chunk-3y7yp0ka.js")),F=e.composablesDir,I=[g.modulesCode??g.modulesTag,D,g.frameworkScript].filter((H)=>H!==null),L=await N(e._layerComposableDirs??F,n,I,w);if(L)g.composableCode=L,g.composableTag=await at('data-stx-scoped data-stx-run="always" data-stx-composables',L,e)??`<script data-stx-scoped data-stx-run="always" data-stx-composables>${L}</script>`}catch{}if(y||!r)break}return g}async function Jn(n,e,c,a={}){let{withModuleSubstitutes:g,moduleSubstitutionKey:r}=await import("./chunk-mad172af.js"),d=await import("./chunk-kh01rvag.js"),{messages:y,webModules:h}=e,x=null,w=null,v=r()===""&&!a.__stx_native_screen;if(y&&d.pageMessagesEnabled(e)&&v)try{x=await d.loadPageMessages(process.cwd(),y)}catch(R){Qn(R)}if(h&&Object.keys(h).length&&v)try{w=await(await import("./chunk-xmy6g81m.js")).loadWebModules(process.cwd(),h)}catch(R){Yn(R)}let k=new Map([...w??[],...x?.stubs??[]]),S=()=>Zn(n,e,c,a),M=k.size?await g(k,S):await S(),A=null;if(x){let R=d.messageAreasIn(M.modulesCode,M.storeCode,M.composableCode),D=d.pageMessagesScript(x,d.pageLanguages(n,x),R);if(D)A=await at('data-stx-scoped data-stx-run="always" data-stx-messages',D,e)??`<script data-stx-scoped data-stx-run="always" data-stx-messages>${D.replace(/<\/script/gi,"<\\/script")}</script>`}return[A,M.modulesTag,M.storeTag,M.composableTag,M.frameworkScript].filter((R)=>R!==null)}var gr=!1;function Qn(n){if(gr)return;gr=!0,console.warn(`[stx] messages: ${n instanceof Error?n.message:String(n)}; pages ship every language`)}var hr=!1;function Yn(n){if(hr)return;hr=!0,console.warn(`[stx] ${n instanceof Error?n.message:String(n)}; pages bundle the real modules`)}function es(n,e=""){let c=Er(n,"data-stx-runtime");if(!c)return n;let a=dr(n);if(a===-1||a===c.start){if(!e)return n;return n.slice(0,c.end)+e+n.slice(c.end)}if(a<c.start)return n.slice(0,a)+n.slice(c.start,c.end)+e+`
1299
- `+n.slice(a,c.start)+n.slice(c.end);let g=n.slice(c.start,c.end),r=n.slice(0,c.start)+n.slice(c.end),d=dr(r);if(d===-1)return g+e+`
1300
- `+r;return r.slice(0,d)+g+e+`
1301
- `+r.slice(d)}function ts(n){let e=/\x00STX_ESC_MUSTACHE_OPEN\x00([\s\S]*?)\x00STX_ESC_MUSTACHE_CLOSE\x00/g;return n.replace(e,(c,a,g)=>{let r=n.slice(0,g);return r.lastIndexOf("<")>r.lastIndexOf(">")?`{{${a}}}`:`{<!--stx-literal-->{${a}}}`})}async function i(n,e,c,a,g){if(await _(),a.ssr===!1&&!a.autoShell&&a.buildMode==="spa")return n;if(e.__stx_signals_gate===void 0)e.__stx_signals_gate=_e(n,c);let r=!e.__stxProcessingDepth;bn(e);for(let d of a._layerGraph?.configDependencies??[])g.add(d);if(r&&a.runtimeConfig)await _n(e,c,a.runtimeConfig);if(r)el(e),e.__stx_scope_seq??={n:0,key:Ks(String(e.__filename??c))},e.__stx_head_injections=Oi(),e.__stx_seo_staged=!1;if(!e.__stxProcessingDepth)e.__stxProcessingDepth=0;if(e.__stxProcessingDepth++,!e.__onceStore)e.__onceStore=new Set;if((a.debug||!T()&&!$n())&&c&&c.endsWith(".stx"))Fo(n,c);try{return await le.timeAsync("template-processing",async()=>{let d=await rs(n,e,c,a,g);if(r)d=vi(d);if(r&&a.autoShell&&a.buildMode!=="compile"){let y=Ee(a.app?.head,{known:Dr,source:"app.head"}),x=(e.__stx_runtime_head||null)??Mi(),w=(e.__stx_head_raw||"").trim(),v,k=w.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(k)v=k[1].trim(),w=w.replace(k[0],"").trim();let S=e.__sections?.title,M=S?E(S,e,c):void 0,A=x.title||v||M,R=!x.title&&(!!v||!!M),D=x.meta||[],j=new Set(D.map((V)=>lt(V)).filter(Boolean)),N={...y,...A&&{title:A},meta:[...(y.meta||[]).filter((V)=>!j.has(lt(V))),...D],link:[...y.link||[],...x.link||[]],script:[...y.script||[],...x.script||[]],headRaw:[y.headRaw,w].filter(Boolean).join(`
1302
- `),...x.htmlAttrs&&{htmlAttrs:yl(y.htmlAttrs,x.htmlAttrs)},...x.bodyAttrs&&{bodyAttrs:{...y.bodyAttrs||{},...x.bodyAttrs}}},F=Ni(d);if(d=Nr(d,N,{...R&&{titleIsHtml:!0},...a.app?.colorMode&&{colorMode:a.app.colorMode}},F),F)d=wl(d,y),d=Or(d,N.htmlAttrs);let I=d.match(/<!-- stx-layout: ([^ ]+) -->/);if(I&&d.includes("<head")){let V=I[1],ae=Ns(V);d=d.replace(/<head\b[^>]*>/i,(X)=>`${X}
1303
- <meta name="stx-layout" content="${fr(V)}">
1304
- <meta name="stx-layout-group" content="${fr(ae)}">`)}let L=d.match(/function (__stx_setup_\w+)\(/),H=L?B(d):null;if(L&&H&&!/\bdata-stx=/.test(H.tag)){d=Qe(d,(ae,X)=>`<body${X} data-stx="${L[1]}">`);let V=new RegExp(`(<(?!body)[a-zA-Z][^>]*) data-stx="${L[1]}"`,"i");d=d.replace(V,"$1")}}if(r){let y=e.__stx_head_injections??Oi(),h=bl(d);if(h!==null)y.beforeClose.push(h);let x=nr(d);if(x!==null)y.afterOpen.push(x);if(a.offline?.enabled&&!d.includes("data-stx-offline"))y.beforeClose.push(sr);d=ml(d,y);let w=a.app?.colorMode;if(w)d=Ir(d,w)}if(r)if(Er(d,"data-stx-runtime")){let h=await Jn(d,a,g,e);d=es(d,h.map((x)=>`
1305
- ${x}`).join(""))}else{let h=await or([d],a,g);if(h){let x=d.search(/<script\b[^>]*>(?:(?!<\/script>)[\s\S])*?__stxModules\[/i);if(x!==-1)d=d.slice(0,x)+h+`
1306
- `+d.slice(x)}}if(r)d=hl(d);if(r&&e.__stx_inject_css!==!1)d=await b(d,void 0,a.buildMode==="serve",!0);else if(r)d=hn(d);if(r)d=pt(d);if(d=d.replace(/\x00STX_ESCAPED_AT\x00/g,"@"),d=ts(d),r&&e.__stx_runtime_config)d=Bt(d,e.__stx_runtime_config);if(r&&!e.__stx_defer_server_data){let y=$r(e);if(y){let h=/<head\b[^>]*>/i.exec(d),x=h?h.index+h[0].length:0;d=d.slice(0,x)+y+d.slice(x)}}return d})}catch(d){if(d instanceof K)throw d;let y=d instanceof Error?d.message:String(d),h=new ee(`Template processing failed: ${y}`,c,void 0,void 0,n.substring(0,200)+(n.length>200?"...":""));if(z.log(h,{filePath:c,context:e}),En.logDetailedError(h,{filePath:c,template:n.substring(0,500)}),T()&&!a.debug)console.error(`[stx] ${se.relative(process.cwd(),c)||c}: ${h.message}`);if(a.debug)throw h;return Pi.createFallbackContent("Template Processing",h)}}async function rs(n,e,c,a,g){let r=process.cwd(),d={...a,partialsDir:a.partialsDir&&!se.isAbsolute(a.partialsDir)?se.resolve(r,a.partialsDir):a.partialsDir,componentsDir:a.componentsDir&&!se.isAbsolute(a.componentsDir)?se.resolve(r,a.componentsDir):a.componentsDir,layoutsDir:a.layoutsDir&&!se.isAbsolute(a.layoutsDir)?se.resolve(r,a.layoutsDir):a.layoutsDir},y=d,h=n;await is(c,e),ss(e,y),h=await Ce(()=>zt(h,e,c,y),h,(I)=>{z.log(I,{filePath:c,phase:"pre-processing-middleware"},"warning"),console.warn(`[stx] pre-processing middleware failed for ${c}: ${I.message}`)}),h=h.replace(/\{\{--[\s\S]*?--\}\}/g,"");let x=ge(h,De,(I,L)=>`\x00STX_HTML_COMMENT_${L}\x00`);h=x.output;let w=x.tokens,v=(I)=>w.length===0?I:I.replace(/\x00STX_HTML_COMMENT_(\d+)\x00/g,(L,H)=>w[Number(H)]??""),k="\x00STX_ESCAPED_AT\x00",S="\x00STX_ESC_MUSTACHE_OPEN\x00",M="\x00STX_ESC_MUSTACHE_CLOSE\x00";h=h.replace(/@@/g,k),h=h.replace(/@\{\{([\s\S]*?)\}\}/g,(I,L)=>`${S}${L}${M}`),h=Qt(h),h=await lr(h,c,g);let A={};h=ds(h,A);let R={...e.__sections||{}},D="",j=bt(vt(n)),N=/@nolayout\b/.test(h)||j===!1;if(/@nolayout\b/.test(h))h=h.replace(/@nolayout\b\s*/g,"");let F=h.match(/@(?:layout|extends)\(\s*['"]([^'"]+)['"]\s*\)/);if(F)D=F[1],h=h.replace(/@(?:layout|extends)\(\s*['"]([^'"]+)['"]\s*\)/g,"");else if(typeof j==="string"){if(D=j,!/@section\s*\(/.test(h))h=`@section('content')
1307
- ${h.trim()}
1308
- @endsection`}if(!D&&!N&&y.defaultLayout){let I=Tn(h),L=/@section\s*\(/.test(h);if(!I||L){let H="",V=se.dirname(c),ae=y.layoutsDir?se.dirname(y.layoutsDir):process.cwd();for(let X=0;X<20;X++){let ce=se.join(V,"_layout.stx");if(await s(ce)){H=ce;break}let oe=se.dirname(V);if(oe===V||oe.length<ae.length)break;V=oe}if(H)D=H;else if(y.layoutsDir){let X=se.isAbsolute(y.layoutsDir)?y.layoutsDir:se.resolve(process.cwd(),y.layoutsDir),ce=se.join(X,`${y.defaultLayout}.stx`);if(await s(ce))D=ce}if(D&&!L)h=`@section('content')
1309
- ${h.trim()}
1310
- @endsection`}}if(D&&h.includes("<script")){let I=J(h),L=I.scripts.map((H)=>yr(H,c)??H);h=kr(I.output,L)}if(h=h.replace(/@section\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)/g,(I,L,H)=>(R[L]=H,"")),h=h.replace(/@section\(\s*['"]([^'"]+)['"]\s*,\s*([^)]+?)\s*\)/g,(I,L,H)=>{if(/^(['"]).*\1$/.test(H.trim()))return I;try{let V=u(H.trim(),e);if(V===void 0)return I;let X=(e.__stx_inline_section_values??=[]).push(V)-1;return R[L]=`{{ __stx_inline_section_values[${X}] }}`,""}catch{return I}}),h=h.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@endsection|@show)/g,(I,L,H)=>{if(H.includes("@parent"))R[L]=H.replace("@parent",Te);else R[L]=H.trim();return""}),e.__sections=R,h=h.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/g,(I,L,H)=>R[L]||H||""),!("slot"in e)||e.slot===void 0)h=h.replace(/\{\{\s*slot\s*\}\}/g,()=>R.content||"");if(h=ps(h,A),D){let I=[],L=J(h),H=ge(L.output,mn,(V,ae)=>`\x00STX_ORPHAN_STYLE_${ae}\x00`);if(h=H.output.replace(/\x00STX_(SCRIPT|ORPHAN_STYLE)_(\d+)\x00/g,(V,ae,X)=>{let ce=ae==="SCRIPT"?yr(L.scripts[Number(X)],c):H.tokens[Number(X)];if(ce)I.push(ce);return""}),I.length>0){let V=I.join(`
1311
- `);R.content=R.content?`${R.content}
1312
- ${V}`:V,e.__sections=R}}if(D)try{let I;if(se.isAbsolute(D))I=D,g.add(D);else I=await Ce(()=>xn(D,c,d,g),null,()=>{throw new ee(`Failed to resolve layout path: ${D}`,c,void 0,void 0,`Layout referenced from ${c}`)});if(!I){let oe=(G)=>{if(!G)return[];try{let ye=se.isAbsolute(G)?G:se.resolve(process.cwd(),G);return Kn.readdirSync(ye).filter((xe)=>xe.endsWith(".stx")).map((xe)=>xe.replace(/\.stx$/,""))}catch{return[]}},te=[...oe(d.layoutsDir),...oe(d.fallbackLayoutsDir)].filter((G,ye,xe)=>xe.indexOf(G)===ye).sort(),he=[d.layoutsDir,d.fallbackLayoutsDir].filter((G)=>typeof G==="string"&&G.length>0),de=he.length>0?` Searched: ${he.join(", ")} (set \`layoutsDir\` to look elsewhere).`:"",re=`Layout not found: ${D} (referenced from ${c})`+(te.length>0?`. Available layouts: ${te.join(", ")}`:d.layoutsDir?`. No .stx layouts found in ${d.layoutsDir}`:"")+de;if(z.log(Error(re),{layoutPath:D,filePath:c,available:te},"error"),console.error(`[stx] ${re}`),d.debug)throw new ee(re,c);return h}let L=await Ce(()=>Bun.file(I).text(),"",()=>{throw new ee(`Failed to read layout file: ${I}`,c,void 0,void 0,"Layout content could not be loaded")});L=ur(L,I),L=L.replace(/\{\{--[\s\S]*?--\}\}/g,"");let H=Array.isArray(e.__layoutChain)?e.__layoutChain:[];if(H.includes(I)){let oe=[...H.slice(H.indexOf(I)),I];throw new ee(oe.length===2?`Circular layout: ${I} extends itself`:`Circular layout: ${oe.join(" -> ")}`,c,void 0,void 0,"Remove the @extends or @layout line that points back at a layout already in use")}let V=L.match(/@(?:layout|extends)\(\s*['"]([^'"]+)['"]\s*\)/);if(V){if(d.debug)console.log(`Found nested layout: ${V[1]} in ${I}`);let oe={},te=L.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(re,G,ye)=>(oe[G]=ye.trim(),""));for(let[re,G]of Object.entries(oe))if(R[re]&&R[re].includes(Te)){let ye=R[re].indexOf(Te);R[re]=R[re].slice(0,ye)+G+R[re].slice(ye+Te.length)}else if(!R[re])R[re]=G;let he={...e,__sections:R,__layoutChain:[...H,I]},de=`@layout('${V[1]}')${te}`;return await i(de,he,I,d,g)}let ae=L.replace(/\{\{--[\s\S]*?--\}\}/g,""),X=ds(ae,A),ce={};return X=X.replace(/@section\(\s*['"]([^'"]+)['"]\s*\)([\s\S]*?)(?:@show|@endsection)/g,(oe,te,he)=>(ce[te]=he.trim(),`@slot('${te}')`)),X=X.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(oe,te,he)=>{if(R[te]){let de=R[te];if(de.includes(Te)){let re=ce[te]||"",G=de.indexOf(Te);de=de.slice(0,G)+re+de.slice(G+Te.length)}return de}return he||""}),X=ns(X,R),X=X.replace(/\{\{\s*slot\s*\}\}/g,()=>R.content||""),X=ps(X,A),e.__originalFilePath=c,h=await xr(X,e,I,d,g),h=`<!-- stx-layout: ${D} -->
1313
- ${h}`,v(h)}catch(I){if(I instanceof K)throw I;throw new ee(`Error processing layout ${D}: ${I instanceof Error?I.message:String(I)}`,c)}return v(await xr(h,e,c,d,g))}function ns(n,e){return n.replace(/@(?:yield|slot)\(\s*['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"]\s*)?\)/g,(c,a,g)=>{let r=e[a];if(r!==void 0){if(!new RegExp(`@(?:yield|slot)\\(\\s*['"]${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}['"]`).test(r))return r}return g||""})}function ss(n,e){if(n.__stx_sfc_mode=!0,n.__stx_options=e,e.buildMode)n.__stx_buildMode=e.buildMode;let c=e.envPrefix||"STX_PUBLIC_",a={};for(let[g,r]of Object.entries(process.env))if(g.startsWith(c)&&r!==void 0)a[g]=r;n.$env=a}async function is(n,e){await Ce(()=>Zt(n,e),void 0,(c)=>{z.log(c,{filePath:n,phase:"view-composer"},"warning"),console.warn(`[stx] view composer failed for ${n}: ${c.message}`)})}var ct="data-stx-source";function yr(n,e){if(!n)return n;let c=/^<script\b([^>]*)>/i.exec(n);if(!c||!/\bserver\b/.test(c[1])||c[1].includes(ct))return n;return`<script ${ct}="${encodeURIComponent(e)}"${n.slice(7)}`}function os(n){let e=new RegExp(`${ct}="([^"]*)"`).exec(n);return e?decodeURIComponent(e[1]):void 0}function wr(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function vr(n,e,c){return`<div data-stx-server-script-error role="alert" style="padding:12px 14px;border:1px solid #f0b4b4;border-left-width:4px;background:#fff5f5;color:#7a1f1f;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace"><strong style="display:block;margin-bottom:4px">stx: a &lt;script server&gt; ${e==="module-resolution"?"imports a module that does not resolve":e==="syntax"?"does not parse":"names something that does not exist"}, so this component rendered nothing.</strong><span style="display:block;opacity:.85">${wr(n)}</span><span style="display:block;margin-top:4px">${wr(c)}</span></div>`}async function as(n,e,c,a){let{scanScriptTags:g}=await o("stx/signal-processing",()=>import("./chunk-pybm7c9p.js")),r=[],d=!T()&&!$n();for(let h of g(n)){let x=h.attrs;if(!/\bserver\b/.test(x))continue;let w=h.start+h.fullMatch.indexOf(">")+1,v=Sr(n,w);if(v===-1)continue;let k=n.slice(w,v);if(!k.trim())continue;let S=os(x)??c,M={index:h.start,length:v+9-h.start};try{let{extractVariables:A}=await o("stx/variable-extractor",()=>import("./chunk-2wba5ypm.js"));await A(k,e,S,{preserveExisting:!0,onFailure:(R)=>{if(R.kind==="unknown")return;if(a?.onServerScriptError?.({sourcePath:S,kind:R.kind,message:R.message}),!d)return;r.push({...M,markup:vr(S,R.kind,R.message)})}})}catch(A){let R=A instanceof Error?A:Error(String(A));if(z.log(R,{filePath:S,phase:"server-script-extraction"},"warning"),console.warn(`[stx] server <script> extraction failed in ${S}: ${R.message}`),d)r.push({...M,markup:vr(S,"unknown",R.message)})}}if(r.length===0)return n;let y=n;for(let h of r.sort((x,w)=>w.index-x.index))y=y.slice(0,h.index)+h.markup+y.slice(h.index+h.length);return y}async function cs(n,e,c){try{let{interpolateScriptsInTemplate:a}=await o("stx/expressions",()=>import("./chunk-zrm2x65c.js"));return a(n,e,{skipServer:!0})}catch(a){let g=a instanceof Error?a:Error(String(a));return z.log(g,{filePath:c,phase:"script-expression-interpolation"},"warning"),console.warn(`[stx] script expression interpolation failed in ${c}: ${g.message}`),n}}async function xr(n,e,c,a,g){let r=n;await _();let d=a;if(r=await as(r,e,c,a),r=await Ht(r,e,c),r=await Ut(r,e,c),r=await cs(r,e,c),await _(),r=await At(r,e,c,d),_e(r))r=Xo(r,e),r=vs(r,e),r=ws(r,e);r=Jo(r),await _();let{processStreamDirectives:y}=await o("stx/streaming",()=>import("./chunk-ck5nzbbv.js"));r=y(r,e),r=await Uo(r,e,c,d,!0),await _(),r=await rr(r,e,c,d,g),r=await ms(r,e,c,d,g),await _(),r=Sc(r,e,c,d);let{processDeferDirectives:h}=await o("stx/defer",()=>import("./chunk-6g7tkmty.js"));r=h(r,e,c);let{processTeleportDirectives:x}=await o("stx/teleport",()=>import("./chunk-c9y1g61m.js"));r=x(r,e,c);let{processTransitionDirectives:w,processTransitionAttributes:v}=await o("stx/transitions",()=>import("./chunk-y86mpnrg.js"));r=w(r,e,c),r=v(r);let{processErrorBoundaryDirectives:k,stripRenderFailedMarkers:S}=await o("stx/error-boundaries",()=>import("./chunk-h85hrwkq.js"));r=k(r,e,c),r=S(r);let{processSuspenseDirectives:M}=await o("stx/suspense",()=>import("./chunk-9jr30fns.js"));r=M(r,e,c);let{processAsyncDirectives:A}=await o("stx/async-components",()=>import("./chunk-fcbpzdyz.js"));r=A(r,e,c);let{processKeepAliveDirectives:R}=await o("stx/keep-alive",()=>import("./chunk-41wwqw0q.js"));r=R(r,e,c);let{processVirtualListDirectives:D,processVirtualGridDirectives:j,processInfiniteListDirectives:N}=await o("stx/virtual-scrolling",()=>import("./chunk-asr5v51s.js"));r=D(r,e,c),r=j(r,e,c),r=N(r,e,c),await _();let{processPartialHydrationDirectives:F,processStaticDirectives:I}=await o("stx/partial-hydration",()=>import("./chunk-fahqq7c4.js"));r=F(r,e,c),r=I(r);let{processComputedDirectives:L,processWatchDirectives:H}=await o("stx/computed",()=>import("./chunk-1xdzcy9d.js"));r=L(r,e,c),r=H(r,e,c);let{processFormValidationDirectives:V}=await o("stx/forms-validation",()=>import("./chunk-kepxsjfx.js"));r=V(r,e,c);let{processHeadDirective:ae,processTitleDirective:X,processMetaDirective:ce,resetHead:oe}=await o("stx/head",()=>import("./chunk-zm0g7ntw.js"));if(!e.__stx_head_preset&&!e.__stx_runtime_head)oe();let te=ae(r);if(r=te.content,te.headContent)e.__stx_head_raw=`${e.__stx_head_raw||""}${te.headContent}
1314
- `;if(r=X(r,e),r=ce(r,e,c),r=Gt(r),r=Wo(r,e),r=Tt(r),r=Wt(r),r=await us(r,e,c,d,g),r=await ms(r,e,c,d,g),await _(),r=r.replace(/@push\s*\(\s*['"][^'"]+['"]\s*\)[\s\S]*?@endpush/g,""),r=vi(r),r=ie(r,e,c),r=hs(r),await _(),e.__stxProcessingDepth===1)r=tl(r,e);if(r=Xc(r,e,{filePath:c,buildMode:d.buildMode}),r=qo(r,e),r=Ko(r,e),r=ze(r,e),r=Pt(r,e),r=jt(r,e),r=await wt(r,e,c,d),r=await _c(r,e,c),r=await Ec(r,e,c,d),await _(),r=Tc(r,e,c,d),r=ri(r,e,c,d),r=si(r,e,c),r=oi(r,e,c,d),r=_t(r,e,c,d),r=Ws(r,e),r=qs(r),r=Yc(r),!d.skipEventDirectives)r=Bc(r,e,c);if(r=Jc(r,e,c,a.skipSignalsRuntime===!0&&Number(e.__stxProcessingDepth)>0),await _(),d.debug){let U=/\bx-data\s*=/.test(r),q=bs(n);if(U&&q)console.warn(`[stx] ${c}: Template mixes Alpine-style (x-data) and signals (state/derived/effect) reactivity.
1315
- Both work on the same page, but they manage separate scopes.
1316
- Prefer signals (state/derived/effect) for new components.`)}r=yc(r,e),r=await Ti(r,e,c),await _(),r=Zc(r),r=Qc(r),r=ht(r);let{processXElementDirectives:he}=await o("stx/x-element",()=>import("./chunk-zhxdpzga.js"));r=he(r);let de=e.__originalFilePath||c,re=je(e);if(r=await Yo(r,d,de,re),await _(),r=It(r,e),r=await Kt(r,e,c,d),await _(),d.media?.image?.autoSiblings){let U=d.publicDir||"public",{rewriteImagesWithSiblings:q}=await o("stx/image-optimization/auto-sibling",()=>import("./chunk-k9fsd6t3.js"));r=await q(r,{publicDir:U})}if(d.seo?.enabled)r=ii(r,e,d);let G=(U,q,Z=!0)=>{if(!q)return U;let me=q.match(/<title\b[^>]*>[\s\S]*?<\/title>/i),ne=/<head\b[^>]*>[\s\S]*?(?:<\/head\s*>|<body\b|$)/i.exec(U),pe=ne?/<title\b[^>]*>[\s\S]*?<\/title>/i.exec(ne[0]):null;if(me&&ne&&pe){if(Z){let Ae=ne.index+pe.index;U=U.slice(0,Ae)+me[0]+U.slice(Ae+pe[0].length)}if(q=q.replace(me[0],"").trim(),!q)return U}if(/<\/head>/i.test(U))return U.replace(/<\/head>/i,`${q}
1317
- </head>`);if(/<head\b[^>]*>/i.test(U))return U.replace(/(<head\b[^>]*>)/i,`$1
1318
- ${q}`);if(/<html\b[^>]*>/i.test(U))return U.replace(/(<html\b[^>]*>)/i,`$1
1319
- <head>
1320
- ${q}
1321
- </head>`);return U},{renderHead:ye,getHead:xe}=await o("stx/head",()=>import("./chunk-zm0g7ntw.js")),Le=e.__stx_runtime_head??xe();if(Le.title||Le.meta?.length||Le.link?.length){let U=ye(Le);if(U)r=G(r,U)}if(te.headContent)r=G(r,te.headContent,!Le.title);if(d.csp?.enabled&&d.csp.addMetaTag)r=$t(r,d.csp,e);if(d.analytics?.enabled)r=yt(r,d);if(d.heatmap?.enabled)r=kc(r,d);if(d.pwa?.enabled&&d.pwa.autoInject!==!1){let{injectPwaTags:U}=await o("stx/pwa/inject",()=>import("./chunk-5mg443dw.js"));r=U(r,d)}let _r=/<script\b(?![^>]*\bserver\b)[^>]*>[\s\S]*?<\/script>/i.test(r),Cr=/\bSTX\.\w+/.test(r),Tr=/window\.STX\s*=/.test(r);if(_r&&Cr&&!Tr){let q=`<script data-stx-scoped data-stx-run="once">
1322
- ${ft()}
1323
- </script>`;if(r.includes("</head>")){let Z=r.indexOf("</head>"),ne=r.slice(0,Z).indexOf("<script");if(ne!==-1){let pe=r.slice(0,ne),Ae=r.slice(ne);r=pe+q+`
1324
- `+Ae}else r=r.replace("</head>",`${q}
1325
- </head>`)}else if(r.includes("<body"))r=r.replace(/<body([^>]*)>/,`<body$1>
1326
- ${q}`);else r=q+`
1327
- `+r}{let{scanScriptTags:U}=await o("stx/signal-processing",()=>import("./chunk-pybm7c9p.js")),q=[];for(let Z of U(r)){if(!/\bserver\b/i.test(Z.attrs))continue;let me=Z.start+Z.fullMatch.indexOf(">")+1,ne=Sr(r,me);if(ne===-1)continue;let pe=ne+9;while(pe<r.length&&/\s/.test(r[pe]))pe++;q.push({start:Z.start,end:pe})}if(q.length>0){let Z=Array(q.length+1),me=0;for(let ne=0;ne<q.length;ne++){let{start:pe,end:Ae}=q[ne];Z[ne]=r.slice(me,pe),me=Ae}Z[q.length]=r.slice(me),r=Z.join("")}}let ut=Vs(r,c);if(ut.hasScoped)r=ut.html;let Ar=e.__stx_event_bindings||[],Ge=!1,dt=[],Rr=/\s:[a-z][\w.-]*\s*=/.test(r),{scanScriptTags:Mr}=await o("stx/signal-processing",()=>import("./chunk-pybm7c9p.js"));for(let U of Mr(r,{skipAttrs:/\bserver\b|\bsrc\s*=|\bdata-stx-scoped\b|\bdata-stx-router\b|\btype\s*=\s*["'](?!(?:text\/javascript|application\/javascript|module)["'])[^"']*["']/}))dt.push({match:U.fullMatch,attrs:U.attrs,content:U.body});for(let{match:U,attrs:q,content:Z}of dt){Ge=!0;let me=Z;Me(Z,c,a.strict,e.__originalFilePath);let ne=await Be(Z,{eventBindings:Ar,attrs:q,hasColonDirectives:Rr,templateContent:n,filePath:c,projectRoot:process.cwd(),production:Di(a.buildMode,a.minifyClient),serverData:re});r=r.replace(U,()=>ne)}if(Ge)e.__stx_event_bindings=[];if(!Ge&&e.__stxProcessingDepth===1){let U=e.__stx_event_bindings||[];if(U.length>0){let q=fi(U);if(q){let Z=r.lastIndexOf("</body>");r=Z===-1?r+q:r.slice(0,Z)+q+`
1328
- `+r.slice(Z)}e.__stx_event_bindings=[]}}if(!d.skipSignalsRuntime&&!ve(r)&&wc(r))r=await pr(r,d);if(r=vc(r),d.csp?.enabled&&d.csp.useNonce&&typeof e.cspNonce==="string")r=Et(r,e.cspNonce);return r}
1329
- export{vt,Pe,fc,ls,jo,Bo,or,i};