@stacksjs/stx 0.2.631 → 0.2.633

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 (193) hide show
  1. package/dist/{chunk-hc1m2psz.js → chunk-0hs8jgw5.js} +2 -2
  2. package/dist/chunk-0mgtrbaa.js +2 -0
  3. package/dist/{chunk-myhxapnn.js → chunk-0qt1887j.js} +2 -2
  4. package/dist/{chunk-b5cv9xp7.js → chunk-0xc6rncm.js} +206 -206
  5. package/dist/chunk-1tpr8d8n.js +2 -0
  6. package/dist/chunk-20kjbf3h.js +2 -0
  7. package/dist/{chunk-776f05vk.js → chunk-236twqn4.js} +3 -3
  8. package/dist/chunk-27784ceh.js +20 -0
  9. package/dist/{chunk-nz6bzffm.js → chunk-2bxsc7gf.js} +4 -4
  10. package/dist/chunk-3gcg3gvy.js +2 -0
  11. package/dist/{chunk-1ma56c2h.js → chunk-3kkf43fv.js} +2 -2
  12. package/dist/chunk-3wsrhj0k.js +2 -0
  13. package/dist/{chunk-z6fb4m1j.js → chunk-3yh585yv.js} +3 -3
  14. package/dist/chunk-575cqc6z.js +2 -0
  15. package/dist/{chunk-s0ar60ng.js → chunk-5x59qjzs.js} +6 -6
  16. package/dist/chunk-5x836mv3.js +2 -0
  17. package/dist/chunk-5yceay9n.js +2 -0
  18. package/dist/{chunk-7ky2ny63.js → chunk-6bhaa9g7.js} +7 -7
  19. package/dist/{chunk-vfbdxxbf.js → chunk-6dzqjbsz.js} +2 -2
  20. package/dist/chunk-6pg2kxsq.js +2 -0
  21. package/dist/{chunk-qpbd2fwp.js → chunk-72p9brmx.js} +4 -4
  22. package/dist/{chunk-b9kn62k3.js → chunk-7gq7w95h.js} +4 -4
  23. package/dist/chunk-7nthebqr.js +2 -0
  24. package/dist/{chunk-xrj3tekf.js → chunk-7q55jxf5.js} +2 -2
  25. package/dist/chunk-7s5304ae.js +2 -0
  26. package/dist/{chunk-a669q9b8.js → chunk-86zj56pf.js} +5 -5
  27. package/dist/{chunk-evs5gb3q.js → chunk-8b2452m1.js} +8 -8
  28. package/dist/chunk-8dybd0g5.js +2 -0
  29. package/dist/chunk-8em788gc.js +2 -0
  30. package/dist/{chunk-fskpdva4.js → chunk-8hjrr8j3.js} +16 -16
  31. package/dist/{chunk-1e25xd0z.js → chunk-8kc6byaz.js} +4 -4
  32. package/dist/{chunk-9b4e815s.js → chunk-8qrhz7n7.js} +4 -4
  33. package/dist/{chunk-8gksvwsm.js → chunk-90pe63me.js} +2 -2
  34. package/dist/{chunk-q2p6y0cn.js → chunk-923vrf9c.js} +4 -4
  35. package/dist/{chunk-179c1rdn.js → chunk-94yycjz8.js} +2 -2
  36. package/dist/{chunk-88d5s6v3.js → chunk-968jp303.js} +3 -3
  37. package/dist/chunk-9svygzeg.js +2 -0
  38. package/dist/chunk-9z4qr5w9.js +2 -0
  39. package/dist/{chunk-av9zf0zb.js → chunk-a887js9p.js} +4 -4
  40. package/dist/chunk-af4ss0p5.js +2 -0
  41. package/dist/chunk-aj34t5h3.js +2 -0
  42. package/dist/chunk-atcy4zq6.js +2 -0
  43. package/dist/{chunk-hfe8g644.js → chunk-avt9cske.js} +6 -6
  44. package/dist/chunk-az28kd7f.js +2 -0
  45. package/dist/{chunk-q7t2mtn4.js → chunk-bd5na0h0.js} +5 -5
  46. package/dist/{chunk-6684b8ym.js → chunk-bng1ayzm.js} +9 -9
  47. package/dist/chunk-cncdgxk3.js +2 -0
  48. package/dist/{chunk-70npkeh2.js → chunk-cy1j2zpr.js} +2 -2
  49. package/dist/{chunk-rns21kkv.js → chunk-d2t2pq1s.js} +2 -2
  50. package/dist/chunk-dcx2t3sy.js +2 -0
  51. package/dist/chunk-dn28q0m3.js +2 -0
  52. package/dist/chunk-dn89zg1v.js +2 -0
  53. package/dist/chunk-dwddzp5f.js +2 -0
  54. package/dist/chunk-enchx79c.js +2 -0
  55. package/dist/chunk-ev8ma4ph.js +2 -0
  56. package/dist/{chunk-27h1xs4k.js → chunk-fdy0hka5.js} +9 -9
  57. package/dist/{chunk-4y06ekvt.js → chunk-ftkrsvqp.js} +1 -1
  58. package/dist/chunk-ftrsaag8.js +2 -0
  59. package/dist/{chunk-6mtth8d1.js → chunk-g2rxbaah.js} +3 -3
  60. package/dist/{chunk-a2ztn8cr.js → chunk-g35zftfn.js} +1 -1
  61. package/dist/chunk-g6efz3ww.js +2 -0
  62. package/dist/{chunk-7f1dw9r4.js → chunk-gd59tkhr.js} +1 -1
  63. package/dist/{chunk-8e9hd2jq.js → chunk-gqdh68vx.js} +2 -2
  64. package/dist/{chunk-604hzs2x.js → chunk-gv15dd41.js} +3 -3
  65. package/dist/{chunk-xh98er3b.js → chunk-gxpgwpq7.js} +2 -2
  66. package/dist/chunk-h1g9m148.js +2 -0
  67. package/dist/chunk-h8tew5mz.js +2 -0
  68. package/dist/{chunk-x17fpc0x.js → chunk-hdrcgepx.js} +3 -3
  69. package/dist/chunk-hn64343d.js +2 -0
  70. package/dist/chunk-j5jkh05f.js +2 -0
  71. package/dist/chunk-j90yng9b.js +2 -0
  72. package/dist/chunk-jabb3v4c.js +2 -0
  73. package/dist/{chunk-7a8jkwah.js → chunk-jbmjcs83.js} +2 -2
  74. package/dist/chunk-jczvjn7z.js +2 -0
  75. package/dist/{chunk-qvqgbvfa.js → chunk-jq7ymh7q.js} +6 -6
  76. package/dist/{chunk-62kxavc5.js → chunk-jzmz66a3.js} +3 -3
  77. package/dist/{chunk-7cw0wkbx.js → chunk-k5atee35.js} +1 -1
  78. package/dist/{chunk-2wvz3fd2.js → chunk-kpxty3pe.js} +2 -2
  79. package/dist/chunk-kqkhcbrx.js +2 -0
  80. package/dist/chunk-mgzegkvk.js +2 -0
  81. package/dist/chunk-mk71833d.js +2 -0
  82. package/dist/chunk-n3s3w1f5.js +2 -0
  83. package/dist/{chunk-yq9rfnd6.js → chunk-nh7bcc4h.js} +2 -2
  84. package/dist/chunk-nj0b4ryt.js +2 -0
  85. package/dist/{chunk-wp3qcfb4.js → chunk-ny6enm8b.js} +2 -2
  86. package/dist/{chunk-y5hdc1sb.js → chunk-p4hmv654.js} +2 -2
  87. package/dist/{chunk-85g35me6.js → chunk-p77g4mhy.js} +2 -2
  88. package/dist/chunk-p8ndfekp.js +2 -0
  89. package/dist/{chunk-w9c7z8p3.js → chunk-pbphq5pj.js} +2 -2
  90. package/dist/{chunk-85bbtv3m.js → chunk-pk757m0k.js} +1 -1
  91. package/dist/{chunk-tmbqz710.js → chunk-pxpmx8vc.js} +1 -1
  92. package/dist/{chunk-7zwsgjy4.js → chunk-q6evk3a4.js} +2 -2
  93. package/dist/chunk-qhjm9hvz.js +2 -0
  94. package/dist/chunk-qzy34xmt.js +2 -0
  95. package/dist/chunk-ra40trfh.js +2 -0
  96. package/dist/chunk-rjq597cn.js +2 -0
  97. package/dist/{chunk-dz4hrgw8.js → chunk-rq1c46zb.js} +4 -4
  98. package/dist/chunk-rrdwynz4.js +2 -0
  99. package/dist/{chunk-cbj2hmx5.js → chunk-sg5zgq5v.js} +4 -4
  100. package/dist/chunk-shhtbdnj.js +2 -0
  101. package/dist/chunk-t4g97h08.js +2 -0
  102. package/dist/{chunk-qfppetcn.js → chunk-t7e9y46s.js} +1 -1
  103. package/dist/chunk-t7f9zmy8.js +2 -0
  104. package/dist/{chunk-t84ww3qb.js → chunk-tc7gm68a.js} +1 -1
  105. package/dist/{chunk-kf2vas4j.js → chunk-tn7hgtyn.js} +4 -4
  106. package/dist/{chunk-pfas39mf.js → chunk-tx4xxpgg.js} +3 -3
  107. package/dist/{chunk-0jeqp6yz.js → chunk-v4tmwamd.js} +2 -2
  108. package/dist/{chunk-y2t8xd39.js → chunk-vhktd16g.js} +2 -2
  109. package/dist/{chunk-2vqz7v37.js → chunk-w8bf4mbw.js} +3 -3
  110. package/dist/{chunk-mer3aea0.js → chunk-w9e17a74.js} +3 -3
  111. package/dist/chunk-x1xx8qt0.js +2 -0
  112. package/dist/{chunk-h4ashx84.js → chunk-xm911f1g.js} +1 -1
  113. package/dist/chunk-xmfhb2v0.js +2 -0
  114. package/dist/{chunk-7mpv1a02.js → chunk-xrkechs8.js} +4 -4
  115. package/dist/{chunk-3p2b88pd.js → chunk-xrrkf04f.js} +2 -2
  116. package/dist/chunk-xsw183n7.js +2 -0
  117. package/dist/chunk-xtwe2rnp.js +2 -0
  118. package/dist/{chunk-b7p3yca7.js → chunk-y04hzz4w.js} +2 -2
  119. package/dist/chunk-y84n0dvg.js +2 -0
  120. package/dist/{chunk-d1ya7f79.js → chunk-y89m80pf.js} +4 -4
  121. package/dist/{chunk-aqra0qcg.js → chunk-ygpa12ez.js} +2 -2
  122. package/dist/chunk-zr0k9pz5.js +2 -0
  123. package/dist/{chunk-e6ccfmx9.js → chunk-zs7t42b5.js} +5 -5
  124. package/dist/chunk-zytcxy8p.js +2 -0
  125. package/dist/cli.js +19 -19
  126. package/dist/client-script-bundler.d.ts +11 -0
  127. package/dist/client-script-bundler.js +31 -8
  128. package/dist/craft-entry.js +2 -2
  129. package/dist/craft.js +2 -2
  130. package/dist/native/components/primitives.d.ts +1 -0
  131. package/dist/process.js +2 -2
  132. package/dist/pwa.js +3 -3
  133. package/dist/ssg.js +3 -3
  134. package/dist/utils.d.ts +10 -0
  135. package/dist/utils.js +24 -2
  136. package/package.json +5 -5
  137. package/dist/chunk-05zhvg8t.js +0 -20
  138. package/dist/chunk-0c31twby.js +0 -2
  139. package/dist/chunk-0nvb2x2f.js +0 -2
  140. package/dist/chunk-2aj6bjyd.js +0 -2
  141. package/dist/chunk-3jda301z.js +0 -2
  142. package/dist/chunk-46qg1tqe.js +0 -2
  143. package/dist/chunk-4eb02a0z.js +0 -2
  144. package/dist/chunk-5fjb6avv.js +0 -2
  145. package/dist/chunk-5kprybdd.js +0 -2
  146. package/dist/chunk-6n6nnt33.js +0 -2
  147. package/dist/chunk-6per0k6j.js +0 -2
  148. package/dist/chunk-7zjv015g.js +0 -2
  149. package/dist/chunk-87nt0kty.js +0 -2
  150. package/dist/chunk-8a3sdg2y.js +0 -2
  151. package/dist/chunk-8vbfbtke.js +0 -2
  152. package/dist/chunk-8yycg9pb.js +0 -2
  153. package/dist/chunk-91ranpvz.js +0 -2
  154. package/dist/chunk-96ypgjm4.js +0 -2
  155. package/dist/chunk-9cg6q8mw.js +0 -2
  156. package/dist/chunk-9e1vjey6.js +0 -2
  157. package/dist/chunk-ag4eck6d.js +0 -2
  158. package/dist/chunk-aq02drjz.js +0 -2
  159. package/dist/chunk-ayt4qd82.js +0 -2
  160. package/dist/chunk-b3mazye4.js +0 -2
  161. package/dist/chunk-bn6sarwd.js +0 -2
  162. package/dist/chunk-c7xt5gyb.js +0 -2
  163. package/dist/chunk-cac98pkx.js +0 -2
  164. package/dist/chunk-czg6ewy3.js +0 -2
  165. package/dist/chunk-dcwmcqbr.js +0 -2
  166. package/dist/chunk-ed1qn902.js +0 -2
  167. package/dist/chunk-ev479f3z.js +0 -2
  168. package/dist/chunk-gmg6aj7y.js +0 -2
  169. package/dist/chunk-j2jm2nqz.js +0 -2
  170. package/dist/chunk-jb8d4n60.js +0 -2
  171. package/dist/chunk-kdnbxwkb.js +0 -2
  172. package/dist/chunk-khzdk7q9.js +0 -2
  173. package/dist/chunk-kt5mzw2w.js +0 -2
  174. package/dist/chunk-kt994306.js +0 -2
  175. package/dist/chunk-mezphhpa.js +0 -2
  176. package/dist/chunk-n7d69a2q.js +0 -2
  177. package/dist/chunk-qz3tnvwm.js +0 -2
  178. package/dist/chunk-rq9cbw2y.js +0 -2
  179. package/dist/chunk-spvr2vvh.js +0 -2
  180. package/dist/chunk-t91250ag.js +0 -2
  181. package/dist/chunk-txkc9w9q.js +0 -2
  182. package/dist/chunk-ty1c2276.js +0 -2
  183. package/dist/chunk-vepjs3tg.js +0 -2
  184. package/dist/chunk-w21444rc.js +0 -2
  185. package/dist/chunk-wfp754ya.js +0 -2
  186. package/dist/chunk-x3sbsxdq.js +0 -2
  187. package/dist/chunk-xdcvp8tt.js +0 -2
  188. package/dist/chunk-y4egzqqf.js +0 -2
  189. package/dist/chunk-y4nm9wq4.js +0 -2
  190. package/dist/chunk-ygx0akfn.js +0 -2
  191. package/dist/chunk-yn9fwnq2.js +0 -2
  192. package/dist/chunk-z0gfb7b4.js +0 -2
  193. package/dist/chunk-z3e54btj.js +0 -2
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{ee}from"./chunk-d1ya7f79.js";import{be,_}from"./chunk-3p2b88pd.js";import{Vi}from"./chunk-nz6bzffm.js";import{a}from"./chunk-wp3qcfb4.js";import v from"fs";import m from"path";import{pathToFileURL as I}from"url";var P=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],R=new Set;function It(s,l={}){let o=m.resolve(s,l.dir??"server/api"),i=[],f=new Map;if(!v.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let u=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=u.pop(),c=n.lastIndexOf("."),d=c>=0?n.slice(c+1):"get",g=d.toUpperCase();if(!P.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${P.map((A)=>A.toLowerCase()).join(", ")}`);if(c>=0)n=n.slice(0,c);if(n!=="index")u.push(n);let r=new Set,h=u.map((A,j)=>{let y=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(A);if(y){if(r.has(y[2])||y[1]&&j!==u.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(y[2]),`:${y[2]}${y[1]?"*":""}`}if(!/^[\w-]+$/.test(A))throw Error(`Unsupported API path segment ${A} in ${e}`);return A}),w=`/api${h.length?`/${h.join("/")}`:""}`,S=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(S))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(S)} and ${e}`);f.set(S,e);let x=m.join(o,e);R.add(m.resolve(x)),R.add(v.realpathSync(x)),i.push({pattern:w,method:g,filePath:x})}return i.sort((e,p)=>{let u=e.pattern.split("/"),n=p.pattern.split("/"),c=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(u.length,n.length);d++){let g=c(n[d])-c(u[d]);if(g)return g}return e.pattern.localeCompare(p.pattern)||e.method.localeCompare(p.method)})}async function ps(s,l){let o=a(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:p}=ee(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${p.map((u)=>`${JSON.stringify(u)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
2
+ import{ee}from"./chunk-y89m80pf.js";import{be,_}from"./chunk-xrrkf04f.js";import{Ui}from"./chunk-2bxsc7gf.js";import{a}from"./chunk-ny6enm8b.js";import v from"fs";import m from"path";import{pathToFileURL as I}from"url";var P=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],R=new Set;function It(s,l={}){let o=m.resolve(s,l.dir??"server/api"),i=[],f=new Map;if(!v.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let u=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=u.pop(),c=n.lastIndexOf("."),d=c>=0?n.slice(c+1):"get",g=d.toUpperCase();if(!P.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${P.map((A)=>A.toLowerCase()).join(", ")}`);if(c>=0)n=n.slice(0,c);if(n!=="index")u.push(n);let r=new Set,h=u.map((A,j)=>{let y=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(A);if(y){if(r.has(y[2])||y[1]&&j!==u.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(y[2]),`:${y[2]}${y[1]?"*":""}`}if(!/^[\w-]+$/.test(A))throw Error(`Unsupported API path segment ${A} in ${e}`);return A}),w=`/api${h.length?`/${h.join("/")}`:""}`,S=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(S))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(S)} and ${e}`);f.set(S,e);let x=m.join(o,e);R.add(m.resolve(x)),R.add(v.realpathSync(x)),i.push({pattern:w,method:g,filePath:x})}return i.sort((e,p)=>{let u=e.pattern.split("/"),n=p.pattern.split("/"),c=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(u.length,n.length);d++){let g=c(n[d])-c(u[d]);if(g)return g}return e.pattern.localeCompare(p.pattern)||e.method.localeCompare(p.method)})}async function ps(s,l){let o=a(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:p}=ee(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${p.map((u)=>`${JSON.stringify(u)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
3
3
  `);if(!await Bun.file(o).exists()||await Bun.file(o).text()!==f)await Bun.write(o,f);return o}async function gs(s,l,o={}){let i=It(s,o);await ps(s,i);let f=[];for(let t of i){let e=await Bun.build({entrypoints:[t.filePath],target:"bun",format:"esm",minify:!1,splitting:!1});if(!e.success)throw Error(`API build failed for ${t.filePath}: ${e.logs.join(`
4
- `)}`);let p=e.outputs.find((c)=>c.kind==="entry-point");if(!p)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await p.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),p),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...ee(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,p=(r)=>r.replace(/:\w+/g,":param"),u=t.filter((r)=>p(r.route.pattern)===p(e)),n=i.method,c=u.find((r)=>r.route.method===n)??(n==="HEAD"?u.find((r)=>r.route.method==="GET"):void 0);if(!c){let r=new Set(u.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=c.regex.exec(f),g=Object.create(null);try{c.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(c.route);if(typeof r!=="function")throw Error(`API endpoint ${c.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function ms(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function Ju(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=It(s,o);return await ps(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=It(s,o);await ps(s,t);let{loadStxConfig:e}=await import("./chunk-yn9fwnq2.js"),p=_((await e(s)).runtimeConfig);return await be(p,()=>E(t,async(u)=>{let n=await Bun.build({entrypoints:[u.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
5
- `));let c=n.outputs.find((d)=>d.kind==="entry-point");if(!c||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${u.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await c.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function hs(s,l,o){if(Vi(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(v.realpathSync(s))))return!0}catch{}if(R.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(l,typeof o==="object"?o.dir??"server/api":"server/api"),t=(p)=>{try{return v.realpathSync(p)}catch{return m.resolve(p)}},e=t(s);return[f,m.resolve(l,"server"),m.resolve(l,".output/server")].some((p)=>{let u=t(p);return e===u||e.startsWith(`${u}${m.sep}`)})}
6
- export{It,ps,gs,ms,Ju,hs};
4
+ `)}`);let p=e.outputs.find((c)=>c.kind==="entry-point");if(!p)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await p.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),p),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...ee(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,p=(r)=>r.replace(/:\w+/g,":param"),u=t.filter((r)=>p(r.route.pattern)===p(e)),n=i.method,c=u.find((r)=>r.route.method===n)??(n==="HEAD"?u.find((r)=>r.route.method==="GET"):void 0);if(!c){let r=new Set(u.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=c.regex.exec(f),g=Object.create(null);try{c.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(c.route);if(typeof r!=="function")throw Error(`API endpoint ${c.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function ms(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function Zu(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=It(s,o);return await ps(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=It(s,o);await ps(s,t);let{loadStxConfig:e}=await import("./chunk-8em788gc.js"),p=_((await e(s)).runtimeConfig);return await be(p,()=>E(t,async(u)=>{let n=await Bun.build({entrypoints:[u.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
5
+ `));let c=n.outputs.find((d)=>d.kind==="entry-point");if(!c||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${u.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await c.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function hs(s,l,o){if(Ui(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(v.realpathSync(s))))return!0}catch{}if(R.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(l,typeof o==="object"?o.dir??"server/api":"server/api"),t=(p)=>{try{return v.realpathSync(p)}catch{return m.resolve(p)}},e=t(s);return[f,m.resolve(l,"server"),m.resolve(l,".output/server")].some((p)=>{let u=t(p);return e===u||e.startsWith(`${u}${m.sep}`)})}
6
+ export{It,ps,gs,ms,Zu,hs};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{D}from"./chunk-7a8jkwah.js";var t={UNCLOSED_DIRECTIVE:1001,UNCLOSED_EXPRESSION:1002,INVALID_DIRECTIVE_SYNTAX:1003,MALFORMED_EXPRESSION:1004,UNEXPECTED_TOKEN:1005,UNDEFINED_VARIABLE:1101,TYPE_ERROR:1102,EVALUATION_ERROR:1103,INFINITE_LOOP:1104,CIRCULAR_REFERENCE:1105,UNSAFE_EXPRESSION:1201,PATH_TRAVERSAL:1202,XSS_ATTEMPT:1203,CODE_INJECTION:1204,DOM_API_VIOLATION:1205,FILE_NOT_FOUND:1301,FILE_READ_ERROR:1302,INVALID_FILE_PATH:1303,PERMISSION_DENIED:1304,INVALID_CONFIG:1401,MISSING_REQUIRED_CONFIG:1402,DEPRECATED_CONFIG:1403,COMPONENT_NOT_FOUND:1501,INVALID_PROPS:1502,COMPONENT_RENDER_ERROR:1503,FILTER_NOT_FOUND:1601,INVALID_FILTER_ARGS:1602,EXPRESSION_TIMEOUT:1603};function A(e){for(let[r,n]of Object.entries(t))if(n===e)return r;return}import ue from"path";var ge={showRelativePaths:!1,enableAutoRecovery:D(),logRecoveryWarnings:!0},P={...ge};function k(){return{...P}}function _(e){if(!P.showRelativePaths||!e)return e;let r=P.baseDir||process.cwd();try{let n=ue.relative(r,e);return n.startsWith("..")?e:n}catch{return e}}class R extends Error{code;filePath;line;column;context;numericCode;constructor(e,r,n,o,s,a,g){super(e);this.code=r;this.filePath=n;this.line=o;this.column=s;this.context=a;if(this.name="StxError",this.numericCode=g||t.EVALUATION_ERROR,this.filePath)this.filePath=_(this.filePath)}}class W extends R{constructor(e,r,n,o,s,a){super(e,"stx_RUNTIME_ERROR",r,n,o,s,a||t.EVALUATION_ERROR);this.name="StxRuntimeError"}}class Mn extends R{constructor(e,r,n,o,s,a){super(e,"stx_FILE_ERROR",r,n,o,s,a||t.FILE_NOT_FOUND);this.name="StxFileError"}}class q extends R{isFatal=!0;constructor(e,r,n,o,s,a){super(e,"stx_VALIDATION_ERROR",r,n,o,s,a||t.DOM_API_VIOLATION);this.name="StxValidationError"}}function H(e){let{type:r,message:n,code:o,filePath:s,line:a,column:g,template:u,offset:h,snippet:m,suggestion:d,format:f="text"}=e,E=a,x=g;if(!E&&u&&h!==void 0){let X=Ee(u,h);E=X.line,x=X.column}let w=s?_(s):void 0,y=o?A(o):void 0,S={type:r,code:o,codeName:y,message:n,filePath:w,line:E,column:x,snippet:m,suggestion:d,timestamp:new Date().toISOString()},v;switch(f){case"html":v=me(S);break;case"json":v=JSON.stringify(S,null,2);break;case"console":v=pe(S,u,h);break;case"text":default:v=fe(S,u,h);break}return{formatted:v,data:S}}function fe(e,r,n){let o=[],s=e.code?` [${e.codeName||e.code}]`:"";if(o.push(`[${e.type} Error${s}]`),e.filePath){let a=e.filePath;if(e.line){if(a+=`:${e.line}`,e.column)a+=`:${e.column}`}o.push(`at ${a}`)}if(o.push(`
2
+ import{D}from"./chunk-jbmjcs83.js";var t={UNCLOSED_DIRECTIVE:1001,UNCLOSED_EXPRESSION:1002,INVALID_DIRECTIVE_SYNTAX:1003,MALFORMED_EXPRESSION:1004,UNEXPECTED_TOKEN:1005,UNDEFINED_VARIABLE:1101,TYPE_ERROR:1102,EVALUATION_ERROR:1103,INFINITE_LOOP:1104,CIRCULAR_REFERENCE:1105,UNSAFE_EXPRESSION:1201,PATH_TRAVERSAL:1202,XSS_ATTEMPT:1203,CODE_INJECTION:1204,DOM_API_VIOLATION:1205,FILE_NOT_FOUND:1301,FILE_READ_ERROR:1302,INVALID_FILE_PATH:1303,PERMISSION_DENIED:1304,INVALID_CONFIG:1401,MISSING_REQUIRED_CONFIG:1402,DEPRECATED_CONFIG:1403,COMPONENT_NOT_FOUND:1501,INVALID_PROPS:1502,COMPONENT_RENDER_ERROR:1503,FILTER_NOT_FOUND:1601,INVALID_FILTER_ARGS:1602,EXPRESSION_TIMEOUT:1603};function A(e){for(let[r,n]of Object.entries(t))if(n===e)return r;return}import ue from"path";var ge={showRelativePaths:!1,enableAutoRecovery:D(),logRecoveryWarnings:!0},P={...ge};function k(){return{...P}}function _(e){if(!P.showRelativePaths||!e)return e;let r=P.baseDir||process.cwd();try{let n=ue.relative(r,e);return n.startsWith("..")?e:n}catch{return e}}class R extends Error{code;filePath;line;column;context;numericCode;constructor(e,r,n,o,s,a,g){super(e);this.code=r;this.filePath=n;this.line=o;this.column=s;this.context=a;if(this.name="StxError",this.numericCode=g||t.EVALUATION_ERROR,this.filePath)this.filePath=_(this.filePath)}}class W extends R{constructor(e,r,n,o,s,a){super(e,"stx_RUNTIME_ERROR",r,n,o,s,a||t.EVALUATION_ERROR);this.name="StxRuntimeError"}}class Mn extends R{constructor(e,r,n,o,s,a){super(e,"stx_FILE_ERROR",r,n,o,s,a||t.FILE_NOT_FOUND);this.name="StxFileError"}}class q extends R{isFatal=!0;constructor(e,r,n,o,s,a){super(e,"stx_VALIDATION_ERROR",r,n,o,s,a||t.DOM_API_VIOLATION);this.name="StxValidationError"}}function H(e){let{type:r,message:n,code:o,filePath:s,line:a,column:g,template:u,offset:h,snippet:m,suggestion:d,format:f="text"}=e,E=a,x=g;if(!E&&u&&h!==void 0){let X=Ee(u,h);E=X.line,x=X.column}let w=s?_(s):void 0,y=o?A(o):void 0,S={type:r,code:o,codeName:y,message:n,filePath:w,line:E,column:x,snippet:m,suggestion:d,timestamp:new Date().toISOString()},v;switch(f){case"html":v=me(S);break;case"json":v=JSON.stringify(S,null,2);break;case"console":v=pe(S,u,h);break;case"text":default:v=fe(S,u,h);break}return{formatted:v,data:S}}function fe(e,r,n){let o=[],s=e.code?` [${e.codeName||e.code}]`:"";if(o.push(`[${e.type} Error${s}]`),e.filePath){let a=e.filePath;if(e.line){if(a+=`:${e.line}`,e.column)a+=`:${e.column}`}o.push(`at ${a}`)}if(o.push(`
3
3
  ${e.message}`),r&&e.line){let a=de(r,e.line,2);if(a)o.push(`
4
4
  ${a}`)}if(e.snippet)o.push(`
5
5
  Snippet: ${e.snippet}`);if(e.suggestion)o.push(`
@@ -17,7 +17,7 @@ ${"\x1B[31m"}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\
17
17
  `)}function he(e,r,n){let o=e.split(`
18
18
  `),s=Math.max(0,r-n-1),a=Math.min(o.length-1,r+n-1),g="\x1B[90m",u="\x1B[31m",h="\x1B[0m",m=[];for(let d=s;d<=a;d++){let f=(d+1).toString().padStart(4),E=d===r-1,x=E?"\x1B[31m>\x1B[0m":" ",w=E?`\x1B[31m${o[d]}\x1B[0m`:`\x1B[90m${o[d]}\x1B[0m`;m.push(`${x}\x1B[90m${f}\x1B[0m | ${w}`)}return m.join(`
19
19
  `)}function G(e){return e.replace(/--/g,"- -").replace(/>/g,"&gt;")}function Ee(e,r){let o=e.substring(0,r).split(`
20
- `);return{line:o.length,column:o[o.length-1].length}}function i(e,r,n){return H({type:e,message:r,code:n,format:"html"}).formatted}async function ae(e,r,n){try{return await e()}catch(o){if(n&&o instanceof Error)n(o);return r}}var to={isEnabled(){return k().enableAutoRecovery},fixCommonSyntaxErrors(e){let r=k();if(!r.enableAutoRecovery)return{fixed:e,fixes:[]};let n=e,o=[],s=(n.match(/\{\{/g)||[]).length,a=(n.match(/\}\}/g)||[]).length;if(s>a){let u=s-a;n+="}}".repeat(u),o.push(`Added ${u} missing closing braces '}}'`)}let g=["if","foreach","for","switch","section"];for(let u of g){let h=(n.match(new RegExp(`@${u}\\b`,"g"))||[]).length,m=(n.match(new RegExp(`@end${u}\\b`,"g"))||[]).length;if(h>m){let d=h-m;for(let f=0;f<d;f++)n+=`
20
+ `);return{line:o.length,column:o[o.length-1].length}}function i(e,r,n){return H({type:e,message:r,code:n,format:"html"}).formatted}async function ae(e,r,n){try{return await e()}catch(o){if(n&&o instanceof Error)n(o);return r}}var no={isEnabled(){return k().enableAutoRecovery},fixCommonSyntaxErrors(e){let r=k();if(!r.enableAutoRecovery)return{fixed:e,fixes:[]};let n=e,o=[],s=(n.match(/\{\{/g)||[]).length,a=(n.match(/\}\}/g)||[]).length;if(s>a){let u=s-a;n+="}}".repeat(u),o.push(`Added ${u} missing closing braces '}}'`)}let g=["if","foreach","for","switch","section"];for(let u of g){let h=(n.match(new RegExp(`@${u}\\b`,"g"))||[]).length,m=(n.match(new RegExp(`@end${u}\\b`,"g"))||[]).length;if(h>m){let d=h-m;for(let f=0;f<d;f++)n+=`
21
21
  @end${u}`;o.push(`Added ${d} missing @end${u}`)}}if(o.length>0&&r.logRecoveryWarnings)console.warn("[stx] Auto-recovery applied fixes:"),o.forEach((u)=>console.warn(` - ${u}`)),console.warn(" Consider fixing these issues in your template.");return{fixed:n,fixes:o}},createFallbackContent(e,r){if(D())return`<!-- ${e} failed: ${r.message} -->`;return"<!-- stx rendering error -->"}};class I{errors=[];maxErrors;enableFileLogging;logFilePath;logFormat;maxFileSize;maxLogFiles;minLevel;writeQueue=Promise.resolve();constructor(e={}){this.maxErrors=e.maxErrors??1000,this.enableFileLogging=e.enableFileLogging??!1,this.logFilePath=e.logFilePath??".stx/errors.log",this.logFormat=e.logFormat??"json",this.maxFileSize=e.maxFileSize??10485760,this.maxLogFiles=e.maxLogFiles??5,this.minLevel=e.minLevel??"all"}configure(e){if(e.maxErrors!==void 0)this.maxErrors=e.maxErrors;if(e.enableFileLogging!==void 0)this.enableFileLogging=e.enableFileLogging;if(e.logFilePath!==void 0)this.logFilePath=e.logFilePath;if(e.logFormat!==void 0)this.logFormat=e.logFormat;if(e.maxFileSize!==void 0)this.maxFileSize=e.maxFileSize;if(e.maxLogFiles!==void 0)this.maxLogFiles=e.maxLogFiles;if(e.minLevel!==void 0)this.minLevel=e.minLevel}log(e,r,n="error"){let o={timestamp:new Date,error:e,context:r,level:n};if(this.errors.push(o),this.errors.length>this.maxErrors)this.errors=this.errors.slice(-this.maxErrors);if(this.enableFileLogging&&this.shouldLog(n))this.writeToFile(o)}shouldLog(e){if(this.minLevel==="all")return!0;if(this.minLevel==="warning")return e==="error"||e==="warning";if(this.minLevel==="error")return e==="error";return!0}formatEntry(e){if(this.logFormat==="json")return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level||"error",type:e.error.constructor.name,message:e.error.message,stack:e.error.stack,context:e.context});let r=[`[${e.timestamp.toISOString()}] [${(e.level||"error").toUpperCase()}] ${e.error.constructor.name}: ${e.error.message}`];if(e.error.stack)r.push(` Stack: ${e.error.stack.split(`
22
22
  `).slice(1).join(`
23
23
  `)}`);if(e.context)r.push(` Context: ${JSON.stringify(e.context)}`);return r.join(`
@@ -25,7 +25,7 @@ ${"\x1B[31m"}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\
25
25
  `;r.appendFileSync(this.logFilePath,s,"utf-8")}catch(r){if(process.env.STX_DEBUG==="true")console.error("Failed to write to error log:",r)}})}async rotateIfNeeded(e){try{if(!e.existsSync(this.logFilePath))return;if(e.statSync(this.logFilePath).size<this.maxFileSize)return;for(let n=this.maxLogFiles-1;n>=1;n--){let o=`${this.logFilePath}.${n}`,s=`${this.logFilePath}.${n+1}`;if(e.existsSync(o))if(n>=this.maxLogFiles-1)e.unlinkSync(o);else e.renameSync(o,s)}if(this.maxLogFiles<=1)e.writeFileSync(this.logFilePath,"");else e.renameSync(this.logFilePath,`${this.logFilePath}.1`)}catch(r){if(process.env.STX_DEBUG==="true")console.error("Failed to rotate error logs:",r)}}getRecentErrors(e=10){return this.errors.slice(-e)}getErrorsByType(e){return this.errors.filter((r)=>r.error.constructor.name===e)}getErrorsByLevel(e){return this.errors.filter((r)=>r.level===e)}clear(){this.errors.length=0}async clearLogFile(){try{let e=await import("fs");if(e.existsSync(this.logFilePath))e.writeFileSync(this.logFilePath,"","utf-8")}catch(e){if(process.env.STX_DEBUG==="true")console.error("Failed to clear error log:",e)}}getStats(){let e={},r={error:0,warning:0,info:0};for(let n of this.errors){let o=n.error.constructor.name;e[o]=(e[o]||0)+1;let s=n.level||"error";r[s]=(r[s]||0)+1}return{total:this.errors.length,byType:e,byLevel:r}}async exportToFile(e,r="json"){let n=await import("fs"),o=await import("path"),s=o.dirname(e);if(!n.existsSync(s))n.mkdirSync(s,{recursive:!0});if(r==="json"){let a=this.errors.map((g)=>({timestamp:g.timestamp.toISOString(),level:g.level||"error",type:g.error.constructor.name,message:g.error.message,stack:g.error.stack,context:g.context}));n.writeFileSync(e,JSON.stringify(a,null,2),"utf-8")}else{let a=this.errors.map((g)=>this.formatEntry(g));n.writeFileSync(e,a.join(`
26
26
 
27
27
  `),"utf-8")}}async flush(){await this.writeQueue}}var O=new I,Ut={isDevelopment(){return D()},logDetailedError(e,r){if(!this.isDevelopment())return;if(console.error("=== stx Detailed Error ==="),console.error("Error:",e.message),console.error("Stack:",e.stack),r)console.error("Context:",r);console.error("========================")},createErrorReport(e,r){let n=["=== stx Error Report ===",`Time: ${new Date().toISOString()}`,`Error: ${e.message}`,`Type: ${e.constructor.name}`,`Stack: ${e.stack}`];if(r)n.push(`Context: ${JSON.stringify(r,null,2)}`);return n.push("========================"),n.join(`
28
- `)}};var xe={maxSanitizeDepth:10,allowBracketNotation:!1},ee={...xe};var F=/\bnew\s+/,L="__stx_safe_ctors",te=["Bun","Deno","Buffer","fetch","atob","btoa","console","Response","Request","Headers","WebAssembly","structuredClone","queueMicrotask","crypto","performance","navigator","Worker","WebSocket","BroadcastChannel","EventSource","XMLHttpRequest","localStorage","sessionStorage"],T=[...te,"Function","setTimeout","setInterval","setImmediate","process","require","exports","module","window","document","global","globalThis","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry"],J=T.map(()=>{return}),M=Object.freeze(Object.assign(Object.create(null),{keys:Object.keys,values:Object.values,entries:Object.entries,fromEntries:Object.fromEntries,assign:Object.assign,hasOwn:Object.hasOwn,is:Object.is})),j=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/,F,/\bdelete\s+/,/\bthis\b/,/\\u(?:\{[\dA-Fa-f]+\}|[\dA-Fa-f]{4})/],U=new Set([...te,"eval","Function","setTimeout","setInterval","setImmediate","process","require","import","exports","module","window","document","global","globalThis","constructor","prototype","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Generator","AsyncGenerator","delete","this",L]),B=new Set(["__proto__","constructor","prototype"]);function re(e){let r="",n=[],o=null,s=!1;for(let a=0;a<e.length;a++){let g=e[a];if(s){s=!1;continue}if(g==="\\"&&o){s=!0;continue}if(o){if(o==="`"&&g==="$"&&a+1<e.length&&e[a+1]==="{"){let u=1;a+=2;while(a<e.length&&u>0){if(e[a]==="{")u++;else if(e[a]==="}")u--;if(u>0)r+=e[a],n.push(a),a++}continue}if(g===o)o=null;continue}if(g==='"'||g==="'"||g==="`"){o=g;continue}r+=g,n.push(a)}return{text:r,map:n}}function ne(e){return re(e).text}var oe=["Collator","DateTimeFormat","DisplayNames","ListFormat","Locale","NumberFormat","PluralRules","RelativeTimeFormat","Segmenter"],se=(()=>{let e={Date,URL,URLSearchParams},r=Intl;for(let n of oe)if(typeof r[n]==="function")e[`Intl_${n}`]=r[n];return Object.freeze(Object.assign(Object.create(null),e))})(),be=/^new(\s+)(Date|URLSearchParams|URL|Intl\s*\.\s*([A-Z_a-z]\w*))\s*\(/,Z=/(?<![\w$])new(?![\w$])/g,Q=`only new Date(), new URL(), new URLSearchParams() and new Intl.{${oe.join(",")}}() are allowed`;function ye(e){let{text:r,map:n}=re(e),o=[];Z.lastIndex=0;let s;while((s=Z.exec(r))!==null){let g=s.index;if(/(?<!\.)\.\s*$/.test(r.slice(0,g)))continue;let u=be.exec(r.slice(g)),h=u?.[3],m=!u?null:h?`Intl_${h}`:u[2];if(!u||!m||!(m in se))throw new b(`matched /${F.source}/; ${Q}`,e);let d=g+u[0].length,f=n[g],E=n[d-1]+1;if(e.slice(f,E)!==r.slice(g,d))throw new b(`matched /${F.source}/; ${Q}`,e);let x=f+3+u[1].length;o.push({start:x,end:x+u[2].length,key:m})}let a=e;for(let g=o.length-1;g>=0;g--){let u=o[g];a=`${a.slice(0,u.start)}${L}.${u.key}${a.slice(u.end)}`}return{source:a,usesSafeConstructors:o.length>0}}class b extends Error{rule;expression;constructor(e,r,n){super(n??`Potentially unsafe expression (${e}): ${r}`);this.name="UnsafeExpressionError",this.rule=e,this.expression=r}}function Ln(e){try{return V(e),null}catch(r){return r instanceof b?r.rule:r instanceof Error?r.message:String(r)}}function ie(e,r){let n=/[$A-Z_a-z][$\w]*/g,o;while((o=n.exec(e))!==null){let s=o[0],a=e[o.index-1];if(U.has(s))throw new b(`matched /\\b${s}\\b/; identifier ${s}`,r);if(a==="."&&B.has(s))throw new b(`matched /.${s}/; property ${s}`,r)}}function ce(e,r=!0){let n=/(?:[$\w)\].]|\?\.)\s*\[([^\]]*)\]/g,o=new Set,s;while((s=n.exec(e))!==null){let a=s.index+s[0].indexOf("["),g=e.slice(0,a);if(/(?:^|[^$\w])(?:let|const|var)\s*$/.test(g))continue;let u=s[1].trim(),h=/^'(?:[^'\\]|\\.)*'$/.test(u),m=/^"(?:[^"\\]|\\.)*"$/.test(u);if(/^\d+$/.test(u))continue;if(h||m){let f=u.slice(1,-1);if(B.has(f))throw new b(`bracket key ${f}`,e);if(!ee.allowBracketNotation)throw new b("bracket notation with a string key; enable with configureSafeEvaluator({ allowBracketNotation: true })",e,`Bracket notation with strings not allowed: ${e}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);continue}if(r&&/^[$A-Z_a-z][$\w]*$/.test(u)){o.add(u);continue}throw new b("dynamic bracket notation is not allowed",e)}return[...o]}function V(e){let r=e.trim(),n=ne(r);ie(n,r);let o=ce(r);for(let s of j){if(s===F)continue;if(s.test(n))throw new b(`matched /${s.source}/`,r)}return{...ye(r),dynamicKeys:o}}function no(e){return V(e),e.trim()}var Er=Symbol("stx.sanitizeCache");function Tr(e){let r={},n=e[Er];r.Math=Math,r.JSON=JSON,r.Date=Date,r.String=String,r.Number=Number,r.Boolean=Boolean,r.Array=Array,r.Object=M,r.parseInt=Number.parseInt,r.parseFloat=Number.parseFloat,r.isNaN=Number.isNaN,r.isFinite=Number.isFinite,r.encodeURIComponent=encodeURIComponent,r.decodeURIComponent=decodeURIComponent;for(let[o,s]of Object.entries(e)){if(o.startsWith("__")||j.some((a)=>a.test(o)))continue;if(s&&typeof s==="object"&&!Array.isArray(s)){let a=n?.get(s);if(a===void 0)a=z(s),n?.set(s,a);r[o]=a}else r[o]=s}return r}function z(e,r=0){if(r>=ee.maxSanitizeDepth)return"[Object too deep]";if(e===null||typeof e!=="object")return e;if(Array.isArray(e))return e.map((o)=>z(o,r+1));if(e instanceof Date||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof Error)return e;let n={};for(let[o,s]of Object.entries(e)){if(o.startsWith("__")||o==="constructor"||o==="prototype")continue;if(s&&typeof s==="object")n[o]=z(s,r+1);else n[o]=s}return n}function l(e,r){try{let n=Tr(r),o=Object.keys(n),s=Object.values(n);return c(e,o)(...s)}catch{return}}function p(e){try{return no(e),!0}catch{return!1}}function Qi(e,r){try{let n=Tr(r),o=Object.keys(n),s=Object.values(n),a=!1,u=c(e,o,()=>{a=!0})(...s);return!a&&Boolean(u)}catch{return!1}}function N(e,r){try{let n=l(e,r);if(n&&typeof n==="object"&&!Array.isArray(n))return n;return{}}catch{return{}}}var le=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","arguments","eval","await"]),we=2000,C=new Map;function Y(e,r){let n=`${e.join(",")}\x00${r}`,o=C.get(n);if(o)return o;let s=Function(...e,r);if(C.size>=we)C.clear();return C.set(n,s),s}function Ie(e){return e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g," ").replace(/\??\.\s*[a-zA-Z_$][\w$]*/g," ").replace(/([{,]\s*)[a-zA-Z_$][\w$]*(\s*:)/g,"$1$2").match(/\b[a-zA-Z_$][\w$]*\b/g)||[]}var Se=/^[A-Za-z_$][\w$]*$/;function ut(e){return Se.test(e)&&!le.has(e)}function c(e,r,n){let{source:o,usesSafeConstructors:s,dynamicKeys:a}=V(e),g=[];for(let f=0;f<r.length;f++){if(!ut(r[f]))continue;if(r[f]===L||r[f]==="Object"||U.has(r[f]))continue;g.push({key:r[f],index:f})}g.sort((f,E)=>f.key.localeCompare(E.key));let u=g.map((f)=>f.key),h=g.map((f)=>f.index),m=`
28
+ `)}};var xe={maxSanitizeDepth:10,allowBracketNotation:!1},ee={...xe};var F=/\bnew\s+/,L="__stx_safe_ctors",te=["Bun","Deno","Buffer","fetch","atob","btoa","console","Response","Request","Headers","WebAssembly","structuredClone","queueMicrotask","crypto","performance","navigator","Worker","WebSocket","BroadcastChannel","EventSource","XMLHttpRequest","localStorage","sessionStorage"],T=[...te,"Function","setTimeout","setInterval","setImmediate","process","require","exports","module","window","document","global","globalThis","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry"],J=T.map(()=>{return}),M=Object.freeze(Object.assign(Object.create(null),{keys:Object.keys,values:Object.values,entries:Object.entries,fromEntries:Object.fromEntries,assign:Object.assign,hasOwn:Object.hasOwn,is:Object.is})),j=[/\b(eval|Function|setTimeout|setInterval|setImmediate)\b/,/\b(process|require|import|exports|module)\b/,/\b(window|document|global|globalThis)\b/,/\b(constructor|prototype|__proto__)\b/,/\b(Reflect|Proxy)\b/,/\bSymbol\b/,/\b(WeakMap|WeakSet|WeakRef|FinalizationRegistry)\b/,/\b(Generator|AsyncGenerator)\b/,/__\w+__/,/\.(bind|call|apply)\s*\(/,F,/\bdelete\s+/,/\bthis\b/,/\\u(?:\{[\dA-Fa-f]+\}|[\dA-Fa-f]{4})/],U=new Set([...te,"eval","Function","setTimeout","setInterval","setImmediate","process","require","import","exports","module","window","document","global","globalThis","constructor","prototype","Reflect","Proxy","Symbol","WeakMap","WeakSet","WeakRef","FinalizationRegistry","Generator","AsyncGenerator","delete","this",L]),B=new Set(["__proto__","constructor","prototype"]);function re(e){let r="",n=[],o=null,s=!1;for(let a=0;a<e.length;a++){let g=e[a];if(s){s=!1;continue}if(g==="\\"&&o){s=!0;continue}if(o){if(o==="`"&&g==="$"&&a+1<e.length&&e[a+1]==="{"){let u=1;a+=2;while(a<e.length&&u>0){if(e[a]==="{")u++;else if(e[a]==="}")u--;if(u>0)r+=e[a],n.push(a),a++}continue}if(g===o)o=null;continue}if(g==='"'||g==="'"||g==="`"){o=g;continue}r+=g,n.push(a)}return{text:r,map:n}}function ne(e){return re(e).text}var oe=["Collator","DateTimeFormat","DisplayNames","ListFormat","Locale","NumberFormat","PluralRules","RelativeTimeFormat","Segmenter"],se=(()=>{let e={Date,URL,URLSearchParams},r=Intl;for(let n of oe)if(typeof r[n]==="function")e[`Intl_${n}`]=r[n];return Object.freeze(Object.assign(Object.create(null),e))})(),be=/^new(\s+)(Date|URLSearchParams|URL|Intl\s*\.\s*([A-Z_a-z]\w*))\s*\(/,Z=/(?<![\w$])new(?![\w$])/g,Q=`only new Date(), new URL(), new URLSearchParams() and new Intl.{${oe.join(",")}}() are allowed`;function ye(e){let{text:r,map:n}=re(e),o=[];Z.lastIndex=0;let s;while((s=Z.exec(r))!==null){let g=s.index;if(/(?<!\.)\.\s*$/.test(r.slice(0,g)))continue;let u=be.exec(r.slice(g)),h=u?.[3],m=!u?null:h?`Intl_${h}`:u[2];if(!u||!m||!(m in se))throw new b(`matched /${F.source}/; ${Q}`,e);let d=g+u[0].length,f=n[g],E=n[d-1]+1;if(e.slice(f,E)!==r.slice(g,d))throw new b(`matched /${F.source}/; ${Q}`,e);let x=f+3+u[1].length;o.push({start:x,end:x+u[2].length,key:m})}let a=e;for(let g=o.length-1;g>=0;g--){let u=o[g];a=`${a.slice(0,u.start)}${L}.${u.key}${a.slice(u.end)}`}return{source:a,usesSafeConstructors:o.length>0}}class b extends Error{rule;expression;constructor(e,r,n){super(n??`Potentially unsafe expression (${e}): ${r}`);this.name="UnsafeExpressionError",this.rule=e,this.expression=r}}function Ln(e){try{return V(e),null}catch(r){return r instanceof b?r.rule:r instanceof Error?r.message:String(r)}}function ie(e,r){let n=/[$A-Z_a-z][$\w]*/g,o;while((o=n.exec(e))!==null){let s=o[0],a=e[o.index-1];if(U.has(s))throw new b(`matched /\\b${s}\\b/; identifier ${s}`,r);if(a==="."&&B.has(s))throw new b(`matched /.${s}/; property ${s}`,r)}}function ce(e,r=!0){let n=/(?:[$\w)\].]|\?\.)\s*\[([^\]]*)\]/g,o=new Set,s;while((s=n.exec(e))!==null){let a=s.index+s[0].indexOf("["),g=e.slice(0,a);if(/(?:^|[^$\w])(?:let|const|var)\s*$/.test(g))continue;let u=s[1].trim(),h=/^'(?:[^'\\]|\\.)*'$/.test(u),m=/^"(?:[^"\\]|\\.)*"$/.test(u);if(/^\d+$/.test(u))continue;if(h||m){let f=u.slice(1,-1);if(B.has(f))throw new b(`bracket key ${f}`,e);if(!ee.allowBracketNotation)throw new b("bracket notation with a string key; enable with configureSafeEvaluator({ allowBracketNotation: true })",e,`Bracket notation with strings not allowed: ${e}. Enable with configureSafeEvaluator({ allowBracketNotation: true })`);continue}if(r&&/^[$A-Z_a-z][$\w]*$/.test(u)){o.add(u);continue}throw new b("dynamic bracket notation is not allowed",e)}return[...o]}function V(e){let r=e.trim(),n=ne(r);ie(n,r);let o=ce(r);for(let s of j){if(s===F)continue;if(s.test(n))throw new b(`matched /${s.source}/`,r)}return{...ye(r),dynamicKeys:o}}function ro(e){return V(e),e.trim()}var Er=Symbol("stx.sanitizeCache");function Tr(e){let r={},n=e[Er];r.Math=Math,r.JSON=JSON,r.Date=Date,r.String=String,r.Number=Number,r.Boolean=Boolean,r.Array=Array,r.Object=M,r.parseInt=Number.parseInt,r.parseFloat=Number.parseFloat,r.isNaN=Number.isNaN,r.isFinite=Number.isFinite,r.encodeURIComponent=encodeURIComponent,r.decodeURIComponent=decodeURIComponent;for(let[o,s]of Object.entries(e)){if(o.startsWith("__")||j.some((a)=>a.test(o)))continue;if(s&&typeof s==="object"&&!Array.isArray(s)){let a=n?.get(s);if(a===void 0)a=z(s),n?.set(s,a);r[o]=a}else r[o]=s}return r}function z(e,r=0){if(r>=ee.maxSanitizeDepth)return"[Object too deep]";if(e===null||typeof e!=="object")return e;if(Array.isArray(e))return e.map((o)=>z(o,r+1));if(e instanceof Date||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof Error)return e;let n={};for(let[o,s]of Object.entries(e)){if(o.startsWith("__")||o==="constructor"||o==="prototype")continue;if(s&&typeof s==="object")n[o]=z(s,r+1);else n[o]=s}return n}function l(e,r){try{let n=Tr(r),o=Object.keys(n),s=Object.values(n);return c(e,o)(...s)}catch{return}}function p(e){try{return ro(e),!0}catch{return!1}}function ea(e,r){try{let n=Tr(r),o=Object.keys(n),s=Object.values(n),a=!1,u=c(e,o,()=>{a=!0})(...s);return!a&&Boolean(u)}catch{return!1}}function N(e,r){try{let n=l(e,r);if(n&&typeof n==="object"&&!Array.isArray(n))return n;return{}}catch{return{}}}var le=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","arguments","eval","await"]),we=2000,C=new Map;function Y(e,r){let n=`${e.join(",")}\x00${r}`,o=C.get(n);if(o)return o;let s=Function(...e,r);if(C.size>=we)C.clear();return C.set(n,s),s}function Ie(e){return e.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g," ").replace(/\??\.\s*[a-zA-Z_$][\w$]*/g," ").replace(/([{,]\s*)[a-zA-Z_$][\w$]*(\s*:)/g,"$1$2").match(/\b[a-zA-Z_$][\w$]*\b/g)||[]}var Se=/^[A-Za-z_$][\w$]*$/;function ut(e){return Se.test(e)&&!le.has(e)}function c(e,r,n){let{source:o,usesSafeConstructors:s,dynamicKeys:a}=V(e),g=[];for(let f=0;f<r.length;f++){if(!ut(r[f]))continue;if(r[f]===L||r[f]==="Object"||U.has(r[f]))continue;g.push({key:r[f],index:f})}g.sort((f,E)=>f.key.localeCompare(E.key));let u=g.map((f)=>f.key),h=g.map((f)=>f.index),m=`
29
29
  'use strict';
30
30
  try {
31
31
  return ${o};
@@ -37,4 +37,4 @@ catch (e) {
37
37
  throw e;
38
38
  }
39
39
  `;return ve(Re(s?(f)=>{let E=Y([L,"Object",...T,...u,...f],m);return(...x)=>E(se,M,...J,...x)}:(f)=>{let E=Y(["Object",...T,...u,...f],m);return(...x)=>E(M,...J,...x)},u,r,g,h,n),r,a)}function ve(e,r,n){if(n.length===0)return e;let o=n.map((s)=>r.indexOf(s));return(...s)=>{for(let a of o){if(a<0)continue;let g=s[a];if(typeof g==="string"&&B.has(g))return}return e(...s)}}function Re(e,r,n,o,s,a){let g=e([]),u=o.every((m,d)=>m.index===d);if(r.length===n.length&&u)return K(g,r,e,void 0,a);return K((...m)=>{let d=Array(s.length);for(let f=0;f<s.length;f++)d[f]=m[s[f]];return g(...d)},r,e,(m)=>{g=e(m)},a)}function K(e,r,n,o,s){let g=/^(\w+) is not defined$/,u=e,h=[],m=new Set(r);return(...d)=>{for(let f=0;f<=8;f++)try{return u(...d)}catch(E){let x=E instanceof Error?E.message:"",w=g.exec(x);if(!(E instanceof ReferenceError)||!w)return;let y=w[1];if(m.has(y)||le.has(y)||U.has(y))return;if(s?.(y),m.add(y),h.push(y),o)o(h);else u=n(h)}return}}function $r(e){let r=e.trim();try{let n=ne(r);if(/\b(?:eval|function|import|require|process|globalthis|window|document|fetch|bun|deno|buffer|console|reflect|proxy|prototype|constructor|this)\b/i.test(n))return!1;ie(n,r),ce(r);for(let o of j)if(o.test(n))return!1}catch{return!1}return!0}
40
- export{t,W,Mn,q,i,ae,to,O,Ut,Ln,no,Er,Tr,l,p,Qi,N,Ie,ut,c,$r};
40
+ export{t,W,Mn,q,i,ae,no,O,Ut,Ln,ro,Er,Tr,l,p,ea,N,Ie,ut,c,$r};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R,k,rn,sn,on}from"./chunk-phbnrw2h.js";import{resolve as Q,basename as J,extname as K,join as Y}from"path";import{mkdir as Z}from"fs/promises";var N={enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:2000,cacheTranscoded:!0,cacheThumbnails:!0,cacheManifests:!0};class Yr{config;constructor(t={}){this.config={...N,...t}}async get(t,e){return rn(t,e,"video",this.config)}async set(t,e,a){return sn(t,e,a,"video",this.config)}async clear(){return on("video",this.config)}updateConfig(t){this.config={...this.config,...t}}}var v=null;function B(t){if(!v)v=new Yr(t);else if(t)v.updateConfig(t);return v}async function Zr(t,e,a){let c=a?{directory:`${a.outputDir}/../.cache`}:{};return B(c).get(t,e)}async function Qr(t,e,a,c){let r=c?{directory:`${c.outputDir}/../.cache`}:{};return B(r).set(t,e,a)}async function ja(){return B().clear()}import{resolve as _,basename as D,extname as A,join as H}from"path";import{mkdir as M}from"fs/promises";async function L(){try{return await import("ts-videos")}catch{return null}}async function es(t,e,a,c){let r=await L();if(!r)return console.warn("[stx-media] ts-videos not installed, cannot generate poster"),null;try{let n=_(t);if(!await k(n))return null;await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),o=e.format||"webp",h=e.timestamp||0,y=`${s}-poster-${i}.${o}`,u=H(a,y),m=await r.extractThumbnails(n,{timestamps:[h],width:e.width||1280,height:e.height,format:o,quality:e.quality||85,outputDir:a,outputPattern:y.replace(`.${o}`,"")});if(m&&m.length>0){let d=m[0];return{path:u,url:`${c}/${y}`,width:d.width||e.width||1280,height:d.height||720,timestamp:h,size:d.size||0}}return null}catch(n){return console.warn(`[stx-media] Failed to generate poster: ${n}`),null}}async function ts(t,e,a,c){let r=await L();if(!r)return[];try{let n=_(t);if(!await k(n))return[];await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),o=e.format||"webp",u=(await new r.Input(n).getInfo()).duration||60,m=e.count||10,d=e.interval||u/m,g=[];for(let f=0;f<m&&f*d<u;f++)g.push(f*d);let l=await r.extractThumbnails(n,{timestamps:g,width:e.width||320,format:o,quality:e.quality||80,outputDir:a,outputPattern:`${s}-thumb-${i}`});if(l&&l.length>0)return l.map((f,b)=>({path:f.path||H(a,`${s}-thumb-${i}-${b}.${o}`),url:`${c}/${s}-thumb-${i}-${b}.${o}`,width:f.width||e.width||320,height:f.height||180,timestamp:g[b],size:f.size||0}));return[]}catch(n){return console.warn(`[stx-media] Failed to generate thumbnails: ${n}`),[]}}async function Ba(t,e,a,c){let r=await L();if(!r)return console.warn("[stx-media] ts-videos not installed, cannot generate sprite sheet"),null;try{let n=_(t);if(!await k(n))return null;await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),y=(await new r.Input(n).getInfo()).duration||60,u=e.columns||10,m=e.interval||5,d=e.thumbnailWidth||160,g=e.thumbnailHeight||90,l=e.format||"jpeg",f=Math.ceil(y/m),b=Math.ceil(f/u),S=`${s}-sprite-${i}.${l}`,w=H(a,S),C=[];for(let P=0;P<f;P++)C.push(P*m);let p=await r.extractThumbnails(n,{timestamps:C,width:d,height:g,format:l,quality:e.quality||70,outputDir:H(a,".temp")});if(!p||p.length===0)return null;try{let P=await import("ts-images"),x=u*d,ie=b*g,re=await P.createSprite({images:p.map((U)=>U.path),columns:u,padding:0,outputPath:w,format:l,quality:e.quality||70});return{url:`${c}/${S}`,path:w,columns:u,rows:b,thumbnailWidth:d,thumbnailHeight:g,interval:m,totalFrames:f}}catch{return console.warn("[stx-media] ts-images not installed, sprite sheet generation skipped"),null}}catch(n){return console.warn(`[stx-media] Failed to generate sprite sheet: ${n}`),null}}import{resolve as E,basename as F,extname as W,join as V}from"path";import{mkdir as T,writeFile as q}from"fs/promises";async function z(){try{return await import("ts-videos")}catch{return null}}var j=[{label:"1080p",width:1920,height:1080,bitrate:5000000,audioBitrate:192000},{label:"720p",width:1280,height:720,bitrate:2500000,audioBitrate:128000},{label:"480p",width:854,height:480,bitrate:1e6,audioBitrate:96000},{label:"360p",width:640,height:360,bitrate:600000,audioBitrate:64000}];async function ns(t,e,a,c,r){let n=await z();if(!n)return console.warn("[stx-media] ts-videos not installed, cannot generate HLS manifest"),null;try{let i=E(t);if(!await k(i))return null;let s=await R(i),o=F(t,W(t)),h=V(a,`${o}-${s}-hls`);await T(h,{recursive:!0});let y=e.length>0?e:j,u=r?.segmentDuration||6,g=(await new n.Input(i).getInfo()).duration||0,l=[],f=0;for(let w of y){let C=V(h,w.label);await T(C,{recursive:!0});let p=`${w.label}.m3u8`,P=V(C,p);try{let x=await n.generateHLS(i,{outputDir:C,segmentDuration:u,width:w.width,height:w.height,videoBitrate:w.bitrate,audioBitrate:w.audioBitrate,playlistName:w.label});if(x)l.push({quality:w,url:`${c}/${o}-${s}-hls/${w.label}/${p}`,path:P}),f+=x.segmentCount||Math.ceil(g/u)}catch(x){console.warn(`[stx-media] Failed to generate HLS for ${w.label}: ${x}`)}}if(l.length===0)return null;let b=V(h,"master.m3u8"),S=X(l,c,o,s);return await q(b,S),{manifestUrl:`${c}/${o}-${s}-hls/master.m3u8`,manifestPath:b,playlists:l,segmentCount:f,duration:g}}catch(i){return console.warn(`[stx-media] Failed to generate HLS manifest: ${i}`),null}}function X(t,e,a,c){let r=["#EXTM3U","#EXT-X-VERSION:3"];for(let n of t){let{quality:i}=n,s=i.bitrate+(i.audioBitrate||128000),o=`${i.width}x${i.height||Math.round(i.width*9/16)}`;r.push(`#EXT-X-STREAM-INF:BANDWIDTH=${s},RESOLUTION=${o},NAME="${i.label}"`,`${i.label}/${i.label}.m3u8`)}return r.join(`
2
+ import{R,k,rn,sn,on}from"./chunk-phbnrw2h.js";import{resolve as Q,basename as J,extname as K,join as Y}from"path";import{mkdir as Z}from"fs/promises";var N={enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:2000,cacheTranscoded:!0,cacheThumbnails:!0,cacheManifests:!0};class Yr{config;constructor(t={}){this.config={...N,...t}}async get(t,e){return rn(t,e,"video",this.config)}async set(t,e,a){return sn(t,e,a,"video",this.config)}async clear(){return on("video",this.config)}updateConfig(t){this.config={...this.config,...t}}}var v=null;function B(t){if(!v)v=new Yr(t);else if(t)v.updateConfig(t);return v}async function Zr(t,e,a){let c=a?{directory:`${a.outputDir}/../.cache`}:{};return B(c).get(t,e)}async function Qr(t,e,a,c){let r=c?{directory:`${c.outputDir}/../.cache`}:{};return B(r).set(t,e,a)}async function Ba(){return B().clear()}import{resolve as _,basename as D,extname as A,join as H}from"path";import{mkdir as M}from"fs/promises";async function L(){try{return await import("ts-videos")}catch{return null}}async function es(t,e,a,c){let r=await L();if(!r)return console.warn("[stx-media] ts-videos not installed, cannot generate poster"),null;try{let n=_(t);if(!await k(n))return null;await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),o=e.format||"webp",h=e.timestamp||0,y=`${s}-poster-${i}.${o}`,u=H(a,y),m=await r.extractThumbnails(n,{timestamps:[h],width:e.width||1280,height:e.height,format:o,quality:e.quality||85,outputDir:a,outputPattern:y.replace(`.${o}`,"")});if(m&&m.length>0){let d=m[0];return{path:u,url:`${c}/${y}`,width:d.width||e.width||1280,height:d.height||720,timestamp:h,size:d.size||0}}return null}catch(n){return console.warn(`[stx-media] Failed to generate poster: ${n}`),null}}async function ts(t,e,a,c){let r=await L();if(!r)return[];try{let n=_(t);if(!await k(n))return[];await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),o=e.format||"webp",u=(await new r.Input(n).getInfo()).duration||60,m=e.count||10,d=e.interval||u/m,g=[];for(let f=0;f<m&&f*d<u;f++)g.push(f*d);let l=await r.extractThumbnails(n,{timestamps:g,width:e.width||320,format:o,quality:e.quality||80,outputDir:a,outputPattern:`${s}-thumb-${i}`});if(l&&l.length>0)return l.map((f,b)=>({path:f.path||H(a,`${s}-thumb-${i}-${b}.${o}`),url:`${c}/${s}-thumb-${i}-${b}.${o}`,width:f.width||e.width||320,height:f.height||180,timestamp:g[b],size:f.size||0}));return[]}catch(n){return console.warn(`[stx-media] Failed to generate thumbnails: ${n}`),[]}}async function Fa(t,e,a,c){let r=await L();if(!r)return console.warn("[stx-media] ts-videos not installed, cannot generate sprite sheet"),null;try{let n=_(t);if(!await k(n))return null;await M(a,{recursive:!0});let i=await R(n),s=D(t,A(t)),y=(await new r.Input(n).getInfo()).duration||60,u=e.columns||10,m=e.interval||5,d=e.thumbnailWidth||160,g=e.thumbnailHeight||90,l=e.format||"jpeg",f=Math.ceil(y/m),b=Math.ceil(f/u),S=`${s}-sprite-${i}.${l}`,w=H(a,S),C=[];for(let P=0;P<f;P++)C.push(P*m);let p=await r.extractThumbnails(n,{timestamps:C,width:d,height:g,format:l,quality:e.quality||70,outputDir:H(a,".temp")});if(!p||p.length===0)return null;try{let P=await import("ts-images"),x=u*d,ie=b*g,re=await P.createSprite({images:p.map((U)=>U.path),columns:u,padding:0,outputPath:w,format:l,quality:e.quality||70});return{url:`${c}/${S}`,path:w,columns:u,rows:b,thumbnailWidth:d,thumbnailHeight:g,interval:m,totalFrames:f}}catch{return console.warn("[stx-media] ts-images not installed, sprite sheet generation skipped"),null}}catch(n){return console.warn(`[stx-media] Failed to generate sprite sheet: ${n}`),null}}import{resolve as E,basename as F,extname as W,join as V}from"path";import{mkdir as T,writeFile as q}from"fs/promises";async function z(){try{return await import("ts-videos")}catch{return null}}var j=[{label:"1080p",width:1920,height:1080,bitrate:5000000,audioBitrate:192000},{label:"720p",width:1280,height:720,bitrate:2500000,audioBitrate:128000},{label:"480p",width:854,height:480,bitrate:1e6,audioBitrate:96000},{label:"360p",width:640,height:360,bitrate:600000,audioBitrate:64000}];async function ns(t,e,a,c,r){let n=await z();if(!n)return console.warn("[stx-media] ts-videos not installed, cannot generate HLS manifest"),null;try{let i=E(t);if(!await k(i))return null;let s=await R(i),o=F(t,W(t)),h=V(a,`${o}-${s}-hls`);await T(h,{recursive:!0});let y=e.length>0?e:j,u=r?.segmentDuration||6,g=(await new n.Input(i).getInfo()).duration||0,l=[],f=0;for(let w of y){let C=V(h,w.label);await T(C,{recursive:!0});let p=`${w.label}.m3u8`,P=V(C,p);try{let x=await n.generateHLS(i,{outputDir:C,segmentDuration:u,width:w.width,height:w.height,videoBitrate:w.bitrate,audioBitrate:w.audioBitrate,playlistName:w.label});if(x)l.push({quality:w,url:`${c}/${o}-${s}-hls/${w.label}/${p}`,path:P}),f+=x.segmentCount||Math.ceil(g/u)}catch(x){console.warn(`[stx-media] Failed to generate HLS for ${w.label}: ${x}`)}}if(l.length===0)return null;let b=V(h,"master.m3u8"),S=X(l,c,o,s);return await q(b,S),{manifestUrl:`${c}/${o}-${s}-hls/master.m3u8`,manifestPath:b,playlists:l,segmentCount:f,duration:g}}catch(i){return console.warn(`[stx-media] Failed to generate HLS manifest: ${i}`),null}}function X(t,e,a,c){let r=["#EXTM3U","#EXT-X-VERSION:3"];for(let n of t){let{quality:i}=n,s=i.bitrate+(i.audioBitrate||128000),o=`${i.width}x${i.height||Math.round(i.width*9/16)}`;r.push(`#EXT-X-STREAM-INF:BANDWIDTH=${s},RESOLUTION=${o},NAME="${i.label}"`,`${i.label}/${i.label}.m3u8`)}return r.join(`
3
3
  `)}async function rs(t,e,a,c,r){let n=await z();if(!n)return console.warn("[stx-media] ts-videos not installed, cannot generate DASH manifest"),null;try{let i=E(t);if(!await k(i))return null;let s=await R(i),o=F(t,W(t)),h=V(a,`${o}-${s}-dash`);await T(h,{recursive:!0});let y=e.length>0?e:j,u=r?.segmentDuration||4,m=r?.minBufferTime||2,l=(await new n.Input(i).getInfo()).duration||0,f=[],b=[];for(let p of y){let P=V(h,p.label);await T(P,{recursive:!0});try{if(await n.generateDASH(i,{outputDir:P,segmentDuration:u,width:p.width,height:p.height,videoBitrate:p.bitrate,audioBitrate:p.audioBitrate})){if(f.push({bandwidth:p.bitrate,width:p.width,height:p.height||Math.round(p.width*9/16),url:`${c}/${o}-${s}-dash/${p.label}/video`}),p.audioBitrate)b.push({bandwidth:p.audioBitrate,url:`${c}/${o}-${s}-dash/${p.label}/audio`})}}catch(x){console.warn(`[stx-media] Failed to generate DASH for ${p.label}: ${x}`)}}if(f.length===0)return null;let S=V(h,"manifest.mpd"),w=G(f,b,l,u,m);await q(S,w);let C=[{type:"video",representations:f}];if(b.length>0)C.push({type:"audio",representations:b});return{manifestUrl:`${c}/${o}-${s}-dash/manifest.mpd`,manifestPath:S,adaptationSets:C,duration:l}}catch(i){return console.warn(`[stx-media] Failed to generate DASH manifest: ${i}`),null}}function G(t,e,a,c,r){let n=I(a),i=I(r),s=`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <MPD xmlns="urn:mpeg:dash:schema:mpd:2011"
5
5
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
@@ -26,4 +26,4 @@ import{R,k,rn,sn,on}from"./chunk-phbnrw2h.js";import{resolve as Q,basename as J,
26
26
  </Representation>
27
27
  `}s+=` </AdaptationSet>
28
28
  `}return s+=` </Period>
29
- </MPD>`,s}function I(t){let e=Math.floor(t/3600),a=Math.floor(t%3600/60),c=Math.floor(t%60),r="PT";if(e>0)r+=`${e}H`;if(a>0)r+=`${a}M`;return r+=`${c}S`,r}async function O(){try{return await import("ts-videos")}catch{return null}}function ee(t){switch(t){case"very-low":return 500000;case"low":return 1e6;case"medium":return 2500000;case"high":return 5000000;case"very-high":return 1e7;case"lossless":return 0;default:return 2500000}}function te(t){switch(t){case"youtube":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000};case"twitter":return{codec:"h264",maxWidth:1280,maxHeight:720,frameRate:30,bitrate:5000000,audioCodec:"aac",audioBitrate:128000};case"instagram-feed":return{codec:"h264",maxWidth:1080,maxHeight:1080,frameRate:30,bitrate:3500000,audioCodec:"aac",audioBitrate:128000};case"instagram-story":case"instagram-reels":return{codec:"h264",maxWidth:1080,maxHeight:1920,frameRate:30,bitrate:3500000,audioCodec:"aac",audioBitrate:128000};case"tiktok":return{codec:"h264",maxWidth:1080,maxHeight:1920,frameRate:30,bitrate:4000000,audioCodec:"aac",audioBitrate:128000};case"discord":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:60,bitrate:8000000,audioCodec:"aac",audioBitrate:192000};case"linkedin":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,bitrate:5000000,audioCodec:"aac",audioBitrate:128000};case"facebook":return{codec:"h264",maxWidth:1280,maxHeight:720,frameRate:30,bitrate:4000000,audioCodec:"aac",audioBitrate:128000};case"web-progressive":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000,twoPass:!0};case"web-streaming":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000};default:return{}}}async function Bo(t){let e=await O();if(!e)return null;try{let a=Q(t),r=await new e.Input(a).getInfo();return{duration:r.duration||0,width:r.width||0,height:r.height||0,frameRate:r.frameRate||0,bitrate:r.bitrate||0,codec:r.videoCodec||"",audioCodec:r.audioCodec}}catch(a){return console.warn(`[stx-media] Failed to analyze video: ${a}`),null}}async function Fa(t,e,a,c){let r=await O();if(!r)return console.warn("[stx-media] ts-videos not installed, skipping processing"),{src:t,processed:!1};let n=await Zr(t,e,a);if(n)return n;try{let i=Q(t);if(!await k(i))return{src:t,processed:!1,errors:[`Source file not found: ${t}`]};let s=a.outputDir||"dist/videos",o=a.baseUrl||"/videos";await Z(s,{recursive:!0});let h=await R(i),y=J(t,K(t)),u={src:t,processed:!0,hash:h};c?.({percentage:5,stage:"analyzing"}),u.metadata=await Bo(i)||void 0;let m={};if(e.quality)m.bitrate=ee(e.quality);if(e.platform)Object.assign(m,te(e.platform));if(e.transcode)Object.assign(m,e.transcode);if(Object.keys(m).length>0||e.process){c?.({percentage:10,stage:"transcoding"});let d=`${y}-${h}.mp4`,g=Y(s,d);try{let l=await ae(i,g,m,r,(f)=>c?.({percentage:10+f*0.5,stage:"transcoding"}));if(l)u.transcoded={path:g,url:`${o}/${d}`,duration:l.duration,size:l.size,video:{codec:m.codec||"h264",width:l.width,height:l.height,bitrate:l.bitrate,frameRate:l.frameRate},audio:l.audioCodec?{codec:m.audioCodec||"aac",bitrate:m.audioBitrate||128000,sampleRate:m.sampleRate||48000,channels:m.channels||2}:void 0}}catch(l){u.errors=u.errors||[],u.errors.push(`Transcoding failed: ${l}`)}}if(e.generatePoster){c?.({percentage:65,stage:"generating-poster"});let d=typeof e.generatePoster==="object"?e.generatePoster:{timestamp:0},g=await es(i,d,s,o);if(g)u.poster=g}if(a.thumbnails?.enabled){c?.({percentage:70,stage:"generating-thumbnails"});let d=await ts(i,a.thumbnails,s,o);if(d.length>0)u.thumbnails=d}if(e.streaming){c?.({percentage:80,stage:"generating-manifests"});let d=typeof e.streaming==="object"?e.streaming:a.streaming||{format:"hls"};if(d.format==="hls"||d.format===void 0){let g=await ns(i,d.qualities||a.streaming?.defaultQualities||[],s,o);if(g)u.streaming={...u.streaming,hls:g}}if(d.format==="dash"){let g=await rs(i,d.qualities||a.streaming?.defaultQualities||[],s,o);if(g)u.streaming={...u.streaming,dash:g}}}if(e.spriteSheet)c?.({percentage:90,stage:"generating-sprite-sheet"});return c?.({percentage:100,stage:"complete"}),await Qr(t,e,u,a),u}catch(i){return{src:t,processed:!1,errors:[`Processing failed: ${i}`]}}}async function ae(t,e,a,c,r){try{let i=await new c.Conversion(t,e,{videoCodec:a.codec,videoBitrate:a.bitrate,width:a.maxWidth,height:a.maxHeight,frameRate:a.frameRate,audioCodec:a.audioCodec,audioBitrate:a.audioBitrate,sampleRate:a.sampleRate,channels:a.channels}).run((s)=>{r?.(s.percentage/100)});return{duration:i.duration||0,size:i.size||0,width:i.width||a.maxWidth||0,height:i.height||a.maxHeight||0,bitrate:i.bitrate||a.bitrate||0,frameRate:i.frameRate||a.frameRate||30,audioCodec:i.audioCodec}}catch(n){return console.error(`[stx-media] Transcoding failed: ${n}`),null}}export{Yr,Zr,Qr,ja,es,ts,Ba,ns,rs,Bo,Fa};
29
+ </MPD>`,s}function I(t){let e=Math.floor(t/3600),a=Math.floor(t%3600/60),c=Math.floor(t%60),r="PT";if(e>0)r+=`${e}H`;if(a>0)r+=`${a}M`;return r+=`${c}S`,r}async function O(){try{return await import("ts-videos")}catch{return null}}function ee(t){switch(t){case"very-low":return 500000;case"low":return 1e6;case"medium":return 2500000;case"high":return 5000000;case"very-high":return 1e7;case"lossless":return 0;default:return 2500000}}function te(t){switch(t){case"youtube":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000};case"twitter":return{codec:"h264",maxWidth:1280,maxHeight:720,frameRate:30,bitrate:5000000,audioCodec:"aac",audioBitrate:128000};case"instagram-feed":return{codec:"h264",maxWidth:1080,maxHeight:1080,frameRate:30,bitrate:3500000,audioCodec:"aac",audioBitrate:128000};case"instagram-story":case"instagram-reels":return{codec:"h264",maxWidth:1080,maxHeight:1920,frameRate:30,bitrate:3500000,audioCodec:"aac",audioBitrate:128000};case"tiktok":return{codec:"h264",maxWidth:1080,maxHeight:1920,frameRate:30,bitrate:4000000,audioCodec:"aac",audioBitrate:128000};case"discord":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:60,bitrate:8000000,audioCodec:"aac",audioBitrate:192000};case"linkedin":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,bitrate:5000000,audioCodec:"aac",audioBitrate:128000};case"facebook":return{codec:"h264",maxWidth:1280,maxHeight:720,frameRate:30,bitrate:4000000,audioCodec:"aac",audioBitrate:128000};case"web-progressive":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000,twoPass:!0};case"web-streaming":return{codec:"h264",maxWidth:1920,maxHeight:1080,frameRate:30,audioCodec:"aac",audioBitrate:128000};default:return{}}}async function Fo(t){let e=await O();if(!e)return null;try{let a=Q(t),r=await new e.Input(a).getInfo();return{duration:r.duration||0,width:r.width||0,height:r.height||0,frameRate:r.frameRate||0,bitrate:r.bitrate||0,codec:r.videoCodec||"",audioCodec:r.audioCodec}}catch(a){return console.warn(`[stx-media] Failed to analyze video: ${a}`),null}}async function za(t,e,a,c){let r=await O();if(!r)return console.warn("[stx-media] ts-videos not installed, skipping processing"),{src:t,processed:!1};let n=await Zr(t,e,a);if(n)return n;try{let i=Q(t);if(!await k(i))return{src:t,processed:!1,errors:[`Source file not found: ${t}`]};let s=a.outputDir||"dist/videos",o=a.baseUrl||"/videos";await Z(s,{recursive:!0});let h=await R(i),y=J(t,K(t)),u={src:t,processed:!0,hash:h};c?.({percentage:5,stage:"analyzing"}),u.metadata=await Fo(i)||void 0;let m={};if(e.quality)m.bitrate=ee(e.quality);if(e.platform)Object.assign(m,te(e.platform));if(e.transcode)Object.assign(m,e.transcode);if(Object.keys(m).length>0||e.process){c?.({percentage:10,stage:"transcoding"});let d=`${y}-${h}.mp4`,g=Y(s,d);try{let l=await ae(i,g,m,r,(f)=>c?.({percentage:10+f*0.5,stage:"transcoding"}));if(l)u.transcoded={path:g,url:`${o}/${d}`,duration:l.duration,size:l.size,video:{codec:m.codec||"h264",width:l.width,height:l.height,bitrate:l.bitrate,frameRate:l.frameRate},audio:l.audioCodec?{codec:m.audioCodec||"aac",bitrate:m.audioBitrate||128000,sampleRate:m.sampleRate||48000,channels:m.channels||2}:void 0}}catch(l){u.errors=u.errors||[],u.errors.push(`Transcoding failed: ${l}`)}}if(e.generatePoster){c?.({percentage:65,stage:"generating-poster"});let d=typeof e.generatePoster==="object"?e.generatePoster:{timestamp:0},g=await es(i,d,s,o);if(g)u.poster=g}if(a.thumbnails?.enabled){c?.({percentage:70,stage:"generating-thumbnails"});let d=await ts(i,a.thumbnails,s,o);if(d.length>0)u.thumbnails=d}if(e.streaming){c?.({percentage:80,stage:"generating-manifests"});let d=typeof e.streaming==="object"?e.streaming:a.streaming||{format:"hls"};if(d.format==="hls"||d.format===void 0){let g=await ns(i,d.qualities||a.streaming?.defaultQualities||[],s,o);if(g)u.streaming={...u.streaming,hls:g}}if(d.format==="dash"){let g=await rs(i,d.qualities||a.streaming?.defaultQualities||[],s,o);if(g)u.streaming={...u.streaming,dash:g}}}if(e.spriteSheet)c?.({percentage:90,stage:"generating-sprite-sheet"});return c?.({percentage:100,stage:"complete"}),await Qr(t,e,u,a),u}catch(i){return{src:t,processed:!1,errors:[`Processing failed: ${i}`]}}}async function ae(t,e,a,c,r){try{let i=await new c.Conversion(t,e,{videoCodec:a.codec,videoBitrate:a.bitrate,width:a.maxWidth,height:a.maxHeight,frameRate:a.frameRate,audioCodec:a.audioCodec,audioBitrate:a.audioBitrate,sampleRate:a.sampleRate,channels:a.channels}).run((s)=>{r?.(s.percentage/100)});return{duration:i.duration||0,size:i.size||0,width:i.width||a.maxWidth||0,height:i.height||a.maxHeight||0,bitrate:i.bitrate||a.bitrate||0,frameRate:i.frameRate||a.frameRate||30,audioCodec:i.audioCodec}}catch(n){return console.error(`[stx-media] Transcoding failed: ${n}`),null}}export{Yr,Zr,Qr,Ba,es,ts,Fa,ns,rs,Fo,za};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{We}from"./chunk-b7p3yca7.js";function nr(e){let n=e.pwa;if(!n?.enabled)return"";let r=n.manifest,t=n.icons?.outputDir?`/${n.icons.outputDir}`:"/pwa-icons",o=We(e),i=`
2
+ import{We}from"./chunk-y04hzz4w.js";function nr(e){let n=e.pwa;if(!n?.enabled)return"";let r=n.manifest,t=n.icons?.outputDir?`/${n.icons.outputDir}`:"/pwa-icons",o=We(e),i=`
3
3
  <!-- stx PWA Meta Tags -->
4
4
  <link rel="manifest" href="/manifest.json">
5
5
  <meta name="theme-color" content="${a(r?.themeColor||"#000000")}">
@@ -45,7 +45,7 @@ if ('serviceWorker' in navigator) {
45
45
  </script>
46
46
  <!-- End stx PWA -->`,i}function ls(e,n){let r=n.pwa;if(!r?.enabled||r.autoInject===!1)return e;if(e.includes("<!-- stx PWA Meta Tags -->"))return e;if(!e.includes("</head>")){let o=e.lastIndexOf("</body>");if(o!==-1){let i=nr(n);return e.slice(0,o)+i+`
47
47
  `+e.slice(o)}return e+nr(n)}let t=nr(n);return e.replace("</head>",`${t}
48
- </head>`)}function dc(e){if(!e.pwa?.enabled)return"";return`<script>
48
+ </head>`)}function pc(e){if(!e.pwa?.enabled)return"";return`<script>
49
49
  if ('serviceWorker' in navigator) {
50
50
  window.addEventListener('load', function() {
51
51
  navigator.serviceWorker.register('/${We(e)}')
@@ -57,5 +57,5 @@ if ('serviceWorker' in navigator) {
57
57
  });
58
58
  });
59
59
  }
60
- </script>`}function pc(){return'<link rel="manifest" href="/manifest.json">'}function fc(e){return`<meta name="theme-color" content="${a(e)}">`}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}
61
- export{nr,ls,dc,pc,fc};
60
+ </script>`}function fc(){return'<link rel="manifest" href="/manifest.json">'}function gc(e){return`<meta name="theme-color" content="${a(e)}">`}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}
61
+ export{nr,ls,pc,fc,gc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Broadcast as s,BroadcastServer as h}from"ts-broadcasting";import{channel as Ll}from"ts-broadcasting";import{Broadcast as jl,BroadcastServer as Bl}from"ts-broadcasting";var e=null,u=[];function Rl(){return e}async function Al(n){if(e)return e;let t=n.driver??"bun",r=n.host??"0.0.0.0",c=n.port??6001,l=n.scheme??"ws",a={verbose:n.verbose??!1,driver:t,default:t,connections:{[t]:{driver:t,host:r,port:c,scheme:l}}};return e=new h(a),s.setServer(e),await e.start(),e}async function Pl(){for(let n of u)clearInterval(n);if(u.length=0,!e)return;await e.stop(),e=null}async function Il(n){let t=await import(n),r=t.default??t;if(typeof r!=="function")throw Error(`routes/channels.ts must export a default function, got ${typeof r}`);let c=0;return r({channel(a,o){if(c++,o.authorize&&e)e.channels.channel(a,o.authorize);if(o.interval&&o.data){let d=o.event??`${a}.updated`,p=o.data,v=setInterval(async()=>{try{let g=await p();Ta(a,d,g)}catch{}},o.interval);u.push(v)}}}),c}var f=!1;function i(){if(e)return!0;if(!f)f=!0,console.warn("[stx] broadcast() called before server started \u2014 messages will be sent once broadcasting is ready");return!1}function Ta(n,t,r){if(!i())return;s.send(n,t,r)}function Ol(n,t,r){if(!i())return;s.toUser(n,t,r)}function Nl(n,t,r){if(!i())return;s.toUsers(n,t,r)}function Dl(n,t,r){if(!i())return;s.send(`private-${n}`,t,r)}function Ml(n,t,r){if(!i())return;s.presence(n,t,r)}
3
- export{Rl,Al,Pl,Il,Ta,Ol,Nl,Dl,Ml,Ll,jl,Bl};
2
+ import{Broadcast as s,BroadcastServer as h}from"ts-broadcasting";import{channel as Bl}from"ts-broadcasting";import{Broadcast as Fl,BroadcastServer as zl}from"ts-broadcasting";var e=null,u=[];function Pl(){return e}async function Il(n){if(e)return e;let t=n.driver??"bun",r=n.host??"0.0.0.0",c=n.port??6001,l=n.scheme??"ws",a={verbose:n.verbose??!1,driver:t,default:t,connections:{[t]:{driver:t,host:r,port:c,scheme:l}}};return e=new h(a),s.setServer(e),await e.start(),e}async function Ol(){for(let n of u)clearInterval(n);if(u.length=0,!e)return;await e.stop(),e=null}async function Nl(n){let t=await import(n),r=t.default??t;if(typeof r!=="function")throw Error(`routes/channels.ts must export a default function, got ${typeof r}`);let c=0;return r({channel(a,o){if(c++,o.authorize&&e)e.channels.channel(a,o.authorize);if(o.interval&&o.data){let d=o.event??`${a}.updated`,p=o.data,v=setInterval(async()=>{try{let g=await p();$a(a,d,g)}catch{}},o.interval);u.push(v)}}}),c}var f=!1;function i(){if(e)return!0;if(!f)f=!0,console.warn("[stx] broadcast() called before server started \u2014 messages will be sent once broadcasting is ready");return!1}function $a(n,t,r){if(!i())return;s.send(n,t,r)}function Dl(n,t,r){if(!i())return;s.toUser(n,t,r)}function Ml(n,t,r){if(!i())return;s.toUsers(n,t,r)}function Ll(n,t,r){if(!i())return;s.send(`private-${n}`,t,r)}function jl(n,t,r){if(!i())return;s.presence(n,t,r)}
3
+ export{Pl,Il,Ol,Nl,$a,Dl,Ml,Ll,jl,Bl,Fl,zl};
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- var cs=new Map([["craft-button",{name:"Button",zigType:"craft.Button",props:[{name:"variant",type:"string",required:!1,default:"primary"},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onclick",type:"callback",required:!1}],children:"single"}],["craft-text-input",{name:"TextInput",zigType:"craft.TextInput",props:[{name:"value",type:"string",required:!1,default:""},{name:"placeholder",type:"string",required:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-textarea",{name:"TextArea",zigType:"craft.TextArea",props:[{name:"value",type:"string",required:!1,default:""},{name:"placeholder",type:"string",required:!1},{name:"rows",type:"number",required:!1,default:3},{name:"disabled",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-checkbox",{name:"Checkbox",zigType:"craft.Checkbox",props:[{name:"checked",type:"boolean",required:!1,default:!1},{name:"label",type:"string",required:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-select",{name:"Select",zigType:"craft.Select",props:[{name:"value",type:"string",required:!1},{name:"options",type:"array",required:!0},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-slider",{name:"Slider",zigType:"craft.Slider",props:[{name:"value",type:"number",required:!1,default:0},{name:"min",type:"number",required:!1,default:0},{name:"max",type:"number",required:!1,default:100},{name:"step",type:"number",required:!1,default:1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-toggle",{name:"Toggle",zigType:"craft.Toggle",props:[{name:"checked",type:"boolean",required:!1,default:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-modal",{name:"Modal",zigType:"craft.Modal",props:[{name:"open",type:"boolean",required:!1,default:!1},{name:"title",type:"string",required:!1},{name:"closable",type:"boolean",required:!1,default:!0},{name:"onclose",type:"callback",required:!1}],children:"multiple"}],["craft-alert",{name:"Alert",zigType:"craft.Alert",props:[{name:"variant",type:"string",required:!1,default:"info"},{name:"title",type:"string",required:!1},{name:"dismissible",type:"boolean",required:!1,default:!1}],children:"single"}],["craft-progress",{name:"ProgressBar",zigType:"craft.ProgressBar",props:[{name:"value",type:"number",required:!1,default:0},{name:"max",type:"number",required:!1,default:100},{name:"indeterminate",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-spinner",{name:"Spinner",zigType:"craft.Spinner",props:[{name:"size",type:"number",required:!1,default:24}],children:"none"}],["craft-avatar",{name:"Avatar",zigType:"craft.Avatar",props:[{name:"src",type:"string",required:!1},{name:"alt",type:"string",required:!1},{name:"size",type:"number",required:!1,default:40}],children:"none"}],["craft-badge",{name:"Badge",zigType:"craft.Badge",props:[{name:"variant",type:"string",required:!1,default:"default"}],children:"single"}],["craft-card",{name:"Card",zigType:"craft.Card",props:[{name:"padding",type:"number",required:!1,default:16}],children:"multiple"}],["craft-sidebar",{name:"Sidebar",zigType:"craft.NativeSidebar",props:[{name:"id",type:"string",required:!1},{name:"variant",type:"string",required:!1,default:"desktop"},{name:"material",type:"string",required:!1,default:"sidebar"},{name:"backgroundEffect",type:"string",required:!1,default:"shimmer"},{name:"allowsVibrancy",type:"boolean",required:!1,default:!0},{name:"materialOpacity",type:"number",required:!1,default:0.68},{name:"minWidth",type:"number",required:!1,default:240},{name:"maxWidth",type:"number",required:!1,default:340},{name:"canCollapse",type:"boolean",required:!1,default:!0},{name:"selectedItem",type:"string",required:!1},{name:"sections",type:"array",required:!1}],children:"multiple",platform:["macos"],fallback:"aside"}],["craft-sidebar-section",{name:"SidebarSection",zigType:"craft.NativeSidebarSection",props:[{name:"id",type:"string",required:!0},{name:"title",type:"string",required:!1},{name:"header",type:"string",required:!1}],children:"multiple",platform:["macos"],fallback:"section"}],["craft-sidebar-item",{name:"SidebarItem",zigType:"craft.NativeSidebarItem",props:[{name:"id",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"icon",type:"string",required:!1},{name:"badge",type:"string",required:!1},{name:"tintColor",type:"color",required:!1}],children:"none",platform:["macos"],fallback:"button"}],["craft-accordion",{name:"Accordion",zigType:"craft.Accordion",props:[{name:"title",type:"string",required:!0},{name:"open",type:"boolean",required:!1,default:!1}],children:"multiple"}],["craft-tabs",{name:"TabView",zigType:"craft.TabView",props:[{name:"activeTab",type:"number",required:!1,default:0},{name:"ontabchange",type:"callback",required:!1}],children:"multiple"}],["craft-tooltip",{name:"Tooltip",zigType:"craft.Tooltip",props:[{name:"content",type:"string",required:!0},{name:"position",type:"string",required:!1,default:"top"}],children:"single"}],["craft-date-picker",{name:"DatePicker",zigType:"craft.DatePicker",props:[{name:"value",type:"string",required:!1},{name:"min",type:"string",required:!1},{name:"max",type:"string",required:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-time-picker",{name:"TimePicker",zigType:"craft.TimePicker",props:[{name:"value",type:"string",required:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-color-picker",{name:"ColorPicker",zigType:"craft.ColorPicker",props:[{name:"value",type:"color",required:!1,default:"#000000"},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-data-table",{name:"DataTable",zigType:"craft.DataTable",props:[{name:"data",type:"array",required:!0},{name:"columns",type:"array",required:!0},{name:"sortable",type:"boolean",required:!1,default:!1},{name:"paginated",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-virtual-list",{name:"VirtualList",zigType:"craft.VirtualList",props:[{name:"items",type:"array",required:!0},{name:"itemHeight",type:"number",required:!1,default:48},{name:"renderItem",type:"callback",required:!0}],children:"none"}],["craft-tree-view",{name:"TreeView",zigType:"craft.TreeView",props:[{name:"data",type:"object",required:!0},{name:"expandable",type:"boolean",required:!1,default:!0}],children:"none"}]]);async function Yo(e,t={}){let r=performance.now(),n={target:t.target||"universal",format:t.format||"zig",optimize:t.optimize??!0,treeShake:t.treeShake??!0,hotReload:t.hotReload??!1,debug:t.debug??!1,sourceMaps:t.sourceMaps??!1,bundle:t.bundle??!0,minify:t.minify??!1,components:t.components||cs},i=typeof e==="string"?w(e):e,o=I(i.tree,n),s=L(o),a=n.treeShake?O(o,s):o,l=new Map;if(n.target==="universal"){let c=["macos","windows","linux","ios","android"];for(let g of c){let q=u(a,{...n,target:g});l.set(g,q)}}else{let c=u(a,n);l.set(n.target,c)}let p=H(a,n,l),S=_(i,a,n),k={compilationTime:performance.now()-r,totalComponents:f(i.tree),nativeComponents:d(a),webComponents:f(i.tree)-d(a),bundleSize:p.length,treeShakenSize:n.treeShake?W(o,a):p.length,warnings:[],errors:[]},m;if(n.sourceMaps)m=B(i,a);return{code:p,platformCode:l,dependencies:s,manifest:S,sourceMaps:m,stats:k}}function w(e){let t={type:"fragment",children:[]},r=e.match(/<body[^>]*>([\s\S]*?)<\/body>/i),n=r?r[1]:e;return b(n,t),{id:T(),hash:x(e),tree:t,scripts:U(e),styles:Z(e),staticParts:new Map,dynamicParts:new Map,dependencies:[],metadata:{hasSlots:!1,hasDynamicContent:e.includes("{{"),hasEventHandlers:e.includes("onclick")||e.includes("onchange"),hasAsyncContent:!1,componentCount:0,maxDepth:0,estimatedSize:e.length}}}function b(e,t){let r=/<(@?[\w-]+)([^>]*)(?:\/>|>([\s\S]*?)<\/\1>)/g,n;while((n=r.exec(e))!==null){let[,i,o,s]=n,a=i.startsWith("@craft-"),l={type:a?"component":"element",tag:a?i.slice(1):i,props:z(o),children:[],componentName:a?i.slice(1):void 0};if(s){let p=s.replace(/<[^>]+>/g,"").trim();if(p)l.children=l.children??[],l.children.push({type:"text",text:p});b(s,l)}t.children=t.children??[],t.children.push(l)}}function z(e){let t={},r=/([\w-:@]+)(?:=["']([^"']*)["'])?/g,n;while((n=r.exec(e))!==null){let[,i,o]=n;t[i]=o??!0}return t}function I(e,t){return h(e,t)}function h(e,t){let r=e.componentName?t.components?.get(e.componentName):void 0,n="craft.View";if(r)n=r.zigType;else if(e.type==="text")n="craft.Text";else if(e.tag)n=R(e.tag);let i={};if(e.props)for(let[l,p]of Object.entries(e.props))i[l]=M(p);let o=[];if(e.children)for(let l of e.children)o.push(h(l,t));let s=new Map;if(e.props){for(let[l,p]of Object.entries(e.props))if(l.startsWith("on")&&typeof p==="string")s.set(l.slice(2).toLowerCase(),p)}let a=V(e);return{type:A(e,r),zigType:n,props:i,children:o,events:s,styles:a,id:e.hydrationKey,key:e.props?.key}}function R(e){return{div:"craft.View",span:"craft.Text",p:"craft.Text",h1:"craft.Text",h2:"craft.Text",h3:"craft.Text",h4:"craft.Text",h5:"craft.Text",h6:"craft.Text",button:"craft.Button",input:"craft.TextInput",textarea:"craft.TextArea",select:"craft.Select",img:"craft.Image",a:"craft.Link",ul:"craft.List",ol:"craft.List",li:"craft.ListItem",form:"craft.Form",label:"craft.Label",nav:"craft.View",header:"craft.View",footer:"craft.View",main:"craft.View",section:"craft.View",article:"craft.View",aside:"craft.View"}[e.toLowerCase()]||"craft.View"}function M(e){if(typeof e==="string"){if(e.startsWith("{{")&&e.endsWith("}}"))return{type:"binding",path:e.slice(2,-2).trim()};if(e.includes("(")&&e.includes(")"))return{type:"callback",handler:e};return{type:"literal",value:e}}if(typeof e==="number"||typeof e==="boolean")return{type:"literal",value:e};return{type:"literal",value:String(e)}}function A(e,t){if(t){let n=t.name.toLowerCase();if(n.includes("button"))return"button";if(n.includes("input")||n.includes("text"))return"input";if(n.includes("image")||n.includes("avatar"))return"image";if(n.includes("list")||n.includes("table"))return"list";if(n.includes("scroll"))return"scroll";return"custom"}if(e.type==="text")return"text";let r=e.tag?.toLowerCase();if(r==="button")return"button";if(r==="input"||r==="textarea")return"input";if(r==="img")return"image";if(r==="ul"||r==="ol")return"list";return"view"}function V(e){let t=e.props?.style,r={},n={};if(t){let i=t.split(";").filter(Boolean);for(let o of i){let[s,a]=o.split(":").map((l)=>l.trim());if(!s||!a)continue;switch(s){case"display":r.display=a;break;case"flex-direction":r.flexDirection=a;break;case"justify-content":r.justifyContent=j(a);break;case"align-items":r.alignItems=D(a);break;case"gap":r.gap=Number.parseInt(a,10);break;case"padding":r.padding=Number.parseInt(a,10);break;case"margin":r.margin=Number.parseInt(a,10);break;case"width":r.width=a==="auto"?"auto":Number.parseInt(a,10);break;case"height":r.height=a==="auto"?"auto":Number.parseInt(a,10);break;case"background-color":case"background":n.backgroundColor=a;break;case"border-color":n.borderColor=a;break;case"border-width":n.borderWidth=Number.parseInt(a,10);break;case"border-radius":n.borderRadius=Number.parseInt(a,10);break;case"opacity":n.opacity=Number.parseFloat(a);break}}}return{layout:r,appearance:n}}function j(e){return{"flex-start":"start","flex-end":"end",center:"center","space-between":"between","space-around":"around"}[e]||"start"}function D(e){return{"flex-start":"start","flex-end":"end",center:"center",stretch:"stretch"}[e]||"start"}function L(e){let t=[],r=new Set;function n(i,o){let s=i.id||T();if(r.has(s))return;r.add(s);let a={id:s,type:"component",path:i.zigType,dependencies:o?[o]:[],size:C(i),isStatic:P(i)};t.push(a);for(let l of i.children)n(l,s)}return n(e),t}function C(e){let t=100;return t+=Object.keys(e.props).length*20,t+=e.events.size*50,t}function P(e){for(let t of Object.values(e.props))if(t.type!=="literal")return!1;return e.events.size===0}function O(e,t){return e}function W(e,t){let r=0;function n(i){r+=C(i);for(let o of i.children)n(o)}return n(t),r}function u(e,t){switch(t.format){case"zig":return y(e,t);case"typescript":return E(e,t);case"json":return JSON.stringify(e,null,t.minify?0:2);default:return y(e,t)}}function y(e,t){let r=[];return r.push("// Auto-generated by stx compiler"),r.push("// Target: "+t.target),r.push(""),r.push('const std = @import("std");'),r.push('const craft = @import("craft");'),r.push(""),r.push("pub fn render(allocator: std.mem.Allocator) !craft.Element {"),r.push(" return try build(allocator);"),r.push("}"),r.push(""),N(e,r,0),r.join(`
2
+ var cs=new Map([["craft-button",{name:"Button",zigType:"craft.Button",props:[{name:"variant",type:"string",required:!1,default:"primary"},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onclick",type:"callback",required:!1}],children:"single"}],["craft-text-input",{name:"TextInput",zigType:"craft.TextInput",props:[{name:"value",type:"string",required:!1,default:""},{name:"placeholder",type:"string",required:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-textarea",{name:"TextArea",zigType:"craft.TextArea",props:[{name:"value",type:"string",required:!1,default:""},{name:"placeholder",type:"string",required:!1},{name:"rows",type:"number",required:!1,default:3},{name:"disabled",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-checkbox",{name:"Checkbox",zigType:"craft.Checkbox",props:[{name:"checked",type:"boolean",required:!1,default:!1},{name:"label",type:"string",required:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-select",{name:"Select",zigType:"craft.Select",props:[{name:"value",type:"string",required:!1},{name:"options",type:"array",required:!0},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-slider",{name:"Slider",zigType:"craft.Slider",props:[{name:"value",type:"number",required:!1,default:0},{name:"min",type:"number",required:!1,default:0},{name:"max",type:"number",required:!1,default:100},{name:"step",type:"number",required:!1,default:1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-toggle",{name:"Toggle",zigType:"craft.Toggle",props:[{name:"checked",type:"boolean",required:!1,default:!1},{name:"disabled",type:"boolean",required:!1,default:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-modal",{name:"Modal",zigType:"craft.Modal",props:[{name:"open",type:"boolean",required:!1,default:!1},{name:"title",type:"string",required:!1},{name:"closable",type:"boolean",required:!1,default:!0},{name:"onclose",type:"callback",required:!1}],children:"multiple"}],["craft-alert",{name:"Alert",zigType:"craft.Alert",props:[{name:"variant",type:"string",required:!1,default:"info"},{name:"title",type:"string",required:!1},{name:"dismissible",type:"boolean",required:!1,default:!1}],children:"single"}],["craft-progress",{name:"ProgressBar",zigType:"craft.ProgressBar",props:[{name:"value",type:"number",required:!1,default:0},{name:"max",type:"number",required:!1,default:100},{name:"indeterminate",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-spinner",{name:"Spinner",zigType:"craft.Spinner",props:[{name:"size",type:"number",required:!1,default:24}],children:"none"}],["craft-avatar",{name:"Avatar",zigType:"craft.Avatar",props:[{name:"src",type:"string",required:!1},{name:"alt",type:"string",required:!1},{name:"size",type:"number",required:!1,default:40}],children:"none"}],["craft-badge",{name:"Badge",zigType:"craft.Badge",props:[{name:"variant",type:"string",required:!1,default:"default"}],children:"single"}],["craft-card",{name:"Card",zigType:"craft.Card",props:[{name:"padding",type:"number",required:!1,default:16}],children:"multiple"}],["craft-sidebar",{name:"Sidebar",zigType:"craft.NativeSidebar",props:[{name:"id",type:"string",required:!1},{name:"variant",type:"string",required:!1,default:"desktop"},{name:"material",type:"string",required:!1,default:"sidebar"},{name:"backgroundEffect",type:"string",required:!1,default:"shimmer"},{name:"allowsVibrancy",type:"boolean",required:!1,default:!0},{name:"materialOpacity",type:"number",required:!1,default:0.68},{name:"minWidth",type:"number",required:!1,default:240},{name:"maxWidth",type:"number",required:!1,default:340},{name:"canCollapse",type:"boolean",required:!1,default:!0},{name:"selectedItem",type:"string",required:!1},{name:"sections",type:"array",required:!1}],children:"multiple",platform:["macos"],fallback:"aside"}],["craft-sidebar-section",{name:"SidebarSection",zigType:"craft.NativeSidebarSection",props:[{name:"id",type:"string",required:!0},{name:"title",type:"string",required:!1},{name:"header",type:"string",required:!1}],children:"multiple",platform:["macos"],fallback:"section"}],["craft-sidebar-item",{name:"SidebarItem",zigType:"craft.NativeSidebarItem",props:[{name:"id",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"icon",type:"string",required:!1},{name:"badge",type:"string",required:!1},{name:"tintColor",type:"color",required:!1}],children:"none",platform:["macos"],fallback:"button"}],["craft-accordion",{name:"Accordion",zigType:"craft.Accordion",props:[{name:"title",type:"string",required:!0},{name:"open",type:"boolean",required:!1,default:!1}],children:"multiple"}],["craft-tabs",{name:"TabView",zigType:"craft.TabView",props:[{name:"activeTab",type:"number",required:!1,default:0},{name:"ontabchange",type:"callback",required:!1}],children:"multiple"}],["craft-tooltip",{name:"Tooltip",zigType:"craft.Tooltip",props:[{name:"content",type:"string",required:!0},{name:"position",type:"string",required:!1,default:"top"}],children:"single"}],["craft-date-picker",{name:"DatePicker",zigType:"craft.DatePicker",props:[{name:"value",type:"string",required:!1},{name:"min",type:"string",required:!1},{name:"max",type:"string",required:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-time-picker",{name:"TimePicker",zigType:"craft.TimePicker",props:[{name:"value",type:"string",required:!1},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-color-picker",{name:"ColorPicker",zigType:"craft.ColorPicker",props:[{name:"value",type:"color",required:!1,default:"#000000"},{name:"onchange",type:"callback",required:!1}],children:"none"}],["craft-data-table",{name:"DataTable",zigType:"craft.DataTable",props:[{name:"data",type:"array",required:!0},{name:"columns",type:"array",required:!0},{name:"sortable",type:"boolean",required:!1,default:!1},{name:"paginated",type:"boolean",required:!1,default:!1}],children:"none"}],["craft-virtual-list",{name:"VirtualList",zigType:"craft.VirtualList",props:[{name:"items",type:"array",required:!0},{name:"itemHeight",type:"number",required:!1,default:48},{name:"renderItem",type:"callback",required:!0}],children:"none"}],["craft-tree-view",{name:"TreeView",zigType:"craft.TreeView",props:[{name:"data",type:"object",required:!0},{name:"expandable",type:"boolean",required:!1,default:!0}],children:"none"}]]);async function Zo(e,t={}){let r=performance.now(),n={target:t.target||"universal",format:t.format||"zig",optimize:t.optimize??!0,treeShake:t.treeShake??!0,hotReload:t.hotReload??!1,debug:t.debug??!1,sourceMaps:t.sourceMaps??!1,bundle:t.bundle??!0,minify:t.minify??!1,components:t.components||cs},i=typeof e==="string"?w(e):e,o=I(i.tree,n),s=L(o),a=n.treeShake?O(o,s):o,l=new Map;if(n.target==="universal"){let c=["macos","windows","linux","ios","android"];for(let g of c){let q=u(a,{...n,target:g});l.set(g,q)}}else{let c=u(a,n);l.set(n.target,c)}let p=H(a,n,l),S=_(i,a,n),k={compilationTime:performance.now()-r,totalComponents:f(i.tree),nativeComponents:d(a),webComponents:f(i.tree)-d(a),bundleSize:p.length,treeShakenSize:n.treeShake?W(o,a):p.length,warnings:[],errors:[]},m;if(n.sourceMaps)m=B(i,a);return{code:p,platformCode:l,dependencies:s,manifest:S,sourceMaps:m,stats:k}}function w(e){let t={type:"fragment",children:[]},r=e.match(/<body[^>]*>([\s\S]*?)<\/body>/i),n=r?r[1]:e;return b(n,t),{id:T(),hash:x(e),tree:t,scripts:U(e),styles:Z(e),staticParts:new Map,dynamicParts:new Map,dependencies:[],metadata:{hasSlots:!1,hasDynamicContent:e.includes("{{"),hasEventHandlers:e.includes("onclick")||e.includes("onchange"),hasAsyncContent:!1,componentCount:0,maxDepth:0,estimatedSize:e.length}}}function b(e,t){let r=/<(@?[\w-]+)([^>]*)(?:\/>|>([\s\S]*?)<\/\1>)/g,n;while((n=r.exec(e))!==null){let[,i,o,s]=n,a=i.startsWith("@craft-"),l={type:a?"component":"element",tag:a?i.slice(1):i,props:z(o),children:[],componentName:a?i.slice(1):void 0};if(s){let p=s.replace(/<[^>]+>/g,"").trim();if(p)l.children=l.children??[],l.children.push({type:"text",text:p});b(s,l)}t.children=t.children??[],t.children.push(l)}}function z(e){let t={},r=/([\w-:@]+)(?:=["']([^"']*)["'])?/g,n;while((n=r.exec(e))!==null){let[,i,o]=n;t[i]=o??!0}return t}function I(e,t){return h(e,t)}function h(e,t){let r=e.componentName?t.components?.get(e.componentName):void 0,n="craft.View";if(r)n=r.zigType;else if(e.type==="text")n="craft.Text";else if(e.tag)n=R(e.tag);let i={};if(e.props)for(let[l,p]of Object.entries(e.props))i[l]=M(p);let o=[];if(e.children)for(let l of e.children)o.push(h(l,t));let s=new Map;if(e.props){for(let[l,p]of Object.entries(e.props))if(l.startsWith("on")&&typeof p==="string")s.set(l.slice(2).toLowerCase(),p)}let a=V(e);return{type:A(e,r),zigType:n,props:i,children:o,events:s,styles:a,id:e.hydrationKey,key:e.props?.key}}function R(e){return{div:"craft.View",span:"craft.Text",p:"craft.Text",h1:"craft.Text",h2:"craft.Text",h3:"craft.Text",h4:"craft.Text",h5:"craft.Text",h6:"craft.Text",button:"craft.Button",input:"craft.TextInput",textarea:"craft.TextArea",select:"craft.Select",img:"craft.Image",a:"craft.Link",ul:"craft.List",ol:"craft.List",li:"craft.ListItem",form:"craft.Form",label:"craft.Label",nav:"craft.View",header:"craft.View",footer:"craft.View",main:"craft.View",section:"craft.View",article:"craft.View",aside:"craft.View"}[e.toLowerCase()]||"craft.View"}function M(e){if(typeof e==="string"){if(e.startsWith("{{")&&e.endsWith("}}"))return{type:"binding",path:e.slice(2,-2).trim()};if(e.includes("(")&&e.includes(")"))return{type:"callback",handler:e};return{type:"literal",value:e}}if(typeof e==="number"||typeof e==="boolean")return{type:"literal",value:e};return{type:"literal",value:String(e)}}function A(e,t){if(t){let n=t.name.toLowerCase();if(n.includes("button"))return"button";if(n.includes("input")||n.includes("text"))return"input";if(n.includes("image")||n.includes("avatar"))return"image";if(n.includes("list")||n.includes("table"))return"list";if(n.includes("scroll"))return"scroll";return"custom"}if(e.type==="text")return"text";let r=e.tag?.toLowerCase();if(r==="button")return"button";if(r==="input"||r==="textarea")return"input";if(r==="img")return"image";if(r==="ul"||r==="ol")return"list";return"view"}function V(e){let t=e.props?.style,r={},n={};if(t){let i=t.split(";").filter(Boolean);for(let o of i){let[s,a]=o.split(":").map((l)=>l.trim());if(!s||!a)continue;switch(s){case"display":r.display=a;break;case"flex-direction":r.flexDirection=a;break;case"justify-content":r.justifyContent=j(a);break;case"align-items":r.alignItems=D(a);break;case"gap":r.gap=Number.parseInt(a,10);break;case"padding":r.padding=Number.parseInt(a,10);break;case"margin":r.margin=Number.parseInt(a,10);break;case"width":r.width=a==="auto"?"auto":Number.parseInt(a,10);break;case"height":r.height=a==="auto"?"auto":Number.parseInt(a,10);break;case"background-color":case"background":n.backgroundColor=a;break;case"border-color":n.borderColor=a;break;case"border-width":n.borderWidth=Number.parseInt(a,10);break;case"border-radius":n.borderRadius=Number.parseInt(a,10);break;case"opacity":n.opacity=Number.parseFloat(a);break}}}return{layout:r,appearance:n}}function j(e){return{"flex-start":"start","flex-end":"end",center:"center","space-between":"between","space-around":"around"}[e]||"start"}function D(e){return{"flex-start":"start","flex-end":"end",center:"center",stretch:"stretch"}[e]||"start"}function L(e){let t=[],r=new Set;function n(i,o){let s=i.id||T();if(r.has(s))return;r.add(s);let a={id:s,type:"component",path:i.zigType,dependencies:o?[o]:[],size:C(i),isStatic:P(i)};t.push(a);for(let l of i.children)n(l,s)}return n(e),t}function C(e){let t=100;return t+=Object.keys(e.props).length*20,t+=e.events.size*50,t}function P(e){for(let t of Object.values(e.props))if(t.type!=="literal")return!1;return e.events.size===0}function O(e,t){return e}function W(e,t){let r=0;function n(i){r+=C(i);for(let o of i.children)n(o)}return n(t),r}function u(e,t){switch(t.format){case"zig":return y(e,t);case"typescript":return E(e,t);case"json":return JSON.stringify(e,null,t.minify?0:2);default:return y(e,t)}}function y(e,t){let r=[];return r.push("// Auto-generated by stx compiler"),r.push("// Target: "+t.target),r.push(""),r.push('const std = @import("std");'),r.push('const craft = @import("craft");'),r.push(""),r.push("pub fn render(allocator: std.mem.Allocator) !craft.Element {"),r.push(" return try build(allocator);"),r.push("}"),r.push(""),N(e,r,0),r.join(`
3
3
  `)}function N(e,t,r){let n=" ".repeat(r);if(r===0)t.push("fn build(allocator: std.mem.Allocator) !craft.Element {");let i=`node_${r}`;t.push(`${n} var ${i} = try ${e.zigType}.init(allocator);`);for(let[o,s]of Object.entries(e.props))if(s.type==="literal"){let a=typeof s.value==="string"?`"${s.value}"`:String(s.value);t.push(`${n} ${i}.set${J(o)}(${a});`)}for(let o=0;o<e.children.length;o++){let s=e.children[o];if(s.type==="text"){let a=s.props.text?.type==="literal"?String(s.props.text.value):"";t.push(`${n} try ${i}.addChild(try craft.Text.init(allocator, "${a}"));`)}else N(s,t,r+1),t.push(`${n} try ${i}.addChild(node_${r+1});`)}if(r===0)t.push(` return ${i}.element();`),t.push("}")}function E(e,t){let r=[];return r.push("// Auto-generated by stx compiler"),r.push("// Target: "+t.target),r.push(""),r.push('import { Craft } from "@stacksjs/craft";'),r.push(""),r.push("export function render(): Craft.Element {"),r.push(" return "+v(e,1)+";"),r.push("}"),r.join(`
4
4
  `)}function v(e,t){let r=" ".repeat(t),n=[];for(let[a,l]of Object.entries(e.props))if(l.type==="literal"){let p=typeof l.value==="string"?`"${l.value}"`:String(l.value);n.push(`${a}: ${p}`)}let i=n.length>0?`{ ${n.join(", ")} }`:"{}",o=e.children.map((a)=>a.type==="text"?`"${a.props.text?.type==="literal"?a.props.text.value:""}"`:v(a,t+1)),s=o.length>0?`,
5
5
  ${r} [${o.join(`,
6
6
  ${r} `)}]`:"";return`Craft.create("${e.zigType}", ${i}${s})`}function H(e,t,r){if(t.target==="universal"){let n=[];n.push("// Universal entry point"),n.push("");for(let[i,o]of r)n.push(`// --- ${i.toUpperCase()} ---`),n.push(`#if ${i.toUpperCase()}`),n.push(o),n.push("#endif"),n.push("");return n.join(`
7
- `)}return r.get(t.target)||u(e,t)}function _(e,t,r){let n=[];function i(o){n.push({name:o.zigType,hash:x(JSON.stringify(o.props)),props:Object.keys(o.props),events:Array.from(o.events.keys()),slots:[],isNative:o.zigType.startsWith("craft.")});for(let s of o.children)i(s)}return i(t),{version:"1.0.0",components:n,entry:e.id,assets:[],styles:e.styles}}function B(e,t){return JSON.stringify({version:3,file:"output.zig",sources:["input.stx"],mappings:""})}var F=0;function T(){return`id_${++F}`}function x(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return Math.abs(t).toString(36)}function J(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(e){let t=[],r=/<script[^>]*>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);return t}function Z(e){let t=[],r=/<style[^>]*>([\s\S]*?)<\/style>/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);return t}function f(e){let t=e.type==="component"?1:0;if(e.children)for(let r of e.children)t+=f(r);return t}function d(e){let t=e.zigType.startsWith("craft.")?1:0;for(let r of e.children)t+=d(r);return t}function Zo(e){return{start:async()=>{console.log("[craft-compiler] Hot reload server started")},stop:async()=>{console.log("[craft-compiler] Hot reload server stopped")},notifyChange:(t)=>{console.log(`[craft-compiler] File changed: ${t}`)}}}var K={compileToNative:Yo,createHotReloadServer:Zo,NATIVE_COMPONENTS:cs},Ku=K;
8
- export{cs,Yo,Zo,Ku};
7
+ `)}return r.get(t.target)||u(e,t)}function _(e,t,r){let n=[];function i(o){n.push({name:o.zigType,hash:x(JSON.stringify(o.props)),props:Object.keys(o.props),events:Array.from(o.events.keys()),slots:[],isNative:o.zigType.startsWith("craft.")});for(let s of o.children)i(s)}return i(t),{version:"1.0.0",components:n,entry:e.id,assets:[],styles:e.styles}}function B(e,t){return JSON.stringify({version:3,file:"output.zig",sources:["input.stx"],mappings:""})}var F=0;function T(){return`id_${++F}`}function x(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return Math.abs(t).toString(36)}function J(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(e){let t=[],r=/<script[^>]*>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);return t}function Z(e){let t=[],r=/<style[^>]*>([\s\S]*?)<\/style>/gi,n;while((n=r.exec(e))!==null)t.push(n[1]);return t}function f(e){let t=e.type==="component"?1:0;if(e.children)for(let r of e.children)t+=f(r);return t}function d(e){let t=e.zigType.startsWith("craft.")?1:0;for(let r of e.children)t+=d(r);return t}function Qo(e){return{start:async()=>{console.log("[craft-compiler] Hot reload server started")},stop:async()=>{console.log("[craft-compiler] Hot reload server stopped")},notifyChange:(t)=>{console.log(`[craft-compiler] File changed: ${t}`)}}}var K={compileToNative:Zo,createHotReloadServer:Qo,NATIVE_COMPONENTS:cs},Ju=K;
8
+ export{cs,Zo,Qo,Ju};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{hc,yc,pe,bc,li,Tt,$t,Yu,ui,Rt,hn,vc,wc,xc,ds,At,Sc,Pt,kc}from"./chunk-27784ceh.js";import"./chunk-8kc6byaz.js";import"./chunk-gh34r6qb.js";import"./chunk-0xc6rncm.js";import"./chunk-jzmz66a3.js";import"./chunk-kpxty3pe.js";import"./chunk-2bxsc7gf.js";import"./chunk-cy1j2zpr.js";import"./chunk-xrrkf04f.js";import"./chunk-6bhaa9g7.js";import"./chunk-8b2452m1.js";import"./chunk-8qrhz7n7.js";import"./chunk-4fv3jq16.js";import"./chunk-d2t2pq1s.js";import"./chunk-y89m80pf.js";import"./chunk-3kkf43fv.js";export{hn as MODULE_SPECIFIER_PREFIX,hc as bundleCacheDir,yc as bundleCacheEntryLimit,Pt as bundleClientScript,$t as clearBundleFailures,pe as clientBundleDependencies,Tt as getBundleFailures,Rt as hasUserImports,At as moduleSubstitutionKey,wc as normalizeRegistrySpecifiers,Sc as queueClientBundleBuild,li as recordBundleFailure,vc as registryIdForPath,ui as resolveBundlerFallback,xc as rewriteRegistryImports,Yu as setBundlerFallbackMode,bc as shouldLogBundlerDiagnostics,kc as tempBuildName,ds as withModuleSubstitutes};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{u,Os,Pi,Ii,Yc,Zc,Qc,el,tl,zs,nl,nt,B,rt,rl,gr,sl,Mi,Hs,st,r,mr,Li,g,ie,xd}from"./chunk-0xc6rncm.js";import"./chunk-jzmz66a3.js";import"./chunk-kpxty3pe.js";import"./chunk-2bxsc7gf.js";import"./chunk-cy1j2zpr.js";import"./chunk-xrrkf04f.js";import"./chunk-6bhaa9g7.js";import"./chunk-8b2452m1.js";import"./chunk-8qrhz7n7.js";import"./chunk-4fv3jq16.js";import"./chunk-d2t2pq1s.js";import"./chunk-y89m80pf.js";import"./chunk-3kkf43fv.js";export{ie as clearComponentCache,Hs as componentClientSignalNames,Os as convertToCommonJS,g as createDetailedErrorMessage,tl as extractDirectiveNames,Pi as extractScriptFromTemplate,u as extractVariables,r as fileExists,xd as getComponentCacheStats,Zc as getPositionInfo,B as getSharedTranspiler,Li as getSourceLineInfo,el as hasDirectives,Ii as hasVariables,sl as isHydrateTrigger,nl as isJavaScriptScript,st as renderComponentWithSlot,mr as resolveTemplatePath,rl as scopeOnRootElement,zs as scopeSequenceKey,nt as shouldTranspileTypeScript,Mi as slotContentHasExpressions,rt as transpileTypeScript,gr as userComponentFileExists,Qc as validateDirective,Yc as validateTemplate};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Me,Le,je}from"./chunk-k2nrx78c.js";import"./chunk-rns21kkv.js";import"./chunk-4fv3jq16.js";import{u}from"./chunk-b5cv9xp7.js";import"./chunk-9b4e815s.js";import"./chunk-2wvz3fd2.js";import"./chunk-d1ya7f79.js";import"./chunk-evs5gb3q.js";import"./chunk-7ky2ny63.js";import"./chunk-nz6bzffm.js";import"./chunk-3p2b88pd.js";import"./chunk-70npkeh2.js";import"./chunk-1ma56c2h.js";import{bt,Dr,vt,uo,De,po,Mr,wt,go,xt}from"./chunk-85g35me6.js";import"./chunk-62kxavc5.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{po("Config file changed, restarting...");try{await e.onChange()}catch(p){De(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:dt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function dt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
2
+ import{Me,Le,je}from"./chunk-k2nrx78c.js";import"./chunk-d2t2pq1s.js";import"./chunk-4fv3jq16.js";import{u}from"./chunk-0xc6rncm.js";import"./chunk-8qrhz7n7.js";import"./chunk-kpxty3pe.js";import"./chunk-y89m80pf.js";import"./chunk-8b2452m1.js";import"./chunk-6bhaa9g7.js";import"./chunk-2bxsc7gf.js";import"./chunk-xrrkf04f.js";import"./chunk-cy1j2zpr.js";import"./chunk-3kkf43fv.js";import{bt,Dr,vt,po,De,fo,Mr,wt,mo,xt}from"./chunk-p77g4mhy.js";import"./chunk-jzmz66a3.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{fo("Config file changed, restarting...");try{await e.onChange()}catch(p){De(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:dt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function dt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
3
3
  <script>
4
4
  (function() {
5
5
  const ws = new WebSocket('${t}');
@@ -556,9 +556,9 @@ window.__stxPerformance = {
556
556
 
557
557
  window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
558
558
  </script>
559
- `}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-wfp754ya.js"),p={},g=h(n);if(g)try{await u(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function gt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await u(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await gt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return ft(t,a.source,c);return b(t,e.path,{props:c})}async function ft(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-wfp754ya.js"),c={...r},n=h(e);if(n)try{await u(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
559
+ `}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-rrdwynz4.js"),p={},g=h(n);if(g)try{await u(g,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function gt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await u(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await gt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return ft(t,a.source,c);return b(t,e.path,{props:c})}async function ft(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-rrdwynz4.js"),c={...r},n=h(e);if(n)try{await u(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
560
560
  `)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
561
- `)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function rt(t,e){let r=await wt(t);Le(t,r);let s=xt(t.config,r);je(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return yt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return ht(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),g=`http://${o}:${e.port}`,y=go(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await wt(t);Le(t,m);let f=xt(t.config,m);if(je(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=g;try{let{exec:l}=await import("child_process"),m=process.platform;l(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:g,close:async()=>{y(),p.stop()}}}async function yt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],g=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((m)=>m.id===p);if(!l)return new Response("Story not found",{status:404});try{let m=await Y(t,l,g,y);return Response.json({html:m.html,css:m.css,js:m.js,errors:m.errors,duration:m.duration})}catch(m){return Response.json({html:"",css:"",js:"",errors:[m instanceof Error?m.message:String(m)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((g)=>g.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function ht(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
561
+ `)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function rt(t,e){let r=await wt(t);Le(t,r);let s=xt(t.config,r);je(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return yt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return ht(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),g=`http://${o}:${e.port}`,y=mo(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await wt(t);Le(t,m);let f=xt(t.config,m);if(je(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=g;try{let{exec:l}=await import("child_process"),m=process.platform;l(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:g,close:async()=>{y(),p.stop()}}}async function yt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],g=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((m)=>m.id===p);if(!l)return new Response("Story not found",{status:404});try{let m=await Y(t,l,g,y);return Response.json({html:m.html,css:m.css,js:m.js,errors:m.errors,duration:m.duration})}catch(m){return Response.json({html:"",css:"",js:"",errors:[m instanceof Error?m.message:String(m)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((g)=>g.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function ht(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
562
562
  <html lang="en" class="${r.darkClass||"dark"}">
563
563
  <head>
564
564
  <meta charset="UTF-8">
@@ -1277,4 +1277,4 @@ else {
1277
1277
  ${D()}
1278
1278
  </body>
1279
1279
  </html>`}import St from"fs";import Pt from"path";var Ct=new Map,Tt=[],Rt=[],It=new Map;async function ot(t){let e=t.config.setupFile;if(!e)return;let r=Pt.resolve(t.root,e);try{await St.promises.access(r)}catch{return}let s={storyContext:t,registerComponent:(o,a)=>{Ct.set(o,a)},addCSS:(o)=>{Tt.push(o)},addScript:(o)=>{Rt.push(o)},setState:(o,a)=>{It.set(o,a)}};try{let o=await import(r);if(typeof o.default==="function")await o.default(s);else if(typeof o.setupStory==="function")await o.setupStory(s)}catch(o){console.warn(`Warning: Failed to load setup file: ${o}`)}}async function he(t={}){bt();let e=await Me({mode:"dev"});if(!e.config.enabled){De("Story feature is disabled in config.");return}await ot(e);let r=t.port??e.config.port,s,o=async()=>{s=await rt(e,{port:r,open:t.open,host:t.host}),vt(e.storyFiles.length),Dr(s.url),Mr()};await o();let a=E(e,{onChange:async()=>{await s.close();let n=await Me({mode:"dev"});Object.assign(e,n),await o()}}),c=async()=>{console.log(`
1280
- `),a.stop(),await s.close(),process.exit(0)};if(process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",async(n)=>{switch(n.toString()){case"h":Mr();break;case"o":try{let{exec:p}=await import("child_process"),g=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";p(`${g} ${s.url}`)}catch{uo("Failed to open browser")}break;case"r":await s.close(),await o();break;case"c":console.clear(),bt(),vt(e.storyFiles.length),Dr(s.url);break;case"q":case"\x03":await c();break}});await new Promise(()=>{})}export{he as devCommand};
1280
+ `),a.stop(),await s.close(),process.exit(0)};if(process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",async(n)=>{switch(n.toString()){case"h":Mr();break;case"o":try{let{exec:p}=await import("child_process"),g=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";p(`${g} ${s.url}`)}catch{po("Failed to open browser")}break;case"r":await s.close(),await o();break;case"c":console.clear(),bt(),vt(e.storyFiles.length),Dr(s.url);break;case"q":case"\x03":await c();break}});await new Promise(()=>{})}export{he as devCommand};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{mu,hu,yu,bu,vu}from"./chunk-86zj56pf.js";export{hu as createSSRSuspense,bu as generateSuspenseCSS,vu as generateSuspenseRuntime,mu as processSuspenseDirectives,yu as renderSSRSuspense};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{xl}from"./chunk-g2rxbaah.js";import"./chunk-0xc6rncm.js";import"./chunk-jzmz66a3.js";import"./chunk-kpxty3pe.js";import"./chunk-2bxsc7gf.js";import"./chunk-cy1j2zpr.js";import"./chunk-xrrkf04f.js";import"./chunk-6bhaa9g7.js";import"./chunk-8b2452m1.js";import"./chunk-8qrhz7n7.js";import"./chunk-4fv3jq16.js";import"./chunk-d2t2pq1s.js";import"./chunk-y89m80pf.js";import"./chunk-3kkf43fv.js";export{xl as startInteractive};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Fr,ko,Gn,zr,Hr,Kt,St,_o,Kn,Xn,Vr,Ur,kl,_l,Be}from"./chunk-72p9brmx.js";export{Be as DeployError,ko as calculateSha1,Gn as collectDeployFiles,Xn as createDefaultNetlifyConfig,zr as createFileManifest,Fr as createNetlifyClient,kl as deploy,Kn as detectProjectConfig,Hr as filterRequiredFiles,Kt as formatSize,_o as generateNetlifyToml,St as getTotalSize,Ur as hasNetlifyConfig,_l as initNetlify,Vr as writeNetlifyConfig};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- function Fo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="id",dynamicHeight:d=!1,estimatedItemHeight:g=l,direction:x="vertical"}=c,e=[...v],t=0,n=new Map;function f(){if(d)return h();let i=Math.max(0,Math.floor(t/l)-s),r=Math.ceil(u/l),m=Math.min(e.length-1,i+r+s*2);return{startIndex:i,endIndex:m}}function h(){let i=0,r=0,m=e.length-1;for(let p=0;p<e.length;p++){let M=n.get(p)||g;if(i+M>t){r=Math.max(0,p-s);break}i+=M}i=0;for(let p=0;p<e.length;p++){let M=n.get(p)||g;if(i+=M,i>t+u){m=Math.min(e.length-1,p+s);break}}return{startIndex:r,endIndex:m}}function w(){if(d){let i=0;for(let r=0;r<e.length;r++)i+=n.get(r)||g;return i}return e.length*l}function y(i){if(d){let r=0;for(let m=0;m<i;m++)r+=n.get(m)||g;return r}return i*l}function S(){let{startIndex:i,endIndex:r}=f();return{startIndex:i,endIndex:r,scrollTop:t,totalHeight:w(),visibleItems:e.slice(i,r+1),itemHeights:new Map(n)}}function L(i,r="auto"){let m=y(i);a(m,r)}function a(i,r="auto"){t=Math.max(0,Math.min(i,w()-u))}function o(){f()}function H(i){e=[...i],n.clear(),o()}function I(){e=[],n.clear()}return{scrollToIndex:L,scrollToOffset:a,getState:S,refresh:o,setItems:H,destroy:I}}function zo(v,c={},l){let u=/@virtualList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualList/gi;return v.replace(u,(s,b,d,g)=>{let x=b.trim(),e=c[x];if(!e||!Array.isArray(e))return`<!-- virtualList: items "${x}" not found or not an array -->`;let t={itemHeight:50,containerHeight:400,overscan:3};if(d)try{let a=d.trim(),o=Function(`return ${a}`)();t={...t,...o}}catch{}let n=`vlist-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(t.containerHeight/t.itemHeight),h=t.overscan||3,w=0,y=Math.min(e.length-1,f+h),S="";for(let a=w;a<=y&&a<e.length;a++){let o=e[a],H=g.replace(/\{\{\s*item\s*\}\}/g,typeof o==="object"?JSON.stringify(o):String(o)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(I,i)=>{if(typeof o==="object"&&o!==null)return String(o[i]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(a));S+=`
2
+ function zo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="id",dynamicHeight:d=!1,estimatedItemHeight:g=l,direction:x="vertical"}=c,e=[...v],t=0,n=new Map;function f(){if(d)return h();let i=Math.max(0,Math.floor(t/l)-s),r=Math.ceil(u/l),m=Math.min(e.length-1,i+r+s*2);return{startIndex:i,endIndex:m}}function h(){let i=0,r=0,m=e.length-1;for(let p=0;p<e.length;p++){let M=n.get(p)||g;if(i+M>t){r=Math.max(0,p-s);break}i+=M}i=0;for(let p=0;p<e.length;p++){let M=n.get(p)||g;if(i+=M,i>t+u){m=Math.min(e.length-1,p+s);break}}return{startIndex:r,endIndex:m}}function w(){if(d){let i=0;for(let r=0;r<e.length;r++)i+=n.get(r)||g;return i}return e.length*l}function y(i){if(d){let r=0;for(let m=0;m<i;m++)r+=n.get(m)||g;return r}return i*l}function S(){let{startIndex:i,endIndex:r}=f();return{startIndex:i,endIndex:r,scrollTop:t,totalHeight:w(),visibleItems:e.slice(i,r+1),itemHeights:new Map(n)}}function L(i,r="auto"){let m=y(i);a(m,r)}function a(i,r="auto"){t=Math.max(0,Math.min(i,w()-u))}function o(){f()}function H(i){e=[...i],n.clear(),o()}function I(){e=[],n.clear()}return{scrollToIndex:L,scrollToOffset:a,getState:S,refresh:o,setItems:H,destroy:I}}function Ho(v,c={},l){let u=/@virtualList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualList/gi;return v.replace(u,(s,b,d,g)=>{let x=b.trim(),e=c[x];if(!e||!Array.isArray(e))return`<!-- virtualList: items "${x}" not found or not an array -->`;let t={itemHeight:50,containerHeight:400,overscan:3};if(d)try{let a=d.trim(),o=Function(`return ${a}`)();t={...t,...o}}catch{}let n=`vlist-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(t.containerHeight/t.itemHeight),h=t.overscan||3,w=0,y=Math.min(e.length-1,f+h),S="";for(let a=w;a<=y&&a<e.length;a++){let o=e[a],H=g.replace(/\{\{\s*item\s*\}\}/g,typeof o==="object"?JSON.stringify(o):String(o)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(I,i)=>{if(typeof o==="object"&&o!==null)return String(o[i]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(a));S+=`
3
3
  <div class="virtual-item ${t.itemClass||""}"
4
4
  style="position: absolute; top: ${a*t.itemHeight}px; height: ${t.itemHeight}px; width: 100%;"
5
5
  data-index="${a}">
@@ -76,7 +76,7 @@ function Fo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="
76
76
  };
77
77
  })();
78
78
  </script>
79
- `})}function za(){return`
79
+ `})}function Ha(){return`
80
80
  .virtual-list-container {
81
81
  position: relative;
82
82
  overflow-y: auto;
@@ -124,7 +124,7 @@ function Fo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="
124
124
  0% { background-position: 200% 0; }
125
125
  100% { background-position: -200% 0; }
126
126
  }
127
- `}function Ha(v,c){let l=null,u=()=>{if(!l)l=Fo(v(),c);return l};return{visibleItems:()=>u().getState().visibleItems,totalHeight:()=>u().getState().totalHeight,containerProps:()=>({style:{height:`${c.containerHeight}px`,overflow:"auto",position:"relative"},onScroll:(s)=>{let b=s.target;if(l)l.scrollToOffset(b.scrollTop)}}),itemProps:(s)=>({style:{position:"absolute",top:`${s*c.itemHeight}px`,height:`${c.itemHeight}px`,width:"100%"},"data-index":s}),scrollToIndex:(s)=>{u().scrollToIndex(s)}}}function Va(v,c={},l){let u=/@infiniteList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@loading\s*([\s\S]*?)@endinfiniteList/gi;return v.replace(u,(s,b,d,g,x)=>{let e=b.trim(),t=c[e];if(!t||!Array.isArray(t))return`<!-- infiniteList: items "${e}" not found or not an array -->`;let n={itemHeight:50,containerHeight:400,overscan:3,threshold:100,hasMore:!0};if(d)try{let w=Function(`return ${d.trim()}`)();n={...n,...w}}catch{}let f=`ilist-${Math.random().toString(36).substring(2,9)}`,h=zo(`@virtualList(${e}, ${JSON.stringify({itemHeight:n.itemHeight,containerHeight:n.containerHeight,overscan:n.overscan,containerClass:n.containerClass})})${g}@endvirtualList`,c);return h=h.replace("</script>",`
127
+ `}function Va(v,c){let l=null,u=()=>{if(!l)l=zo(v(),c);return l};return{visibleItems:()=>u().getState().visibleItems,totalHeight:()=>u().getState().totalHeight,containerProps:()=>({style:{height:`${c.containerHeight}px`,overflow:"auto",position:"relative"},onScroll:(s)=>{let b=s.target;if(l)l.scrollToOffset(b.scrollTop)}}),itemProps:(s)=>({style:{position:"absolute",top:`${s*c.itemHeight}px`,height:`${c.itemHeight}px`,width:"100%"},"data-index":s}),scrollToIndex:(s)=>{u().scrollToIndex(s)}}}function Ua(v,c={},l){let u=/@infiniteList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@loading\s*([\s\S]*?)@endinfiniteList/gi;return v.replace(u,(s,b,d,g,x)=>{let e=b.trim(),t=c[e];if(!t||!Array.isArray(t))return`<!-- infiniteList: items "${e}" not found or not an array -->`;let n={itemHeight:50,containerHeight:400,overscan:3,threshold:100,hasMore:!0};if(d)try{let w=Function(`return ${d.trim()}`)();n={...n,...w}}catch{}let f=`ilist-${Math.random().toString(36).substring(2,9)}`,h=Ho(`@virtualList(${e}, ${JSON.stringify({itemHeight:n.itemHeight,containerHeight:n.containerHeight,overscan:n.overscan,containerClass:n.containerClass})})${g}@endvirtualList`,c);return h=h.replace("</script>",`
128
128
  // Infinite scroll detection
129
129
  container.addEventListener('scroll', function() {
130
130
  const scrollBottom = container.scrollTop + container.clientHeight;
@@ -142,7 +142,7 @@ function Fo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="
142
142
  ${x}
143
143
  </div>
144
144
  </div>
145
- `})}function Ua(v,c={},l){let u=/@virtualGrid\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualGrid/gi;return v.replace(u,(s,b,d,g)=>{let x=b.trim(),e=c[x];if(!e||!Array.isArray(e))return`<!-- virtualGrid: items "${x}" not found or not an array -->`;let t={columns:3,rowHeight:100,containerHeight:400,gap:10,overscan:2};if(d)try{let o=Function(`return ${d.trim()}`)();t={...t,...o}}catch{}let n=`vgrid-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(e.length/t.columns),h=f*(t.rowHeight+(t.gap||0)),w=Math.ceil(t.containerHeight/(t.rowHeight+(t.gap||0))),y=t.overscan||2,S=0,L=Math.min(f-1,w+y),a="";for(let o=S;o<=L;o++)for(let H=0;H<t.columns;H++){let I=o*t.columns+H;if(I>=e.length)break;let i=e[I],r=H*(100/t.columns),m=o*(t.rowHeight+(t.gap||0)),p=g.replace(/\{\{\s*item\s*\}\}/g,typeof i==="object"?JSON.stringify(i):String(i)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(M,T)=>{if(typeof i==="object"&&i!==null)return String(i[T]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(I));a+=`
145
+ `})}function Wa(v,c={},l){let u=/@virtualGrid\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualGrid/gi;return v.replace(u,(s,b,d,g)=>{let x=b.trim(),e=c[x];if(!e||!Array.isArray(e))return`<!-- virtualGrid: items "${x}" not found or not an array -->`;let t={columns:3,rowHeight:100,containerHeight:400,gap:10,overscan:2};if(d)try{let o=Function(`return ${d.trim()}`)();t={...t,...o}}catch{}let n=`vgrid-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(e.length/t.columns),h=f*(t.rowHeight+(t.gap||0)),w=Math.ceil(t.containerHeight/(t.rowHeight+(t.gap||0))),y=t.overscan||2,S=0,L=Math.min(f-1,w+y),a="";for(let o=S;o<=L;o++)for(let H=0;H<t.columns;H++){let I=o*t.columns+H;if(I>=e.length)break;let i=e[I],r=H*(100/t.columns),m=o*(t.rowHeight+(t.gap||0)),p=g.replace(/\{\{\s*item\s*\}\}/g,typeof i==="object"?JSON.stringify(i):String(i)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(M,T)=>{if(typeof i==="object"&&i!==null)return String(i[T]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(I));a+=`
146
146
  <div class="virtual-grid-item"
147
147
  style="position: absolute; top: ${m}px; left: ${r}%; width: calc(${100/t.columns}% - ${t.gap||0}px); height: ${t.rowHeight}px;"
148
148
  data-index="${I}">
@@ -212,5 +212,5 @@ function Fo(v,c){let{itemHeight:l,containerHeight:u,overscan:s=3,keyProperty:b="
212
212
  });
213
213
  })();
214
214
  </script>
215
- `})}var Zl={createVirtualList:Fo,processVirtualListDirectives:zo,processInfiniteListDirectives:Va,processVirtualGridDirectives:Ua,generateVirtualListCSS:za,useVirtualList:Ha};
216
- export{Fo,zo,za,Ha,Va,Ua,Zl};
215
+ `})}var eu={createVirtualList:zo,processVirtualListDirectives:Ho,processInfiniteListDirectives:Ua,processVirtualGridDirectives:Wa,generateVirtualListCSS:Ha,useVirtualList:Va};
216
+ export{zo,Ho,Ha,Va,Ua,Wa,eu};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Ve,ln,Tu}from"./chunk-rq1c46zb.js";import{K,un,$u,dn,os,Qn,er,Ru,Au,Pu,pn,fn,is,tr,Iu}from"./chunk-v4tmwamd.js";import"./chunk-d2t2pq1s.js";export{os as batch,Tu as default,un as derived,dn as effect,Ve as generateSignalsRuntime,ln as generateSignalsRuntimeDev,fn as isDerived,pn as isSignal,$u as memo,er as onDestroy,Qn as onMount,tr as peek,Pu as pendingLifecycleCounts,Au as runDestroyCallbacks,Ru as runMountCallbacks,K as state,is as untrack,Iu as useOptimistic};